Commit 6b3ca06f by HlQ

[chg] 使用 Jackson 替代 Hutool 的json

1 parent 737cb2cc
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
<version>1</version> <version>1</version>
<properties> <properties>
<java.version>21</java.version> <java.version>21</java.version>
<hutool.version>6.0.0-M13</hutool.version> <hutool.version>6.0.0-M16</hutool.version>
<redisson.verion>3.32.0</redisson.verion> <redisson.verion>3.32.0</redisson.verion>
<mapstruct-plus.version>1.4.3</mapstruct-plus.version> <mapstruct-plus.version>1.4.3</mapstruct-plus.version>
<mp.version>3.5.7</mp.version> <mp.version>3.5.7</mp.version>
......
...@@ -3,6 +3,7 @@ package vion.controller; ...@@ -3,6 +3,7 @@ package vion.controller;
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.liaochong.myexcel.core.DefaultExcelBuilder; import com.github.liaochong.myexcel.core.DefaultExcelBuilder;
import com.github.liaochong.myexcel.core.watermark.Watermark; import com.github.liaochong.myexcel.core.watermark.Watermark;
import com.github.liaochong.myexcel.utils.WatermarkUtil; import com.github.liaochong.myexcel.utils.WatermarkUtil;
...@@ -14,7 +15,6 @@ import org.dromara.hutool.core.lang.Assert; ...@@ -14,7 +15,6 @@ import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.text.CharSequenceUtil; import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.JSONObject;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import vion.cron.ContractRunner; import vion.cron.ContractRunner;
import vion.dto.ContractDTO; import vion.dto.ContractDTO;
...@@ -116,7 +116,7 @@ public class ContractController { ...@@ -116,7 +116,7 @@ public class ContractController {
@GetMapping("/contract/calAmount") @GetMapping("/contract/calAmount")
@SaCheckPermission(value = "contract:calAmount", orRole = "admin") @SaCheckPermission(value = "contract:calAmount", orRole = "admin")
public JSONObject calAmount(ContractDTO dto) { public JsonNode calAmount(ContractDTO dto) {
return contractService.calAmount(dto); return contractService.calAmount(dto);
} }
...@@ -165,7 +165,7 @@ public class ContractController { ...@@ -165,7 +165,7 @@ public class ContractController {
@GetMapping("/contract/getCRMProduct") @GetMapping("/contract/getCRMProduct")
@SaCheckPermission(value = "contract:CRMProduct", orRole = "admin") @SaCheckPermission(value = "contract:CRMProduct", orRole = "admin")
public JSONObject getCRMProduct(@RequestParam String name, public JsonNode getCRMProduct(@RequestParam String name,
@RequestParam String code, @RequestParam String code,
@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "20") Integer pageSize) { @RequestParam(defaultValue = "20") Integer pageSize) {
......
package vion.cron; package vion.cron;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.collection.CollUtil; import org.dromara.hutool.core.collection.CollUtil;
...@@ -10,8 +11,6 @@ import org.dromara.hutool.core.math.NumberUtil; ...@@ -10,8 +11,6 @@ import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RedissonClient; import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
...@@ -23,11 +22,13 @@ import vion.constant.RedisKeyEnum; ...@@ -23,11 +22,13 @@ import vion.constant.RedisKeyEnum;
import vion.model.Dictionary; import vion.model.Dictionary;
import vion.model.*; import vion.model.*;
import vion.service.*; import vion.service.*;
import vion.utils.JsonUtil;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/** /**
* 从crm系统定时同步合同信息 * 从crm系统定时同步合同信息
...@@ -60,73 +61,77 @@ public class ContractRunner { ...@@ -60,73 +61,77 @@ public class ContractRunner {
Long modifyTime = Opt.ofNullable((Long) redissonClient.getBucket(RedisKeyEnum.CONTRACT_SYNC_NEW_TIME.getVal()).get()).orElse(0L); Long modifyTime = Opt.ofNullable((Long) redissonClient.getBucket(RedisKeyEnum.CONTRACT_SYNC_NEW_TIME.getVal()).get()).orElse(0L);
// 只同步申请日期(原CRM中的签订日期)2024-05-07号(含)之后的合同 // 只同步申请日期(原CRM中的签订日期)2024-05-07号(含)之后的合同
var json = JSONUtil.ofObj() var json = JsonUtil.createObj()
.set("sortMap", JSONUtil.ofObj() .putPOJO("sortMap", JsonUtil.createObj()
.set("field", "updateTime") .put("field", "updateTime")
.set("sort", "desc")) .put("sort", "desc"))
.set("conditions", JSONUtil.ofArray() .putPOJO("conditions", JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("attr", "date_3") .put("attr", "date_3")
.set("symbol", "greaterequal") .put("symbol", "greaterequal")
.set("value", new String[]{"1715356800"})) .putPOJO("value", new String[]{"1715356800"}))
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("attr", "updateTime") .put("attr", "updateTime")
.set("symbol", "greatethan") .put("symbol", "greatethan")
.set("value", new String[]{String.valueOf(modifyTime / 1000)})) .putPOJO("value", new String[]{String.valueOf(modifyTime / 1000)}))
) )
.set("corpid", corpId) .put("corpid", corpId)
.set("formId", 8429903) .put("formId", 8429903)
.set("pageSize", 100); .put("pageSize", 100);
var jobO = bongRestClient.post() var jobO = bongRestClient.post()
.uri("/pro/v2/api/contract/list") .uri("/pro/v2/api/contract/list")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json.toString() + token)) .header("sign", SecureUtil.sha256(json.toString() + token))
.body(json.toString()) .body(json.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobO.getInt("code") != 1) { if (ObjUtil.isNull(jobO) || jobO.path("code").asInt() != 1) {
log.error("获取合同列表失败,错误原因:{}", jobO); log.error("获取合同列表失败,错误原因:{}", jobO);
return; return;
} }
Integer cnt = jobO.getJSONObject("result").getInt("totalCount"); var cnt = jobO.path("result").path("totalCount").asInt();
Integer page = jobO.getJSONObject("result").getInt("totalPage"); var page = jobO.path("result").path("totalPage").asInt();
if (NumberUtil.equals(cnt, 0)) { if (NumberUtil.equals(cnt, 0)) {
log.info("没有需要插入或更新的合同"); log.info("没有需要插入或更新的合同");
return; return;
} }
var jsonArray = jobO.getJSONObject("result").getJSONArray("list"); var jsonArray = jobO.path("result").withArray("list");
// 合同记录唯一 dataId // 合同记录唯一 dataId
var dataIdSet = jsonArray.stream().map(v -> JSONUtil.parseObj(v).getInt("dataId")).collect(Collectors.toSet()); var dataIdSet = StreamSupport.stream(jsonArray.spliterator(), false)
.map(v -> v.path("dataId").asInt())
.collect(Collectors.toSet());
for (int i = 2; i <= page; i++) { for (int i = 2; i <= page; i++) {
var jsonR = JSONUtil.ofObj() var jsonR = JsonUtil.createObj()
.set("sortMap", JSONUtil.ofObj() .putPOJO("sortMap", JsonUtil.createObj()
.set("field", "updateTime") .put("field", "updateTime")
.set("sort", "desc")) .put("sort", "desc"))
.set("conditions", JSONUtil.ofArray() .putPOJO("conditions", JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("attr", "date_3") .put("attr", "date_3")
.set("symbol", "greaterequal") .put("symbol", "greaterequal")
.set("value", new String[]{"1715356800"})) .putPOJO("value", new String[]{"1715356800"}))
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("attr", "updateTime") .put("attr", "updateTime")
.set("fieldType", "10015") .put("fieldType", "10015")
.set("symbol", "greatethan") .put("symbol", "greatethan")
.set("value", new String[]{String.valueOf(modifyTime)})) .putPOJO("value", new String[]{String.valueOf(modifyTime)}))
) )
.set("corpid", corpId) .put("corpid", corpId)
.set("formId", 8429903) .put("formId", 8429903)
.set("page", i) .put("page", i)
.set("pageSize", 100); .put("pageSize", 100);
var jobR = bongRestClient.post() var jobR = bongRestClient.post()
.uri("/pro/v2/api/contract/list") .uri("/pro/v2/api/contract/list")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(jsonR.toString() + token)) .header("sign", SecureUtil.sha256(jsonR.toString() + token))
.body(jsonR.toString()) .body(jsonR.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
var jsonArrR = jobR.getJSONObject("result").getJSONArray("list"); var jsonArrR = jobR.path("result").withArray("list");
var dataIdSetR = jsonArrR.stream().map(v -> JSONUtil.parseObj(v).getInt("dataId")).collect(Collectors.toSet()); var dataIdSetR = StreamSupport.stream(jsonArrR.spliterator(), false)
.map(v -> v.path("dataId").asInt())
.collect(Collectors.toSet());
dataIdSet.addAll(dataIdSetR); dataIdSet.addAll(dataIdSetR);
} }
...@@ -140,47 +145,46 @@ public class ContractRunner { ...@@ -140,47 +145,46 @@ public class ContractRunner {
return; return;
} }
dataIdSet.forEach(dataId -> { dataIdSet.forEach(dataId -> {
var json1 = JSONUtil.ofObj() var json1 = JsonUtil.createObj()
.set("corpid", corpId) .put("corpid", corpId)
.set("dataId", dataId); .put("dataId", dataId);
var jobj1 = bongRestClient.post() var jobj1 = bongRestClient.post()
.uri("/pro/v2/api/contract/detail") .uri("/pro/v2/api/contract/detail")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json1.toString() + token)) .header("sign", SecureUtil.sha256(json1.toString() + token))
.body(json1.toString()) .body(json1.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobj1.getInt("code") != 1) { if (ObjUtil.isNull(jobj1) || jobj1.path("code").asInt() != 1) {
log.error("获取合同详情失败,错误原因:{}", jobj1); log.error("获取合同详情失败,错误原因:{}", jobj1);
return; return;
} }
var result = jobj1.getJSONObject("result"); var result = jobj1.path("result");
var jsonObj1 = result.getJSONObject("data"); var jsonObj1 = result.path("data");
Contract contract = new Contract(); Contract contract = new Contract();
contract.setName(jsonObj1.getStr("text_14")); contract.setName(jsonObj1.path("text_14").asText());
contract.setContractNo(jsonObj1.getStr("serialNo")); contract.setContractNo(jsonObj1.path("serialNo").asText());
contract.setType(contractTypeMap.getOrDefault(jsonObj1.getJSONObject("text_17").getStr("text"), 0)); contract.setType(contractTypeMap.getOrDefault(jsonObj1.path("text_17").path("text").asText(), 0));
contract.setSignDate(DateUtil.date(jsonObj1.getLong("date_1") * 1000)); contract.setSignDate(DateUtil.date(jsonObj1.path("date_1").asLong() * 1000));
contract.setMaintainSdate(Opt.ofNullable(jsonObj1.getLong("date_4")).map(sec -> DateUtil.date(sec * 1000)).orElse(null)); contract.setMaintainSdate(Opt.ofNullable(jsonObj1.path("date_4")).filter(JsonNode::isNumber).map(sec -> DateUtil.date(sec.asLong() * 1000)).orElse(null));
contract.setMaintainEdate(Opt.ofNullable(jsonObj1.getLong("date_5")).map(sec -> DateUtil.date(sec * 1000)).orElse(null)); contract.setMaintainEdate(Opt.ofNullable(jsonObj1.path("date_5")).filter(JsonNode::isNumber).map(sec -> DateUtil.date(sec.asLong() * 1000)).orElse(null));
String warrantyPeriod = Opt.ofNullable(jsonObj1.getJSONObject("text_23")).map(wp -> wp.getStr("text")).orElse(""); String warrantyPeriod = jsonObj1.path("text_23").path("text").asText("");
// 23 质保 没有维保开始时间和结束时间 25 维保 // 23 质保 没有维保开始时间和结束时间 25 维保
if (StrUtil.isNotBlank(warrantyPeriod) && warrantyPeriod.contains("个月")) { if (StrUtil.isNotBlank(warrantyPeriod) && warrantyPeriod.contains("个月")) {
String substring = warrantyPeriod.substring(0, (warrantyPeriod.length() - 2)); String substring = warrantyPeriod.substring(0, (warrantyPeriod.length() - 2));
contract.setWarrantyPeriod(Integer.parseInt(substring)); contract.setWarrantyPeriod(Integer.parseInt(substring));
} }
contract.setStatus(1); contract.setStatus(1);
contract.setTotalAmount(jsonObj1.getBigDecimal("num_1")); contract.setTotalAmount(jsonObj1.path("num_1").decimalValue());
contract.setPaidAmount(BigDecimal.ZERO); contract.setPaidAmount(BigDecimal.ZERO);
contract.setReceivableAmount(BigDecimal.ZERO); contract.setReceivableAmount(BigDecimal.ZERO);
contract.setOutstandingAmount(jsonObj1.getBigDecimal("num_1")); contract.setOutstandingAmount(jsonObj1.path("num_1").decimalValue());
var paymentForm = jsonObj1.getJSONArray("subForm_1"); var paymentForm = jsonObj1.withArray("subForm_1");
if (!paymentForm.isEmpty()) { if (!paymentForm.isEmpty()) {
paymentForm.forEach(pf -> { paymentForm.forEach(pf -> {
var pfObj = JSONUtil.parseObj(pf); var ratio = NumberUtil.div(BigDecimal.valueOf(Double.parseDouble(pf.path("text_1").asText())), 100);
var ratio = NumberUtil.div(BigDecimal.valueOf(Double.parseDouble(pfObj.getStr("text_1"))), 100); var date = DateUtil.date(pf.path("date_1").asLong() * 1000);
var date = DateUtil.date(pfObj.getLong("date_1") * 1000); var stage = pf.path("text_2").path("text").asText();
var stage = pfObj.getJSONObject("text_2").getStr("text");
if (StrUtil.equals(stage, "预付款")) { if (StrUtil.equals(stage, "预付款")) {
contract.setSignRatio(ratio); contract.setSignRatio(ratio);
contract.setSignDate1(date); contract.setSignDate1(date);
...@@ -215,35 +219,40 @@ public class ContractRunner { ...@@ -215,35 +219,40 @@ public class ContractRunner {
}); });
} }
contract.setSubject("北京文安智能技术股份有限公司"); contract.setSubject("北京文安智能技术股份有限公司");
contract.setCustomerName(jsonObj1.getJSONObject("text_2").getStr("name")); contract.setCustomerName(jsonObj1.path("text_2").path("name").asText());
contract.setSaleName(jsonObj1.getJSONObject("text_8").getStr("name")); contract.setSaleName(jsonObj1.path("text_8").path("name").asText());
contract.setBackInfo(jsonObj1.getStr("text_29")); contract.setBackInfo(jsonObj1.path("text_29").asText());
contract.setCreateUser(-1L); contract.setCreateUser(-1L);
contract.setModifyUser(-1L); contract.setModifyUser(-1L);
contract.setEntryTime(DateUtil.date(result.getLong("addTime") * 1000)); contract.setEntryTime(DateUtil.date(result.path("addTime").asLong() * 1000));
contract.setOriginalModTime(DateUtil.date(result.getLong("updateTime") * 1000)); contract.setOriginalModTime(DateUtil.date(result.path("updateTime").asLong() * 1000));
insOrUpdContractList.add(contract); insOrUpdContractList.add(contract);
var productArr = jsonObj1.getJSONArray("array_4"); var productArr = jsonObj1.withArray("array_4");
if (!productArr.isEmpty()) { if (!productArr.isEmpty()) {
productArr.forEach(pro -> { productArr.forEach(pro -> {
var product = JSONUtil.parseObj(pro); var crmProJson =
var crmProJson = crmProList.stream().filter(p -> p.getInt("dataId").equals(product.getInt("text_1"))).toList().getFirst(); crmProList.stream()
var crmPro = crmProJson.getJSONObject("data"); .filter(p -> p.path("dataId").asInt() != 0 && p.path("dataId").asInt() == pro.path(
"text_1").asInt())
.toList()
.getFirst();
var crmPro = crmProJson.path("data");
var contractProduct = new RContractProduct(); var contractProduct = new RContractProduct();
contractProduct.setContractNo(contract.getContractNo()); contractProduct.setContractNo(contract.getContractNo());
contractProduct.setProductName(crmPro.getStr("text_1")); contractProduct.setProductName(crmPro.path("text_1").asText());
contractProduct.setProductCode(crmPro.getStr("serialNo")); contractProduct.setProductCode(crmPro.path("serialNo").asText());
contractProduct.setProductModel(crmPro.getStr("text_4")); contractProduct.setProductModel(crmPro.path("text_4").asText());
contractProduct.setNum(product.getInt("num_3")); contractProduct.setNum(pro.path("num_3").asInt());
contractProduct.setTaxPrice(product.getBigDecimal("num_1")); contractProduct.setTaxPrice(pro.path("num_1").decimalValue());
contractProduct.setTaxRate(BigDecimal.valueOf(Integer.parseInt(crmPro.getStr("text_12").replace("%", "")) / 100)); contractProduct.setTaxRate(BigDecimal.valueOf(Integer.parseInt(crmPro.path("text_12").asText().replace(
"%", "")) / 100));
// contractProduct.setNoTaxPrice(product.getBigDecimal("num_6")); // contractProduct.setNoTaxPrice(product.getBigDecimal("num_6"));
contractProduct.setDiscountRate(NumberUtil.div(product.getBigDecimal("num_4"), 100)); contractProduct.setDiscountRate(NumberUtil.div(pro.path("num_4").decimalValue(), 100));
contractProduct.setActualPrice(product.getBigDecimal("num_6")); contractProduct.setActualPrice(pro.path("num_6").decimalValue());
// contractProduct.setErase(product); // contractProduct.setErase(product);
contractProduct.setTotalPrice(product.getBigDecimal("num_5")); contractProduct.setTotalPrice(pro.path("num_5").decimalValue());
productList.add(contractProduct); productList.add(contractProduct);
}); });
} }
...@@ -398,14 +407,14 @@ public class ContractRunner { ...@@ -398,14 +407,14 @@ public class ContractRunner {
/** /**
* 获取CRM产品列表,若循环调用接口出现一次失败,则直接返回空列表 * 获取CRM产品列表,若循环调用接口出现一次失败,则直接返回空列表
* *
* @return java.util.List<org.dromara.hutool.json.JSONObject> * @return java.util.List<com.fasterxml.jackson.databind.JsonNode>
*/ */
public List<JSONObject> getProductList() { public List<JsonNode> getProductList() {
List<JSONObject> resList = new ArrayList<>(); List<JsonNode> resList = new ArrayList<>();
var json = JSONUtil.ofObj() var json = JsonUtil.createObj()
.set("corpid", corpId) .put("corpid", corpId)
.set("page", 1) .put("page", 1)
.set("pageSize", 100); .put("pageSize", 100);
var jobj = bongRestClient.post() var jobj = bongRestClient.post()
.uri("/pro/v2/api/product/list") .uri("/pro/v2/api/product/list")
...@@ -413,33 +422,33 @@ public class ContractRunner { ...@@ -413,33 +422,33 @@ public class ContractRunner {
.header("sign", SecureUtil.sha256(json.toString() + token)) .header("sign", SecureUtil.sha256(json.toString() + token))
.body(json.toString()) .body(json.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobj.getInt("code") != 1) { if (ObjUtil.isNull(jobj) || jobj.path("code").asInt() != 1) {
log.error("获取CRM产品列表失败:{}", jobj); log.error("获取CRM产品列表失败:{}", jobj);
return List.of(); return List.of();
} }
var result = jobj.getJSONObject("result"); var result = jobj.path("result");
var totalPage = result.getInt("totalPage"); var totalPage = result.path("totalPage").asInt();
result.getJSONArray("list").stream().map(JSONUtil::parseObj).forEach(resList::add); result.withArray("list").forEach(resList::add);
for (int i = 2; i <= totalPage; i++) { for (int i = 2; i <= totalPage; i++) {
var json1 = JSONUtil.ofObj() var json1 = JsonUtil.createObj()
.set("corpid", corpId) .put("corpid", corpId)
.set("page", i) .put("page", i)
.set("pageSize", 100); .put("pageSize", 100);
var jobj1 = bongRestClient.post() var jobj1 = bongRestClient.post()
.uri("/pro/v2/api/product/list") .uri("/pro/v2/api/product/list")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json1.toString() + token)) .header("sign", SecureUtil.sha256(json1.toString() + token))
.body(json1.toString()) .body(json1.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobj1.getInt("code") != 1) { if (ObjUtil.isNull(jobj1) || jobj1.path("code").asInt() != 1) {
log.error("获取CRM产品列表失败:{}", jobj1); log.error("获取CRM产品列表失败:{}", jobj1);
return List.of(); return List.of();
} }
var result1 = jobj1.getJSONObject("result"); var result1 = jobj1.path("result");
result1.getJSONArray("list").stream().map(JSONUtil::parseObj).forEach(resList::add); result1.withArray("list").forEach(resList::add);
} }
return resList; return resList;
} }
......
...@@ -8,8 +8,6 @@ import org.dromara.hutool.core.text.StrUtil; ...@@ -8,8 +8,6 @@ import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.cron.CronUtil; import org.dromara.hutool.cron.CronUtil;
import org.dromara.hutool.cron.task.Task; import org.dromara.hutool.cron.task.Task;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RedissonClient; import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -20,6 +18,7 @@ import vion.model.User; ...@@ -20,6 +18,7 @@ import vion.model.User;
import vion.service.IRStoreUserService; import vion.service.IRStoreUserService;
import vion.service.IStoreService; import vion.service.IStoreService;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -74,21 +73,22 @@ public class LogPushRunner { ...@@ -74,21 +73,22 @@ public class LogPushRunner {
}; };
} }
JSONObject buildMsg(String storeName, String userid) { String buildMsg(String storeName, String userid) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = new JSONObject(); var content = JsonUtil.createObj()
var content = new JSONObject(); .put("title", "项目日志待提交提醒")
content.set("title", "项目日志待提交提醒") .put("text", StrUtil.format("""
.set("text", StrUtil.format("""
### 项目日志待提交提醒 ### 项目日志待提交提醒
#### 项目:[{}]请及时提交日志 #### 项目:[{}]请及时提交日志
#### 发送时间:{}""", storeName, DateUtil.now())); #### 发送时间:{}""", storeName, DateUtil.now()));
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj()
.put("msgtype", "markdown")
.set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
} }
...@@ -5,9 +5,6 @@ import lombok.RequiredArgsConstructor; ...@@ -5,9 +5,6 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.date.DateUtil; import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.lang.Opt; import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.json.JSONArray;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import vion.model.Task; import vion.model.Task;
...@@ -15,6 +12,7 @@ import vion.model.User; ...@@ -15,6 +12,7 @@ import vion.model.User;
import vion.service.ITaskService; import vion.service.ITaskService;
import vion.service.IUserService; import vion.service.IUserService;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -44,27 +42,27 @@ public class TaskRunner { ...@@ -44,27 +42,27 @@ public class TaskRunner {
log.info("推送未完成工单完成"); log.info("推送未完成工单完成");
} }
JSONObject buildMsg(User user) { String buildMsg(User user) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", user.getUserid()); .put("userid_list", user.getUserid());
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj()
var content = JSONUtil.ofObj() .put("title", "请查看您未完成的工单~_~")
.set("title", "请查看您未完成的工单~_~") .put("markdown", """
.set("markdown", """
### 未完成工单提醒 ### 未完成工单提醒
#### 请查看您未完成的工单 #### 请查看您未完成的工单
#### 发送时间:""" + DateUtil.now()) #### 发送时间:""" + DateUtil.now())
.set("btn_orientation", "1"); .put("btn_orientation", "1");
JSONArray jsonArray = JSONUtil.ofArray() var jsonArray = JsonUtil.createArr()
.put(JSONUtil.ofObj().set("title", "查看详情") .add(JsonUtil.createObj().put("title", "查看详情")
.set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FuserId%3D" + user.getId())); .put("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid" +
"=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FuserId%3D" + user.getId()));
content.set("btn_json_list", jsonArray); content.set("btn_json_list", jsonArray);
msg.set("msgtype", "action_card").set("action_card", content); var msg = JsonUtil.createObj().put("msgtype", "action_card").set("action_card", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
} }
\ No newline at end of file \ No newline at end of file
package vion.service; package vion.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.yulichang.base.MPJBaseService; import com.github.yulichang.base.MPJBaseService;
import org.dromara.hutool.json.JSONObject;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import vion.dto.ContractDTO; import vion.dto.ContractDTO;
...@@ -33,7 +33,7 @@ public interface IContractService extends MPJBaseService<Contract> { ...@@ -33,7 +33,7 @@ public interface IContractService extends MPJBaseService<Contract> {
String updateById(Long id, String contractNo, ContractDTO dto); String updateById(Long id, String contractNo, ContractDTO dto);
JSONObject calAmount(ContractDTO dto); JsonNode calAmount(ContractDTO dto);
Map<String, Object> analyze(ContractDTO dto); Map<String, Object> analyze(ContractDTO dto);
...@@ -49,7 +49,7 @@ public interface IContractService extends MPJBaseService<Contract> { ...@@ -49,7 +49,7 @@ public interface IContractService extends MPJBaseService<Contract> {
String createContract(String contractJson); String createContract(String contractJson);
JSONObject getCRMProduct(String name, String code, Integer page, Integer pageSize); JsonNode getCRMProduct(String name, String code, Integer page, Integer pageSize);
String syncContractFile(String[] contractNoList); String syncContractFile(String[] contractNoList);
} }
\ No newline at end of file \ No newline at end of file
...@@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; ...@@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db; import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.github.yulichang.base.MPJBaseServiceImpl; import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper; import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter; import io.github.linpeilie.Converter;
...@@ -30,7 +32,6 @@ import org.dromara.hutool.core.util.ObjUtil; ...@@ -30,7 +32,6 @@ import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.http.client.HttpDownloader; import org.dromara.hutool.http.client.HttpDownloader;
import org.dromara.hutool.json.JSONObject; import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
...@@ -45,6 +46,7 @@ import vion.model.Dictionary; ...@@ -45,6 +46,7 @@ import vion.model.Dictionary;
import vion.model.*; import vion.model.*;
import vion.service.*; import vion.service.*;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.vo.*; import vion.vo.*;
import java.io.File; import java.io.File;
...@@ -53,6 +55,7 @@ import java.math.BigDecimal; ...@@ -53,6 +55,7 @@ import java.math.BigDecimal;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/** /**
* @author HlQ * @author HlQ
...@@ -385,15 +388,15 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -385,15 +388,15 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
} }
@Override @Override
public JSONObject calAmount(ContractDTO dto) { public JsonNode calAmount(ContractDTO dto) {
Result result = getResult(dto); Result result = getResult(dto);
JSONObject obj = JSONUtil.ofObj() var obj = JsonUtil.createObj()
.set("totalAmount", 0) .put("totalAmount", 0)
.set("paidAmount", 0) .put("paidAmount", 0)
.set("recAmount", 0) .put("recAmount", 0)
.set("outAmount", 0) .put("outAmount", 0)
.set("invoiceAmount", 0); .put("invoiceAmount", 0);
if (!result.roleCodeList.contains("admin") && !result.roleCodeList.contains("xiaoshou") && !result.roleCodeList.contains("caiwu")) { if (!result.roleCodeList.contains("admin") && !result.roleCodeList.contains("xiaoshou") && !result.roleCodeList.contains("caiwu")) {
return obj; return obj;
} }
...@@ -412,11 +415,11 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -412,11 +415,11 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
List<BigDecimal> invoices = Db.listObjs(Wrappers.lambdaQuery(Invoice.class).select(Invoice::getInvoiceAmount).in(BeanUtil.isNotEmpty(dto), Invoice::getContractNo, noList), Invoice::getInvoiceAmount); List<BigDecimal> invoices = Db.listObjs(Wrappers.lambdaQuery(Invoice.class).select(Invoice::getInvoiceAmount).in(BeanUtil.isNotEmpty(dto), Invoice::getContractNo, noList), Invoice::getInvoiceAmount);
BigDecimal invoiceAmount = invoices.stream().reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal invoiceAmount = invoices.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
obj.set("totalAmount", totalAmount) obj.put("totalAmount", totalAmount)
.set("paidAmount", paidAmount) .put("paidAmount", paidAmount)
.set("recAmount", recAmount) .put("recAmount", recAmount)
.set("outAmount", outAmount) .put("outAmount", outAmount)
.set("invoiceAmount", invoiceAmount); .put("invoiceAmount", invoiceAmount);
}); });
return obj; return obj;
} }
...@@ -533,8 +536,8 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -533,8 +536,8 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
.header("sign", sha256) .header("sign", sha256)
.body(contractJson) .body(contractJson)
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobj.getInt("code") != 1) { if (ObjUtil.isNull(jobj) || jobj.path("code").asInt() != 1) {
log.error("调用CRM接口创建合同失败,错误原因:{}", jobj); log.error("调用CRM接口创建合同失败,错误原因:{}", jobj);
return "创建合同失败"; return "创建合同失败";
} }
...@@ -542,21 +545,27 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -542,21 +545,27 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
} }
@Override @Override
public JSONObject getCRMProduct(String name, String code, Integer page, Integer pageSize) { public JsonNode getCRMProduct(String name, String code, Integer page, Integer pageSize) {
var conditions = JSONUtil.ofArray().put(JSONUtil.ofObj() var conditions = JsonUtil.createArr().add(JsonUtil.createObj()
.set("attr", "num_3") .put("attr", "num_3")
.set("symbol", "noequal") .put("symbol", "noequal")
.set("value", new int[]{0})); .putPOJO("value", new int[]{0}));
if (StrUtil.isNotBlank(name)) { if (StrUtil.isNotBlank(name)) {
conditions.put(JSONUtil.ofObj().set("attr", "text_1").set("symbol", "like").set("value", new String[]{name})); conditions.add(JsonUtil.createObj()
.put("attr", "text_1")
.put("symbol", "like")
.putPOJO("value", new String[]{name}));
} }
if (StrUtil.isNotBlank(code)) { if (StrUtil.isNotBlank(code)) {
conditions.put(JSONUtil.ofObj().set("attr", "serialNo").set("symbol", "like").set("value", new String[]{code})); conditions.add(JsonUtil.createObj()
.put("attr", "serialNo")
.put("symbol", "like")
.putPOJO("value", new String[]{code}));
} }
var json = JSONUtil.ofObj() var json = JsonUtil.createObj()
.set("corpid", "ding6bb660048f7ae2dcee0f45d8e4f7c288") .put("corpid", "ding6bb660048f7ae2dcee0f45d8e4f7c288")
.set("page", page) .put("page", page)
.set("pageSize", pageSize) .put("pageSize", pageSize)
.set("conditions", conditions); .set("conditions", conditions);
var jobj = bongRestClient.post() var jobj = bongRestClient.post()
...@@ -565,69 +574,70 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -565,69 +574,70 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
.header("sign", SecureUtil.sha256(json.toString() + token)) .header("sign", SecureUtil.sha256(json.toString() + token))
.body(json.toString()) .body(json.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobj.getInt("code") != 1) { if (ObjUtil.isNull(jobj) || jobj.path("code").asInt() != 1) {
log.error("调用CRM接口获取产品列表失败,错误原因:{}", jobj); log.error("调用CRM接口获取产品列表失败,错误原因:{}", jobj);
return JSONUtil.ofObj(); return JsonUtil.createObj();
} }
return JSONUtil.ofObj().set("records", jobj.getJSONObject("result").getJSONArray("list")) return JsonUtil.createObj().putPOJO("records", jobj.path("result").withArray("list"))
.set("current", page) .put("current", page)
.set("size", pageSize) .put("size", pageSize)
.set("total", jobj.getJSONObject("result").getInt("totalCount")) .put("total", jobj.path("result").path("totalCount").asInt())
.set("pages", jobj.getJSONObject("result").getInt("totalPage")); .put("pages", jobj.path("result").path("totalPage").asInt());
} }
@Override @Override
public String syncContractFile(String[] contractNoList) { public String syncContractFile(String[] contractNoList) {
log.info("同步销帮帮合同文件[开始]"); log.info("同步销帮帮合同文件[开始]");
// 只同步申请日期(原CRM中的签订日期)2024-05-07号(含)之后的合同 // 只同步申请日期(原CRM中的签订日期)2024-05-07号(含)之后的合同
var conditions = JSONUtil.ofArray() var conditions = JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("attr", "date_3") .put("attr", "date_3")
.set("symbol", "greaterequal") .put("symbol", "greaterequal")
.set("value", new String[]{"1715356800"})); .putPOJO("value", new String[]{"1715356800"}));
if (ArrayUtil.isNotEmpty(contractNoList)) { if (ArrayUtil.isNotEmpty(contractNoList)) {
conditions.put(JSONUtil.ofObj() conditions.add(JsonUtil.createObj()
.set("attr", "serialNo") .put("attr", "serialNo")
.set("symbol", "in") .put("symbol", "in")
.set("value", contractNoList)); .putPOJO("value", contractNoList));
} }
var json = JSONUtil.ofObj() var json = JsonUtil.createObj()
.set("conditions", conditions) .put("corpid", corpId)
.set("corpid", corpId) .put("formId", 8429903)
.set("formId", 8429903) .put("pageSize", 100)
.set("pageSize", 100); .set("conditions", conditions);
var jobO = bongRestClient.post() var jobO = bongRestClient.post()
.uri("/pro/v2/api/contract/list") .uri("/pro/v2/api/contract/list")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json.toString() + token)) .header("sign", SecureUtil.sha256(json.toString() + token))
.body(json.toString()) .body(json.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobO.getInt("code") != 1) { if (ObjUtil.isNull(jobO) || jobO.path("code").asInt() != 1) {
var errorInfo = StrUtil.format("获取合同列表失败,错误原因:{}", jobO); var errorInfo = StrUtil.format("获取合同列表失败,错误原因:{}", jobO);
log.error(errorInfo); log.error(errorInfo);
return errorInfo; return errorInfo;
} }
Integer cnt = jobO.getJSONObject("result").getInt("totalCount"); var cnt = jobO.path("result").path("totalCount").asInt();
Integer page = jobO.getJSONObject("result").getInt("totalPage"); var page = jobO.path("result").path("totalPage").asInt();
if (NumberUtil.equals(cnt, 0)) { if (NumberUtil.equals(cnt, 0)) {
return "没有需要插入或更新的合同"; return "没有需要插入或更新的合同";
} }
var jsonArray = jobO.getJSONObject("result").getJSONArray("list"); ArrayNode jsonArray = jobO.path("result").withArray("list");
var fileList = jsonArray.stream().map(v -> { var fileList = StreamSupport.stream(jsonArray.spliterator(), false)
var fileArr = JSONUtil.parseObj(v).getJSONObject("data").getJSONArray("file_1"); .map(v -> {
var contractNo = JSONUtil.parseObj(v).getJSONObject("data").getStr("serialNo"); var fileArr = v.path("data").withArray("file_1");
return JSONUtil.ofObj().set("contractNo", contractNo).set("fileArr", fileArr); var contractNo = v.path("data").path("serialNo").asText();
}).collect(Collectors.toList()); return (JsonNode) JsonUtil.createObj().put("contractNo", contractNo).set("fileArr", fileArr);
}).collect(Collectors.toList());
for (int i = 2; i <= page; i++) { for (int i = 2; i <= page; i++) {
var jsonR = JSONUtil.ofObj() var jsonR = JsonUtil.createObj()
.set("conditions", conditions) .putPOJO("conditions", conditions)
.set("corpid", corpId) .put("corpid", corpId)
.set("formId", 8429903) .put("formId", 8429903)
.set("page", i) .put("page", i)
.set("pageSize", 100); .put("pageSize", 100);
var jobR = bongRestClient.post() var jobR = bongRestClient.post()
.uri("/pro/v2/api/contract/list") .uri("/pro/v2/api/contract/list")
...@@ -635,13 +645,14 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -635,13 +645,14 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
.header("sign", SecureUtil.sha256(jsonR.toString() + token)) .header("sign", SecureUtil.sha256(jsonR.toString() + token))
.body(jsonR.toString()) .body(jsonR.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
var jsonArrR = jobR.getJSONObject("result").getJSONArray("list"); var jsonArrR = jobR.path("result").withArray("list");
var fileListR = jsonArrR.stream().map(v -> { var fileListR = StreamSupport.stream(jsonArrR.spliterator(), false)
var fileArr = JSONUtil.parseObj(v).getJSONObject("data").getJSONArray("file_1"); .map(v -> {
var contractNo = JSONUtil.parseObj(v).getJSONObject("data").getStr("serialNo"); var fileArr = v.path("data").withArray("file_1");
return JSONUtil.ofObj().set("contractNo", contractNo).set("fileArr", fileArr); var contractNo = v.path("data").path("serialNo").asText();
}).toList(); return (JsonNode) JsonUtil.createObj().put("contractNo", contractNo).set("fileArr", fileArr);
}).toList();
fileList.addAll(fileListR); fileList.addAll(fileListR);
} }
...@@ -655,9 +666,9 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -655,9 +666,9 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
var contractId2Sha256Map = fileInfoList.stream().collect(Collectors.groupingBy(FileInfo::getContractId, var contractId2Sha256Map = fileInfoList.stream().collect(Collectors.groupingBy(FileInfo::getContractId,
Collectors.mapping(FileInfo::getSha256, Collectors.toList()))); Collectors.mapping(FileInfo::getSha256, Collectors.toList())));
for (JSONObject entries : fileList) { for (JsonNode entries : fileList) {
var contractNo = entries.getStr("contractNo"); var contractNo = entries.path("contractNo").asText();
var fileArr = entries.getJSONArray("fileArr"); ArrayNode fileArr = entries.withArray("fileArr");
if (ObjUtil.isNull(fileArr) || fileArr.isEmpty()) { if (ObjUtil.isNull(fileArr) || fileArr.isEmpty()) {
log.info("合同:{},没有文件", contractNo); log.info("合同:{},没有文件", contractNo);
continue; continue;
...@@ -669,13 +680,12 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -669,13 +680,12 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
} }
List<FileInfo> saveFileInfoList = new ArrayList<>(); List<FileInfo> saveFileInfoList = new ArrayList<>();
for (Object o : fileArr) { for (JsonNode o : fileArr) {
var fileObj = JSONUtil.parseObj(o); var filename = o.path("filename").asText();
var filename = fileObj.getStr("filename");
String path = fileUrl + FileUtil.FILE_SEPARATOR + "contract" + FileUtil.FILE_SEPARATOR + contractId + FileUtil.FILE_SEPARATOR + filename; String path = fileUrl + FileUtil.FILE_SEPARATOR + "contract" + FileUtil.FILE_SEPARATOR + contractId + FileUtil.FILE_SEPARATOR + filename;
byte[] bytes; byte[] bytes;
try { try {
bytes = HttpDownloader.downloadBytes(fileObj.getStr("attachIndex")); bytes = HttpDownloader.downloadBytes(o.path("attachIndex").asText());
} catch (Exception e) { } catch (Exception e) {
log.error("合同:{},[{}] 文件同步失败", contractNo, filename); log.error("合同:{},[{}] 文件同步失败", contractNo, filename);
continue; continue;
...@@ -815,13 +825,12 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -815,13 +825,12 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
} }
} }
JSONObject buildMsg(String userid, Contract contract, String applicantName) { String buildMsg(String userid, Contract contract, String applicantName) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "合同施工申请,请及时处理哦~_~");
var content = JSONUtil.ofObj().set("title", "合同施工申请,请及时处理哦~_~");
String template = """ String template = """
### 合同施工申请 ### 合同施工申请
#### 合同编号: **{}** #### 合同编号: **{}**
...@@ -831,20 +840,19 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -831,20 +840,19 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
contract.getContractNo(), contract.getName(), applicantName, DateUtil.now()); contract.getContractNo(), contract.getName(), applicantName, DateUtil.now());
content.set("markdown", markdown); content.put("markdown", markdown);
msg.set("msgtype", "action_card").set("action_card", content); var msg = JsonUtil.createObj().put("msgtype", "action_card").set("action_card", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
JSONObject buildMsg(String userid, ContractDTO dto, Contract contract, String statusStr) { String buildMsg(String userid, ContractDTO dto, Contract contract, String statusStr) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "验收提醒");
var content = JSONUtil.ofObj().set("title", "验收提醒");
String template = """ String template = """
#### 验收提醒 #### 验收提醒
#### 合同编号:**{}** #### 合同编号:**{}**
...@@ -855,11 +863,11 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -855,11 +863,11 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
contract.getContractNo(), contract.getName(), statusStr, DateUtil.formatDate(dto.getNodeDate()), DateUtil.now()); contract.getContractNo(), contract.getName(), statusStr, DateUtil.formatDate(dto.getNodeDate()), DateUtil.now());
content.set("text", markdown); content.put("text", markdown);
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
private record Result(Set<String> roleCodeList, MPJLambdaWrapper<Contract> wrapper) { private record Result(Set<String> roleCodeList, MPJLambdaWrapper<Contract> wrapper) {
...@@ -875,51 +883,54 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -875,51 +883,54 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
var contractNoList = this.listObjs(Wrappers.<Contract>lambdaQuery().select(Contract::getContractNo), var contractNoList = this.listObjs(Wrappers.<Contract>lambdaQuery().select(Contract::getContractNo),
Object::toString); Object::toString);
var json = JSONUtil.ofObj() var json = JsonUtil.createObj()
.set("sortMap", JSONUtil.ofObj() .putPOJO("sortMap", JsonUtil.createObj()
.set("field", "updateTime") .put("field", "updateTime")
.set("sort", "desc")) .put("sort", "desc"))
.set("corpid", corpId) .put("corpid", corpId)
.set("formId", 8429903) .put("formId", 8429903)
.set("pageSize", 100); .put("pageSize", 100);
var jobO = bongRestClient.post() var jobO = bongRestClient.post()
.uri("/pro/v2/api/contract/list") .uri("/pro/v2/api/contract/list")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json.toString() + token)) .header("sign", SecureUtil.sha256(json.toString() + token))
.body(json.toString()) .body(json.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobO.getInt("code") != 1) { if (ObjUtil.isNull(jobO) || jobO.path("code").asInt() != 1) {
log.error("获取合同列表失败,错误原因:{}", jobO); log.error("获取合同列表失败,错误原因:{}", jobO);
} }
Integer cnt = jobO.getJSONObject("result").getInt("totalCount"); var cnt = jobO.path("result").path("totalCount").asInt();
Integer page = jobO.getJSONObject("result").getInt("totalPage"); var page = jobO.path("result").path("totalPage").asInt();
if (NumberUtil.equals(cnt, 0)) { if (NumberUtil.equals(cnt, 0)) {
log.info("没有需要插入或更新的合同"); log.info("没有需要插入或更新的合同");
} }
var jsonArray = jobO.getJSONObject("result").getJSONArray("list"); var jsonArray = jobO.path("result").withArray("list");
// 合同编号 // 合同编号
var dataIdSet = var dataIdSet = StreamSupport.stream(jsonArray.spliterator(), false)
jsonArray.stream().map(v -> JSONUtil.parseObj(v).getJSONObject("data").getStr("serialNo")).collect(Collectors.toSet()); .map(v -> v.path("data").path("serialNo").asText())
.collect(Collectors.toSet());
for (int i = 2; i <= page; i++) { for (int i = 2; i <= page; i++) {
var jsonR = JSONUtil.ofObj() var jsonR = JsonUtil.createObj()
.set("sortMap", JSONUtil.ofObj() .putPOJO("sortMap", JsonUtil.createObj()
.set("field", "updateTime") .put("field", "updateTime")
.set("sort", "desc")) .put("sort", "desc"))
.set("corpid", corpId) .put("corpid", corpId)
.set("formId", 8429903) .put("formId", 8429903)
.set("page", i) .put("page", i)
.set("pageSize", 100); .put("pageSize", 100);
var jobR = bongRestClient.post() var jobR = bongRestClient.post()
.uri("/pro/v2/api/contract/list") .uri("/pro/v2/api/contract/list")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(jsonR.toString() + token)) .header("sign", SecureUtil.sha256(jsonR.toString() + token))
.body(jsonR.toString()) .body(jsonR.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
var jsonArrR = jobR.getJSONObject("result").getJSONArray("list"); var jsonArrR = jobR.path("result").withArray("list");
var dataIdSetR = jsonArrR.stream().map(v -> JSONUtil.parseObj(v).getJSONObject("data").getStr("serialNo")).collect(Collectors.toSet()); var dataIdSetR = StreamSupport.stream(jsonArrR.spliterator(), false)
.map(v -> v.path("data").path("serialNo").asText())
.collect(Collectors.toSet());
dataIdSet.addAll(dataIdSetR); dataIdSet.addAll(dataIdSetR);
} }
...@@ -928,7 +939,7 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -928,7 +939,7 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
// 返回项目运维管理平台存在,但销帮帮不存在的合同(可能销帮帮对该合同删除了) // 返回项目运维管理平台存在,但销帮帮不存在的合同(可能销帮帮对该合同删除了)
var extraList = CollUtil.subtractToList(contractNoList, dataIdSet); var extraList = CollUtil.subtractToList(contractNoList, dataIdSet);
// 两平台共存的合同 // 两平台共存的合同
log.info("合同编号验证:{}", JSONUtil.ofObj().set("unsynced", unsyncedList).set("extra", extraList)); log.info("合同编号验证:{}", JsonUtil.createObj().putPOJO("unsynced", unsyncedList).putPOJO("extra", extraList));
var sameList = CollUtil.intersectionDistinct(dataIdSet, contractNoList); var sameList = CollUtil.intersectionDistinct(dataIdSet, contractNoList);
// 只比对合同编号SC开头的合同 // 只比对合同编号SC开头的合同
contractDiff(sameList.stream().filter(no -> StrUtil.startWith(no, "SC")).collect(Collectors.toSet())); contractDiff(sameList.stream().filter(no -> StrUtil.startWith(no, "SC")).collect(Collectors.toSet()));
...@@ -991,19 +1002,19 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -991,19 +1002,19 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
Contract::getRemark, Contract::getCreateUser, Contract::getModifyUser, Contract::getCreateTime, Contract::getRemark, Contract::getCreateUser, Contract::getModifyUser, Contract::getCreateTime,
Contract::getModifyTime, Contract::getFinalDate, Contract::getInvoiceAmount, Contract::getModifyTime, Contract::getFinalDate, Contract::getInvoiceAmount,
Contract::getFinancialStatus, Contract::getOriginalModTime, Contract::getBackInfo) Contract::getFinancialStatus, Contract::getOriginalModTime, Contract::getBackInfo)
.ignoreNullValue(); .setIgnoreNullValue(true);
var platMap = BeanUtil.beanToMap(platContract, new HashMap<>(), copyOptions); var platMap = BeanUtil.beanToMap(platContract, new HashMap<>(), copyOptions);
var json = JSONUtil.ofObj() var json = JsonUtil.createObj()
.set("conditions", JSONUtil.ofArray() .putPOJO("conditions", JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("attr", "serialNo") .put("attr", "serialNo")
.set("symbol", "equal") .put("symbol", "equal")
.set("value", new String[]{contractNo})) .set("value", JsonUtil.createArr().add(contractNo)))
) )
.set("corpid", corpId) .put("corpid", corpId)
.set("formId", 8429903) .put("formId", 8429903)
.set("pageSize", 100); .put("pageSize", 100);
var jobO = bongRestClient.post() var jobO = bongRestClient.post()
.uri("/pro/v2/api/contract/list") .uri("/pro/v2/api/contract/list")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
...@@ -1011,29 +1022,31 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -1011,29 +1022,31 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
.body(json.toString()) .body(json.toString())
.retrieve() .retrieve()
// fixme GOAWAY received // fixme GOAWAY received
.body(JSONObject.class); .body(JsonNode.class);
if (jobO.getInt("code") != 1) { if (ObjUtil.isNull(jobO) || jobO.path("code").asInt() != 1) {
log.error("获取合同列表失败,错误原因:{}", jobO); log.error("获取合同列表失败,错误原因:{}", jobO);
} }
var jsonArray = jobO.getJSONObject("result").getJSONArray("list"); var jsonArray = jobO.path("result").withArray("list");
// 合同记录唯一 dataId // 合同记录唯一 dataId
var dataIdSet = jsonArray.stream().map(v -> JSONUtil.parseObj(v).getInt("dataId")).collect(Collectors.toSet()); var dataIdSet = StreamSupport.stream(jsonArray.spliterator(), false)
.map(v -> v.path("dataId").asInt())
.collect(Collectors.toSet());
var json1 = JSONUtil.ofObj() var json1 = JsonUtil.createObj()
.set("corpid", corpId) .put("corpid", corpId)
.set("dataId", CollUtil.getFirst(dataIdSet)); .put("dataId", CollUtil.getFirst(dataIdSet));
var jobj1 = bongRestClient.post() var jobj1 = bongRestClient.post()
.uri("/pro/v2/api/contract/detail") .uri("/pro/v2/api/contract/detail")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json1.toString() + token)) .header("sign", SecureUtil.sha256(json1.toString() + token))
.body(json1.toString()) .body(json1.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jobj1.getInt("code") != 1) { if (ObjUtil.isNull(jobj1) || jobj1.path("code").asInt() != 1) {
log.error("获取合同详情失败,错误原因:{}", jobj1); log.error("获取合同详情失败,错误原因:{}", jobj1);
} }
var result = jobj1.getJSONObject("result"); var result = jobj1.path("result");
var jsonObj1 = result.getJSONObject("data"); var jsonObj1 = result.path("data");
Map<String, Integer> contractTypeMap = Db.list(Wrappers.lambdaQuery(Dictionary.class).eq(Dictionary::getType, Map<String, Integer> contractTypeMap = Db.list(Wrappers.lambdaQuery(Dictionary.class).eq(Dictionary::getType,
"contract_type")) "contract_type"))
...@@ -1041,29 +1054,28 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -1041,29 +1054,28 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
.collect(Collectors.toMap(Dictionary::getValue, Dictionary::getKey)); .collect(Collectors.toMap(Dictionary::getValue, Dictionary::getKey));
Contract xbongContract = new Contract(); Contract xbongContract = new Contract();
xbongContract.setName(jsonObj1.getStr("text_14")); xbongContract.setName(jsonObj1.path("text_14").asText());
xbongContract.setContractNo(jsonObj1.getStr("serialNo")); xbongContract.setContractNo(jsonObj1.path("serialNo").asText());
xbongContract.setType(contractTypeMap.getOrDefault(jsonObj1.getJSONObject("text_17").getStr("text"), 0)); xbongContract.setType(contractTypeMap.getOrDefault(jsonObj1.path("text_17").path("text").asText(), 0));
xbongContract.setSignDate(DateUtil.date(jsonObj1.getLong("date_1") * 1000).toJdkDate()); xbongContract.setSignDate(DateUtil.date(jsonObj1.path("date_1").asLong() * 1000).toJdkDate());
xbongContract.setMaintainSdate(Opt.ofNullable(jsonObj1.getLong("date_4")).map(sec -> DateUtil.date(sec * 1000).toJdkDate()).orElse(null)); xbongContract.setMaintainSdate(Opt.ofNullable(jsonObj1.path("date_4")).filter(JsonNode::isNumber).map(sec -> DateUtil.date(sec.asLong() * 1000).toJdkDate()).orElse(null));
xbongContract.setMaintainEdate(Opt.ofNullable(jsonObj1.getLong("date_5")).map(sec -> DateUtil.date(sec * 1000).toJdkDate()).orElse(null)); xbongContract.setMaintainEdate(Opt.ofNullable(jsonObj1.path("date_5")).filter(JsonNode::isNumber).map(sec -> DateUtil.date(sec.asLong() * 1000).toJdkDate()).orElse(null));
String warrantyPeriod = Opt.ofNullable(jsonObj1.getJSONObject("text_23")).map(wp -> wp.getStr("text")).orElse(""); String warrantyPeriod = jsonObj1.path("text_23").path("text").asText("");
if (StrUtil.isNotBlank(warrantyPeriod) && warrantyPeriod.contains("个月")) { if (StrUtil.isNotBlank(warrantyPeriod) && warrantyPeriod.contains("个月")) {
String substring = warrantyPeriod.substring(0, (warrantyPeriod.length() - 2)); String substring = warrantyPeriod.substring(0, (warrantyPeriod.length() - 2));
xbongContract.setWarrantyPeriod(Integer.parseInt(substring)); xbongContract.setWarrantyPeriod(Integer.parseInt(substring));
} }
xbongContract.setStatus(1); xbongContract.setStatus(1);
xbongContract.setTotalAmount(jsonObj1.getBigDecimal("num_1")); xbongContract.setTotalAmount(jsonObj1.path("num_1").decimalValue());
xbongContract.setPaidAmount(BigDecimal.ZERO); xbongContract.setPaidAmount(BigDecimal.ZERO);
xbongContract.setReceivableAmount(BigDecimal.ZERO); xbongContract.setReceivableAmount(BigDecimal.ZERO);
xbongContract.setOutstandingAmount(jsonObj1.getBigDecimal("num_1")); xbongContract.setOutstandingAmount(jsonObj1.path("num_1").decimalValue());
var paymentForm = jsonObj1.getJSONArray("subForm_1"); var paymentForm = jsonObj1.withArray("subForm_1");
if (!paymentForm.isEmpty()) { if (!paymentForm.isEmpty()) {
paymentForm.forEach(pf -> { paymentForm.forEach(pf -> {
var pfObj = JSONUtil.parseObj(pf); var ratio = NumberUtil.div(BigDecimal.valueOf(Double.parseDouble(pf.path("text_1").asText())), 100);
var ratio = NumberUtil.div(BigDecimal.valueOf(Double.parseDouble(pfObj.getStr("text_1"))), 100); var date = DateUtil.date(pf.path("date_1").asLong() * 1000);
var date = DateUtil.date(pfObj.getLong("date_1") * 1000); var stage = pf.path("text_2").path("text").asText();
var stage = pfObj.getJSONObject("text_2").getStr("text");
if (StrUtil.equals(stage, "预付款")) { if (StrUtil.equals(stage, "预付款")) {
xbongContract.setSignRatio(ratio); xbongContract.setSignRatio(ratio);
xbongContract.setSignDate1(date); xbongContract.setSignDate1(date);
...@@ -1098,12 +1110,12 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont ...@@ -1098,12 +1110,12 @@ public class ContractServiceImpl extends MPJBaseServiceImpl<ContractMapper, Cont
}); });
} }
xbongContract.setSubject("北京文安智能技术股份有限公司"); xbongContract.setSubject("北京文安智能技术股份有限公司");
xbongContract.setCustomerName(jsonObj1.getJSONObject("text_2").getStr("name")); xbongContract.setCustomerName(jsonObj1.path("text_2").path("name").asText());
xbongContract.setSaleName(jsonObj1.getJSONObject("text_8").getStr("name")); xbongContract.setSaleName(jsonObj1.path("text_8").path("name").asText());
xbongContract.setCreateUser(-1L); xbongContract.setCreateUser(-1L);
xbongContract.setModifyUser(-1L); xbongContract.setModifyUser(-1L);
xbongContract.setEntryTime(DateUtil.date(result.getLong("addTime") * 1000).toJdkDate()); xbongContract.setEntryTime(DateUtil.date(result.path("addTime").asLong() * 1000).toJdkDate());
xbongContract.setOriginalModTime(DateUtil.date(result.getLong("updateTime") * 1000).toJdkDate()); xbongContract.setOriginalModTime(DateUtil.date(result.path("updateTime").asLong() * 1000).toJdkDate());
var bongMap = BeanUtil.beanToMap(xbongContract, new HashMap<>(), copyOptions); var bongMap = BeanUtil.beanToMap(xbongContract, new HashMap<>(), copyOptions);
if (!mapEqual(platMap, bongMap)) { if (!mapEqual(platMap, bongMap)) {
......
...@@ -8,8 +8,6 @@ import org.dromara.hutool.core.array.ArrayUtil; ...@@ -8,8 +8,6 @@ import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.date.DateUtil; import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.lang.Opt; import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RedissonClient; import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import vion.constant.RedisKeyEnum; import vion.constant.RedisKeyEnum;
...@@ -20,6 +18,7 @@ import vion.service.IDeliverLogService; ...@@ -20,6 +18,7 @@ import vion.service.IDeliverLogService;
import vion.service.IRStoreConfederateService; import vion.service.IRStoreConfederateService;
import vion.service.IStoreService; import vion.service.IStoreService;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.vo.DeliverLogVO; import vion.vo.DeliverLogVO;
import java.util.Comparator; import java.util.Comparator;
...@@ -126,15 +125,14 @@ public class DeliverLogServiceImpl extends MPJBaseServiceImpl<DeliverLogMapper, ...@@ -126,15 +125,14 @@ public class DeliverLogServiceImpl extends MPJBaseServiceImpl<DeliverLogMapper,
return StrUtil.containsIgnoreCase(pushRes, "ok"); return StrUtil.containsIgnoreCase(pushRes, "ok");
} }
JSONObject buildMsg(String userid, String storeName, String confederateName, DeliverLog deliverLog) { String buildMsg(String userid, String storeName, String confederateName, DeliverLog deliverLog) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = new JSONObject(); var content = JsonUtil.createObj()
var content = new JSONObject(); .put("title", "项目交付日志提醒")
content.set("title", "项目交付日志提醒") .put("text", StrUtil.format("""
.set("text", StrUtil.format("""
### 项目交付日志提醒 ### 项目交付日志提醒
#### 项目:{} #### 项目:{}
#### 合同编号:{} #### 合同编号:{}
...@@ -150,27 +148,26 @@ public class DeliverLogServiceImpl extends MPJBaseServiceImpl<DeliverLogMapper, ...@@ -150,27 +148,26 @@ public class DeliverLogServiceImpl extends MPJBaseServiceImpl<DeliverLogMapper,
deliverLog.getContent(), deliverLog.getContent(),
DateUtil.now())); DateUtil.now()));
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
JSONObject buildMsg1(String[] userIdStr, String dateStr) { String buildMsg1(String[] userIdStr, String dateStr) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", String.join(",", userIdStr)); .put("userid_list", String.join(",", userIdStr));
var msg = new JSONObject(); var content = JsonUtil.createObj()
var content = new JSONObject(); .put("title", "项目交付日志提醒")
content.set("title", "项目交付日志提醒") .put("text", StrUtil.format("""
.set("text", StrUtil.format("""
### 项目交付日志提醒 ### 项目交付日志提醒
#### 您的日志还未提交,请尽快提交! #### 您的日志还未提交,请尽快提交!
#### 未提交日志日期:{} #### 未提交日志日期:{}
#### 发送时间:{}""", dateStr, DateUtil.now())); #### 发送时间:{}""", dateStr, DateUtil.now()));
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
} }
...@@ -16,8 +16,6 @@ import org.dromara.hutool.core.map.MapUtil; ...@@ -16,8 +16,6 @@ import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import vion.dto.ContractDTO; import vion.dto.ContractDTO;
...@@ -26,6 +24,7 @@ import vion.mapper.DeliveryRecordMapper; ...@@ -26,6 +24,7 @@ import vion.mapper.DeliveryRecordMapper;
import vion.model.*; import vion.model.*;
import vion.service.*; import vion.service.*;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.vo.DeliveryRecordVO; import vion.vo.DeliveryRecordVO;
import vion.vo.UserVO; import vion.vo.UserVO;
...@@ -150,13 +149,13 @@ public class DeliveryRecordServiceImpl extends MPJBaseServiceImpl<DeliveryRecord ...@@ -150,13 +149,13 @@ public class DeliveryRecordServiceImpl extends MPJBaseServiceImpl<DeliveryRecord
.ifPresent(p -> pointInfoService.designPush(null, p, "发货")); .ifPresent(p -> pointInfoService.designPush(null, p, "发货"));
} }
JSONObject buildMsg(String userid, DeliveryRecord rec, Contract contract) { String buildMsg(String userid, DeliveryRecord rec, Contract contract) {
var jsonObj = JSONUtil.ofObj() var jsonNode = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var msg = JsonUtil.createObj();
var content = JSONUtil.ofObj().set("title", "设备发货提醒"); var content = JsonUtil.createObj().put("title", "设备发货提醒");
String template = """ String template = """
#### 发货通知 #### 发货通知
#### 合同名称:**{}** #### 合同名称:**{}**
...@@ -169,17 +168,18 @@ public class DeliveryRecordServiceImpl extends MPJBaseServiceImpl<DeliveryRecord ...@@ -169,17 +168,18 @@ public class DeliveryRecordServiceImpl extends MPJBaseServiceImpl<DeliveryRecord
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
contract.getName(), contract.getContractNo(), rec.getCourierCompany(), rec.getTrackingNumber(), rec.getConsignee(), DateUtil.formatDate(rec.getShipDate()), DateUtil.now()); contract.getName(), contract.getContractNo(), rec.getCourierCompany(), rec.getTrackingNumber(), rec.getConsignee(), DateUtil.formatDate(rec.getShipDate()), DateUtil.now());
content.set("markdown", markdown).set("btn_orientation", "1"); content.put("markdown", markdown).put("btn_orientation", "1");
var jsonArray = JSONUtil.ofArray() var jsonArray = JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("title", "查看详情") .put("title", "查看详情")
.set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FdeliveryId%3D" + rec.getId())); .put("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid" +
"=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FdeliveryId%3D" + rec.getId()));
content.set("btn_json_list", jsonArray); content.set("btn_json_list", jsonArray);
msg.set("msgtype", "action_card").set("action_card", content); msg.put("msgtype", "action_card").set("action_card", content);
jsonObj.set("msg", msg); jsonNode.set("msg", msg);
return jsonObj; return jsonNode.toString();
} }
private void saveFile(DeliveryRecordDTO dto, DeliveryRecord deliveryRecord) { private void saveFile(DeliveryRecordDTO dto, DeliveryRecord deliveryRecord) {
......
package vion.service.impl; package vion.service.impl;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl; import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper; import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter; import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import vion.dto.FormDTO; import vion.dto.FormDTO;
import vion.mapper.FormMapper; import vion.mapper.FormMapper;
...@@ -16,6 +15,7 @@ import vion.model.Account; ...@@ -16,6 +15,7 @@ import vion.model.Account;
import vion.model.Form; import vion.model.Form;
import vion.model.Store; import vion.model.Store;
import vion.service.IFormService; import vion.service.IFormService;
import vion.utils.JsonUtil;
import vion.vo.FormVO; import vion.vo.FormVO;
/** /**
...@@ -44,7 +44,7 @@ public class FormServiceImpl extends MPJBaseServiceImpl<FormMapper, Form> implem ...@@ -44,7 +44,7 @@ public class FormServiceImpl extends MPJBaseServiceImpl<FormMapper, Form> implem
Form form = converter.convert(dto, Form.class); Form form = converter.convert(dto, Form.class);
String nanoId = IdUtil.nanoId(); String nanoId = IdUtil.nanoId();
form.setUuid(nanoId); form.setUuid(nanoId);
return this.save(form) ? JSONUtil.ofObj().set("id", form.getId()).set("uuid", nanoId) : "创建失败"; return this.save(form) ? JsonUtil.createObj().put("id", form.getId()).put("uuid", nanoId) : "创建失败";
} }
@Override @Override
......
...@@ -14,8 +14,6 @@ import org.dromara.hutool.core.map.MapUtil; ...@@ -14,8 +14,6 @@ import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.math.NumberUtil; import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import vion.dto.InvoiceDTO; import vion.dto.InvoiceDTO;
...@@ -27,6 +25,7 @@ import vion.service.IContractService; ...@@ -27,6 +25,7 @@ import vion.service.IContractService;
import vion.service.IInvoiceService; import vion.service.IInvoiceService;
import vion.service.IRContractUserService; import vion.service.IRContractUserService;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.vo.InvoiceVO; import vion.vo.InvoiceVO;
import vion.vo.RoleVO; import vion.vo.RoleVO;
import vion.vo.UserVO; import vion.vo.UserVO;
...@@ -171,13 +170,12 @@ public class InvoiceServiceImpl extends MPJBaseServiceImpl<InvoiceMapper, Invoic ...@@ -171,13 +170,12 @@ public class InvoiceServiceImpl extends MPJBaseServiceImpl<InvoiceMapper, Invoic
return "金额计算成功"; return "金额计算成功";
} }
JSONObject buildMsg(String userid, Invoice invoice, Contract contract) { String buildMsg(String userid, Invoice invoice, Contract contract) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "开票提醒");
var content = JSONUtil.ofObj().set("title", "开票提醒");
String template = """ String template = """
#### 开票提醒 #### 开票提醒
#### 合同编号:**{}** #### 合同编号:**{}**
...@@ -190,10 +188,10 @@ public class InvoiceServiceImpl extends MPJBaseServiceImpl<InvoiceMapper, Invoic ...@@ -190,10 +188,10 @@ public class InvoiceServiceImpl extends MPJBaseServiceImpl<InvoiceMapper, Invoic
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
contract.getContractNo(), contract.getName(), invoice.getInvoiceNo(), invoice.getInvoiceAmount(), DateUtil.formatDate(invoice.getInvoicingTime()), invoice.getRemark(), DateUtil.now()); contract.getContractNo(), contract.getName(), invoice.getInvoiceNo(), invoice.getInvoiceAmount(), DateUtil.formatDate(invoice.getInvoicingTime()), invoice.getRemark(), DateUtil.now());
content.set("text", markdown); content.put("text", markdown);
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
} }
package vion.service.impl; package vion.service.impl;
import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.collection.CollUtil; import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.date.DateUtil; import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.lang.Assert; import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.Opt; import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.core.map.MapUtil; import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.json.JSONObject; import org.dromara.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import vion.dto.PaymentDTO; import vion.dto.PaymentDTO;
...@@ -28,6 +26,7 @@ import vion.service.IContractService; ...@@ -28,6 +26,7 @@ import vion.service.IContractService;
import vion.service.IPaymentService; import vion.service.IPaymentService;
import vion.service.IRContractUserService; import vion.service.IRContractUserService;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.vo.PaymentVO; import vion.vo.PaymentVO;
import vion.vo.RoleVO; import vion.vo.RoleVO;
import vion.vo.UserVO; import vion.vo.UserVO;
...@@ -181,13 +180,12 @@ public class PaymentServiceImpl extends MPJBaseServiceImpl<PaymentMapper, Paymen ...@@ -181,13 +180,12 @@ public class PaymentServiceImpl extends MPJBaseServiceImpl<PaymentMapper, Paymen
return "删除成功"; return "删除成功";
} }
JSONObject buildMsg(String userid, Payment payment, Contract contract) { String buildMsg(String userid, Payment payment, Contract contract) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "收款提醒");
var content = JSONUtil.ofObj().set("title", "收款提醒");
String template = """ String template = """
#### 收款提醒 #### 收款提醒
#### 合同编号:**{}** #### 合同编号:**{}**
...@@ -199,10 +197,10 @@ public class PaymentServiceImpl extends MPJBaseServiceImpl<PaymentMapper, Paymen ...@@ -199,10 +197,10 @@ public class PaymentServiceImpl extends MPJBaseServiceImpl<PaymentMapper, Paymen
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
contract.getContractNo(), contract.getName(), payment.getPaymentAmount(), DateUtil.formatDate(payment.getCollectionTime()), payment.getRemark(), DateUtil.now()); contract.getContractNo(), contract.getName(), payment.getPaymentAmount(), DateUtil.formatDate(payment.getCollectionTime()), payment.getRemark(), DateUtil.now());
content.set("text", markdown); content.put("text", markdown);
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
} }
package vion.service.impl; package vion.service.impl;
import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.stp.StpUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
...@@ -27,7 +14,18 @@ import me.chanjar.weixin.common.error.WxErrorException; ...@@ -27,7 +14,18 @@ import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser; import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData; import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import org.dromara.hutool.json.JSONUtil; import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -39,6 +37,7 @@ import vion.model.*; ...@@ -39,6 +37,7 @@ import vion.model.*;
import vion.service.*; import vion.service.*;
import vion.third.DingMod; import vion.third.DingMod;
import vion.third.WechatMod; import vion.third.WechatMod;
import vion.utils.JsonUtil;
import vion.utils.ResultUtil; import vion.utils.ResultUtil;
import vion.vo.PointInfoVO; import vion.vo.PointInfoVO;
import vion.vo.UserVO; import vion.vo.UserVO;
...@@ -491,11 +490,11 @@ public class PointInfoServiceImpl extends MPJBaseServiceImpl<PointInfoMapper, Po ...@@ -491,11 +490,11 @@ public class PointInfoServiceImpl extends MPJBaseServiceImpl<PointInfoMapper, Po
} }
String buildMsg(String title, String content) { String buildMsg(String title, String content) {
var jsonObj = JSONUtil.ofObj().set("msgtype", "markdown"); var jsonObj = JsonUtil.createObj().put("msgtype", "markdown");
JSONObject markdown = JSONUtil.ofObj() var markdown = JsonUtil.createObj()
.set("title", title) .put("title", title)
.set("text", content); .put("text", content);
jsonObj.set("markdown", markdown); jsonObj.set("markdown", markdown);
return jsonObj.toString(); return jsonObj.toString();
} }
......
...@@ -15,7 +15,6 @@ import org.dromara.hutool.core.map.MapUtil; ...@@ -15,7 +15,6 @@ import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import vion.dto.RepairRecDTO; import vion.dto.RepairRecDTO;
...@@ -24,6 +23,7 @@ import vion.model.*; ...@@ -24,6 +23,7 @@ import vion.model.*;
import vion.service.IFileService; import vion.service.IFileService;
import vion.service.IRepairRecService; import vion.service.IRepairRecService;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.vo.RepairRecVO; import vion.vo.RepairRecVO;
import vion.vo.UserVO; import vion.vo.UserVO;
...@@ -138,12 +138,11 @@ public class RepairRecServiceImpl extends MPJBaseServiceImpl<RepairRecMapper, Re ...@@ -138,12 +138,11 @@ public class RepairRecServiceImpl extends MPJBaseServiceImpl<RepairRecMapper, Re
.map(l -> l.stream().map(RRepairDevice::getDeviceNo).collect(Collectors.joining(","))) .map(l -> l.stream().map(RRepairDevice::getDeviceNo).collect(Collectors.joining(",")))
.orElse("暂无"); .orElse("暂无");
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "返修设备已发货");
var content = JSONUtil.ofObj().set("title", "返修设备已发货");
String text = StrUtil.format(""" String text = StrUtil.format("""
### 返修设备已发货 ### 返修设备已发货
### 项目名称:{} ### 项目名称:{}
...@@ -154,12 +153,12 @@ public class RepairRecServiceImpl extends MPJBaseServiceImpl<RepairRecMapper, Re ...@@ -154,12 +153,12 @@ public class RepairRecServiceImpl extends MPJBaseServiceImpl<RepairRecMapper, Re
""", repairRecVO.getProjectName(), Opt.ofBlankAble(repairRecVO.getTrackingNumber()).orElse("暂无"), """, repairRecVO.getProjectName(), Opt.ofBlankAble(repairRecVO.getTrackingNumber()).orElse("暂无"),
deviceNoStr, deviceNoStr,
Opt.ofBlankAble(DateUtil.formatDate(repairRecVO.getShipDate())).orElse("暂无"), DateUtil.now()); Opt.ofBlankAble(DateUtil.formatDate(repairRecVO.getShipDate())).orElse("暂无"), DateUtil.now());
content.set("text", text); content.put("text", text);
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
var pushRes = dingMod.workMsg(jsonObj); var pushRes = dingMod.workMsg(jsonObj.toString());
return StrUtil.containsIgnoreCase(pushRes, "ok"); return StrUtil.containsIgnoreCase(pushRes, "ok");
} }
} }
...@@ -15,7 +15,6 @@ import org.dromara.hutool.core.map.MapUtil; ...@@ -15,7 +15,6 @@ import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import vion.dto.SparePartDTO; import vion.dto.SparePartDTO;
...@@ -24,6 +23,7 @@ import vion.model.*; ...@@ -24,6 +23,7 @@ import vion.model.*;
import vion.service.IFileService; import vion.service.IFileService;
import vion.service.ISparePartService; import vion.service.ISparePartService;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.vo.SparePartVO; import vion.vo.SparePartVO;
import vion.vo.UserVO; import vion.vo.UserVO;
...@@ -132,12 +132,11 @@ public class SparePartServiceImpl extends MPJBaseServiceImpl<SparePartMapper, Sp ...@@ -132,12 +132,11 @@ public class SparePartServiceImpl extends MPJBaseServiceImpl<SparePartMapper, Sp
.map(l -> l.stream().map(RRepairDevice::getDeviceNo).collect(Collectors.joining(","))) .map(l -> l.stream().map(RRepairDevice::getDeviceNo).collect(Collectors.joining(",")))
.orElse("暂无"); .orElse("暂无");
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "备件已发货");
var content = JSONUtil.ofObj().set("title", "备件已发货");
String text = StrUtil.format(""" String text = StrUtil.format("""
### 备件已发货 ### 备件已发货
### 项目名称:{} ### 项目名称:{}
...@@ -148,12 +147,12 @@ public class SparePartServiceImpl extends MPJBaseServiceImpl<SparePartMapper, Sp ...@@ -148,12 +147,12 @@ public class SparePartServiceImpl extends MPJBaseServiceImpl<SparePartMapper, Sp
""", sparePartVO.getProjectName(), Opt.ofBlankAble(sparePartVO.getTrackingNumber()).orElse("暂无"), """, sparePartVO.getProjectName(), Opt.ofBlankAble(sparePartVO.getTrackingNumber()).orElse("暂无"),
deviceNoStr, deviceNoStr,
Opt.ofBlankAble(DateUtil.formatDate(sparePartVO.getShipDate())).orElse("暂无"), DateUtil.now()); Opt.ofBlankAble(DateUtil.formatDate(sparePartVO.getShipDate())).orElse("暂无"), DateUtil.now());
content.set("text", text); content.put("text", text);
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
var pushRes = dingMod.workMsg(jsonObj); var pushRes = dingMod.workMsg(jsonObj.toString());
return StrUtil.containsIgnoreCase(pushRes, "ok"); return StrUtil.containsIgnoreCase(pushRes, "ok");
} }
......
...@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.metadata.OrderItem; ...@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db; import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.liaochong.myexcel.core.DefaultExcelBuilder; import com.github.liaochong.myexcel.core.DefaultExcelBuilder;
import com.github.liaochong.myexcel.core.watermark.Watermark; import com.github.liaochong.myexcel.core.watermark.Watermark;
import com.github.liaochong.myexcel.utils.WatermarkUtil; import com.github.liaochong.myexcel.utils.WatermarkUtil;
...@@ -27,8 +28,6 @@ import org.dromara.hutool.core.util.ObjUtil; ...@@ -27,8 +28,6 @@ import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.cron.CronUtil; import org.dromara.hutool.cron.CronUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.http.html.HtmlUtil; import org.dromara.hutool.http.html.HtmlUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RedissonClient; import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -43,6 +42,7 @@ import vion.mapper.TaskMapper; ...@@ -43,6 +42,7 @@ import vion.mapper.TaskMapper;
import vion.model.*; import vion.model.*;
import vion.service.*; import vion.service.*;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.utils.excel.AttachmentExportUtil; import vion.utils.excel.AttachmentExportUtil;
import vion.vo.ContractVO; import vion.vo.ContractVO;
import vion.vo.StoreVO; import vion.vo.StoreVO;
...@@ -457,17 +457,17 @@ public class StoreServiceImpl extends MPJBaseServiceImpl<StoreMapper, Store> imp ...@@ -457,17 +457,17 @@ public class StoreServiceImpl extends MPJBaseServiceImpl<StoreMapper, Store> imp
### 内容: ### 内容:
> {} > {}
""", storeVO.getName(), user.getUsername(), DateUtil.formatDate(storeLog.getLogDate()), logText); """, storeVO.getName(), user.getUsername(), DateUtil.formatDate(storeLog.getLogDate()), logText);
var markdown = JSONUtil.ofObj() var markdown = JsonUtil.createObj()
.set("title", "项目日志提醒") .put("title", "项目日志提醒")
.set("text", text); .put("text", text);
JSONObject atObj = null; JsonNode atObj = null;
if (ArrayUtil.isNotEmpty(userIdStr)) { if (ArrayUtil.isNotEmpty(userIdStr)) {
var arr = JSONUtil.ofArray(); var arr = JsonUtil.createArr();
Arrays.stream(userIdStr).forEach(arr::put); Arrays.stream(userIdStr).forEach(arr::add);
var atUser = Arrays.stream(userIdStr).collect(Collectors.joining("@", "@", "")); var atUser = Arrays.stream(userIdStr).collect(Collectors.joining("@", "@", ""));
System.out.println(atUser); System.out.println(atUser);
atObj = JSONUtil.ofObj().set("atUserIds", arr); atObj = JsonUtil.createObj().set("atUserIds", arr);
text = StrUtil.format(""" text = StrUtil.format("""
### 项目日志 ### 项目日志
### 查收人:{} ### 查收人:{}
...@@ -477,13 +477,14 @@ public class StoreServiceImpl extends MPJBaseServiceImpl<StoreMapper, Store> imp ...@@ -477,13 +477,14 @@ public class StoreServiceImpl extends MPJBaseServiceImpl<StoreMapper, Store> imp
### 内容: ### 内容:
> {} > {}
""", atUser, storeVO.getName(), user.getUsername(), DateUtil.formatDate(storeLog.getLogDate()), logText); """, atUser, storeVO.getName(), user.getUsername(), DateUtil.formatDate(storeLog.getLogDate()), logText);
markdown.set("text", text); markdown.put("text", text);
} }
var body = JSONUtil.ofObj() var body = JsonUtil.createObj()
.set("msgtype", "markdown") .put("msgtype", "markdown")
.set("markdown", markdown) .putPOJO("markdown", markdown)
.setOpt("at", atObj); // fixme atObj is null, dont add it
.putPOJO("at", atObj);
var pushRes = dingMod.robotPush(storeVO.getBotToken(), body.toString()); var pushRes = dingMod.robotPush(storeVO.getBotToken(), body.toString());
return StrUtil.containsIgnoreCase(pushRes, "ok"); return StrUtil.containsIgnoreCase(pushRes, "ok");
} }
...@@ -684,50 +685,48 @@ public class StoreServiceImpl extends MPJBaseServiceImpl<StoreMapper, Store> imp ...@@ -684,50 +685,48 @@ public class StoreServiceImpl extends MPJBaseServiceImpl<StoreMapper, Store> imp
Collectors.counting()))); Collectors.counting())));
} }
JSONObject buildMsg(String storeName, String userid) { String buildMsg(String storeName, String userid) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj()
var content = JSONUtil.ofObj() .put("title", "项目日志提醒")
.set("title", "项目日志提醒") .put("text", StrUtil.format("""
.set("text", StrUtil.format("""
#### 项目:[{}]请及时提交日志 #### 项目:[{}]请及时提交日志
#### 发送时间:{}""", storeName, DateUtil.now())); #### 发送时间:{}""", storeName, DateUtil.now()));
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
JSONObject buildMsg1(String storeName, String contractNo, String sourceName, String buildMsg1(String storeName, String contractNo, String sourceName,
String[] fileNameArr, String[] userIdStr) { String[] fileNameArr, String[] userIdStr) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", String.join(",", userIdStr)); .put("userid_list", String.join(",", userIdStr));
UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser"); UserVO userVO = (UserVO) StpUtil.getTokenSession().get("curLoginUser");
var msg = new JSONObject(); String fileNameStr = Arrays.stream(fileNameArr)
var content = new JSONObject(); .map(v -> StrUtil.format("{}. {}", Arrays.asList(fileNameArr).indexOf(v) + 1, v))
.collect(Collectors.joining("\n"));
String fileNameStr = Arrays.stream(fileNameArr).map(v -> StrUtil.format("{}. {}",
Arrays.asList(fileNameArr).indexOf(v) + 1, v)).collect(Collectors.joining("\n")); var content = JsonUtil.createObj()
.put("title", "项目资料提交提醒")
content.set("title", "项目资料提交提醒") .put("text", StrUtil.format("""
.set("text", StrUtil.format(""" ### 项目资料提交提醒
### 项目资料提交提醒 #### 项目名称:{}
#### 项目名称:{} #### 合同编号:{}
#### 合同编号:{} #### 上传人:{}
#### 上传人:{} #### 资料类型:{}
#### 资料类型:{} #### 资料名称:
#### 资料名称: {}
{} #### 发送时间:{}""", storeName, contractNo, userVO.getUsername(), sourceName, fileNameStr,
#### 发送时间:{}""", storeName, contractNo, userVO.getUsername(), sourceName, fileNameStr,
DateUtil.now())); DateUtil.now()));
msg.set("msgtype", "markdown").set("markdown", content); var msg = JsonUtil.createObj().put("msgtype", "markdown").set("markdown", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
} }
...@@ -22,8 +22,6 @@ import org.dromara.hutool.core.map.MapUtil; ...@@ -22,8 +22,6 @@ import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RMap; import org.redisson.api.RMap;
import org.redisson.api.RedissonClient; import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
...@@ -37,6 +35,7 @@ import vion.model.*; ...@@ -37,6 +35,7 @@ import vion.model.*;
import vion.service.*; import vion.service.*;
import vion.third.DingMod; import vion.third.DingMod;
import vion.third.WechatMod; import vion.third.WechatMod;
import vion.utils.JsonUtil;
import vion.vo.RoleVO; import vion.vo.RoleVO;
import vion.vo.TaskTempVO; import vion.vo.TaskTempVO;
import vion.vo.TaskVO; import vion.vo.TaskVO;
...@@ -328,7 +327,7 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -328,7 +327,7 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
.map(User::getUserid) .map(User::getUserid)
.ifPresent(useridList::add); .ifPresent(useridList::add);
} }
JSONObject msg = buildMsg(String.join(",", useridList), store.getName(), existTask); var msg = buildMsg(String.join(",", useridList), store.getName(), existTask);
String pushRes = dingMod.workMsg(msg); String pushRes = dingMod.workMsg(msg);
// todo 异步微信公众号消息推送 // todo 异步微信公众号消息推送
...@@ -357,8 +356,8 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -357,8 +356,8 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
* 文件处理 * 文件处理
* *
* @param files 文件列表 * @param files 文件列表
* @param task 工单 * @param task 工单
* @param user 当前登录用户 * @param user 当前登录用户
*/ */
private void handleFiles(MultipartFile[] files, Task task, UserVO user) { private void handleFiles(MultipartFile[] files, Task task, UserVO user) {
Opt.ofNullable(files) Opt.ofNullable(files)
...@@ -422,7 +421,7 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -422,7 +421,7 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
Task task = this.getById(taskId); Task task = this.getById(taskId);
Store store = storeService.getById(task.getStoreId()); Store store = storeService.getById(task.getStoreId());
JSONObject msg = buildMsg3(forwardUser, store.getName(), task); var msg = buildMsg3(forwardUser, store.getName(), task);
String pushRes = dingMod.workMsg(msg); String pushRes = dingMod.workMsg(msg);
return StrUtil.contains(pushRes, "ok") ? "成功" : "失败"; return StrUtil.contains(pushRes, "ok") ? "成功" : "失败";
} }
...@@ -437,7 +436,7 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -437,7 +436,7 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
.orElse(null); .orElse(null);
Store store = storeService.getById(task.getStoreId()); Store store = storeService.getById(task.getStoreId());
JSONObject msg = buildMsg4(userid, store.getName(), task, remark); var msg = buildMsg4(userid, store.getName(), task, remark);
String pushRes = dingMod.workMsg(msg); String pushRes = dingMod.workMsg(msg);
return StrUtil.contains(pushRes, "ok") ? "成功" : "失败"; return StrUtil.contains(pushRes, "ok") ? "成功" : "失败";
} }
...@@ -546,15 +545,14 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -546,15 +545,14 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
return resMap; return resMap;
} }
JSONObject buildMsg(String userid, String storeName, Task task) { String buildMsg(String userid, String storeName, Task task) {
RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal()); RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal());
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "您有一条新工单请及时处理哦~_~");
var content = JSONUtil.ofObj().set("title", "您有一条新工单请及时处理哦~_~");
String template = """ String template = """
### 工单流转消息通知 ### 工单流转消息通知
#### 门店信息: **{}** [FullOfVitality] #### 门店信息: **{}** [FullOfVitality]
...@@ -567,26 +565,25 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -567,26 +565,25 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), task.getFaultDescription(), DateUtil.now()); storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), task.getFaultDescription(), DateUtil.now());
content.set("markdown", markdown).set("btn_orientation", "1"); content.put("markdown", markdown).put("btn_orientation", "1");
var jsonArray = JSONUtil.ofArray() var jsonArray = JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("title", "查看详情") .put("title", "查看详情")
.set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FstoreId%3D" + task.getStoreId() + "%26taskId%3D" + task.getId())); .put("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FstoreId%3D" + task.getStoreId() + "%26taskId%3D" + task.getId()));
content.set("btn_json_list", jsonArray); content.set("btn_json_list", jsonArray);
msg.set("msgtype", "action_card").set("action_card", content); var msg = JsonUtil.createObj().put("msgtype", "action_card").set("action_card", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
JSONObject buildMsg2(String userid, String storeName, Task task) { String buildMsg2(String userid, String storeName, Task task) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "工单消息提醒");
var content = JSONUtil.ofObj().set("title", "工单消息提醒");
String template = """ String template = """
### 客户工单提醒 ### 客户工单提醒
#### 门店信息: **{}** #### 门店信息: **{}**
...@@ -597,26 +594,25 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -597,26 +594,25 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
storeName, task.getRepairPeople(), task.getRepairPhone(), task.getFaultDescription(), DateUtil.now()); storeName, task.getRepairPeople(), task.getRepairPhone(), task.getFaultDescription(), DateUtil.now());
content.set("markdown", markdown).set("btn_orientation", "1"); content.put("markdown", markdown).put("btn_orientation", "1");
var jsonArray = JSONUtil.ofArray() var jsonArray = JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("title", "查看详情") .put("title", "查看详情")
.set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FtaskUuid%3D" + task.getUuid())); .put("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FtaskUuid%3D" + task.getUuid()));
content.set("btn_json_list", jsonArray); content.set("btn_json_list", jsonArray);
msg.set("msgtype", "action_card").set("action_card", content); var msg = JsonUtil.createObj().put("msgtype", "action_card").set("action_card", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
JSONObject buildMsg3(String userid, String storeName, Task task) { String buildMsg3(String userid, String storeName, Task task) {
RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal()); RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal());
var jsonObj = JSONUtil.ofObj().set("agent_id", 2358374016L).set("userid_list", userid); var jsonObj = JsonUtil.createObj().put("agent_id", 2358374016L).put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "工单转发提醒");
var content = JSONUtil.ofObj().set("title", "工单转发提醒");
String template = """ String template = """
### 工单转发提醒 ### 工单转发提醒
#### 门店信息: **{}** [FullOfVitality] #### 门店信息: **{}** [FullOfVitality]
...@@ -629,28 +625,27 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -629,28 +625,27 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), task.getFaultDescription(), DateUtil.now()); storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), task.getFaultDescription(), DateUtil.now());
content.set("markdown", markdown).set("btn_orientation", "1"); content.put("markdown", markdown).put("btn_orientation", "1");
var jsonArray = JSONUtil.ofArray() var jsonArray = JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("title", "查看详情") .put("title", "查看详情")
.set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FtaskUuid%3D" + task.getUuid())); .put("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FtaskUuid%3D" + task.getUuid()));
content.set("btn_json_list", jsonArray); content.set("btn_json_list", jsonArray);
msg.set("msgtype", "action_card").set("action_card", content); var msg = JsonUtil.createObj().put("msgtype", "action_card").set("action_card", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
JSONObject buildMsg4(String userid, String storeName, Task task, String remark) { String buildMsg4(String userid, String storeName, Task task, String remark) {
RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal()); RMap<Integer, String> orderStatusMap = redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.ORDER_STATUS.getVal());
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj(); var content = JsonUtil.createObj().put("title", "工单催办提醒");
var content = JSONUtil.ofObj().set("title", "工单催办提醒");
String template = """ String template = """
### 工单催办提醒 ### 工单催办提醒
#### 门店信息: **{}** [FullOfVitality] #### 门店信息: **{}** [FullOfVitality]
...@@ -663,16 +658,16 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem ...@@ -663,16 +658,16 @@ public class TaskServiceImpl extends MPJBaseServiceImpl<TaskMapper, Task> implem
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), remark, DateUtil.now()); storeName, task.getUuid(), task.getRepairPeople(), task.getRepairPhone(), orderStatusMap.get(task.getStatus()), remark, DateUtil.now());
content.set("markdown", markdown).set("btn_orientation", "1"); content.put("markdown", markdown).put("btn_orientation", "1");
var jsonArray = JSONUtil.ofArray() var jsonArray = JsonUtil.createArr()
.put(JSONUtil.ofObj() .add(JsonUtil.createObj()
.set("title", "查看详情") .put("title", "查看详情")
.set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FstoreId%3D" + task.getStoreId() + "%26taskId%3D" + task.getId())); .put("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FstoreId%3D" + task.getStoreId() + "%26taskId%3D" + task.getId()));
content.set("btn_json_list", jsonArray); content.set("btn_json_list", jsonArray);
msg.set("msgtype", "action_card").set("action_card", content); var msg = JsonUtil.createObj().put("msgtype", "action_card").set("action_card", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
} }
...@@ -20,8 +20,6 @@ import org.dromara.hutool.core.math.NumberUtil; ...@@ -20,8 +20,6 @@ import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.text.StrUtil; import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RedissonClient; import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -32,6 +30,7 @@ import vion.service.IFileService; ...@@ -32,6 +30,7 @@ import vion.service.IFileService;
import vion.service.ITaskTempService; import vion.service.ITaskTempService;
import vion.service.IUserService; import vion.service.IUserService;
import vion.third.DingMod; import vion.third.DingMod;
import vion.utils.JsonUtil;
import vion.vo.TaskTempVO; import vion.vo.TaskTempVO;
import java.io.File; import java.io.File;
...@@ -151,14 +150,11 @@ public class TaskTempServiceImpl extends MPJBaseServiceImpl<TaskTempMapper, Task ...@@ -151,14 +150,11 @@ public class TaskTempServiceImpl extends MPJBaseServiceImpl<TaskTempMapper, Task
return Map.of(); return Map.of();
} }
JSONObject buildMsg(String userid, TaskTemp taskTemp) { String buildMsg(String userid, TaskTemp taskTemp) {
var jsonObj = JSONUtil.ofObj() var jsonObj = JsonUtil.createObj()
.set("agent_id", 2358374016L) .put("agent_id", 2358374016L)
.set("userid_list", userid); .put("userid_list", userid);
var msg = JSONUtil.ofObj();
var content = JSONUtil.ofObj()
.set("title", "客户提交工单,请及时处理哦~_~");
String template = """ String template = """
### 客户提交工单提醒 ### 客户提交工单提醒
#### 门店信息: **{}** #### 门店信息: **{}**
...@@ -169,17 +165,19 @@ public class TaskTempServiceImpl extends MPJBaseServiceImpl<TaskTempMapper, Task ...@@ -169,17 +165,19 @@ public class TaskTempServiceImpl extends MPJBaseServiceImpl<TaskTempMapper, Task
"""; """;
String markdown = StrUtil.format(template, String markdown = StrUtil.format(template,
taskTemp.getStoreName(), taskTemp.getRepairPeople(), taskTemp.getRepairPhone(), taskTemp.getFaultDescription(), DateUtil.now()); taskTemp.getStoreName(), taskTemp.getRepairPeople(), taskTemp.getRepairPhone(), taskTemp.getFaultDescription(), DateUtil.now());
content.set("markdown", markdown).set("btn_orientation", "1"); var content = JsonUtil.createObj()
.put("title", "客户提交工单,请及时处理哦~_~")
var jsonArray = JSONUtil.ofArray() .put("markdown", markdown).put("btn_orientation", "1");
.put(JSONUtil.ofObj()
.set("title", "查看详情") var jsonArray = JsonUtil.createArr()
.set("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FtaskTempId%3D" + taskTemp.getId())); .add(JsonUtil.createObj()
.put("title", "查看详情")
.put("action_url", "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingkrzwks0jpi2di3uo&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=https%3A%2F%2Fyunwei.vionyun.com%3A8443%2Fyunwei%2Fapi%2Fding%2Fcallback%2Finside%3FtaskTempId%3D" + taskTemp.getId()));
content.set("btn_json_list", jsonArray); content.set("btn_json_list", jsonArray);
msg.set("msgtype", "action_card").set("action_card", content); var msg = JsonUtil.createObj().put("msgtype", "action_card").set("action_card", content);
jsonObj.set("msg", msg); jsonObj.set("msg", msg);
return jsonObj; return jsonObj.toString();
} }
/** /**
......
package vion.third; package vion.third;
import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.linpeilie.Converter; import io.github.linpeilie.Converter;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
...@@ -14,9 +15,6 @@ import org.dromara.hutool.core.text.StrUtil; ...@@ -14,9 +15,6 @@ import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil; import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.crypto.SecureUtil; import org.dromara.hutool.crypto.SecureUtil;
import org.dromara.hutool.crypto.digest.mac.HMac; import org.dromara.hutool.crypto.digest.mac.HMac;
import org.dromara.hutool.json.JSONArray;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.redisson.api.RedissonClient; import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
...@@ -26,6 +24,7 @@ import vion.constant.RedisKeyEnum; ...@@ -26,6 +24,7 @@ import vion.constant.RedisKeyEnum;
import vion.dto.DingDTO; import vion.dto.DingDTO;
import vion.model.*; import vion.model.*;
import vion.service.*; import vion.service.*;
import vion.utils.JsonUtil;
import vion.vo.RoleVO; import vion.vo.RoleVO;
import vion.vo.UserVO; import vion.vo.UserVO;
...@@ -70,17 +69,18 @@ public class DingMod { ...@@ -70,17 +69,18 @@ public class DingMod {
public String getToken() { public String getToken() {
return (String) Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.ACCESS_TOKEN.getVal()).get()) return (String) Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.ACCESS_TOKEN.getVal()).get())
.orElseGet(() -> { .orElseGet(() -> {
String res = oDingRestClient.get() JsonNode tokenJson = oDingRestClient.get()
.uri("/gettoken?appkey=" + appKey + "&appsecret=" + appSecret) .uri("/gettoken?appkey={appKey}&appsecret={appSecret}", appKey, appSecret)
.retrieve() .retrieve()
.body(String.class); .body(JsonNode.class);
JSONObject jsonObj = JSONUtil.parseObj(res); return Opt.ofNullable(tokenJson)
if (jsonObj.containsKey("access_token")) { .map(jsonNode -> {
String accessToken = jsonObj.getStr("access_token"); String accessToken = jsonNode.path("access_token").asText();
redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.ACCESS_TOKEN.getVal()).set(accessToken, Duration.ofSeconds(7000)); redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.ACCESS_TOKEN.getVal())
return accessToken; .set(accessToken, Duration.ofSeconds(7000));
} return accessToken;
return ""; })
.orElse("");
}); });
} }
...@@ -95,22 +95,21 @@ public class DingMod { ...@@ -95,22 +95,21 @@ public class DingMod {
boolean flag = true; boolean flag = true;
while (flag) { while (flag) {
// 2:试用期 3:正式 5:待离职 -1:无状态 // 2:试用期 3:正式 5:待离职 -1:无状态
JSONObject paramJson = JSONUtil.ofObj() var paramJson = JsonUtil.createObj()
.set("status_list", "2,3,5,-1") .put("status_list", "2,3,5,-1")
.set("size", 50) .put("size", 50)
.set("offset", offset); .put("offset", offset);
var jsonObject = oDingRestClient.post() var jsonNode = oDingRestClient.post()
.uri("/topapi/smartwork/hrm/employee/queryonjob?access_token=" + accessToken) .uri("/topapi/smartwork/hrm/employee/queryonjob?access_token={accessToken}", accessToken)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(paramJson.toString()) .body(paramJson.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jsonObject.getBool("success", false)) { if (ObjUtil.isNotNull(jsonNode) && jsonNode.path("success").asBoolean(false)) {
JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("data_list"); jsonNode.path("result").withArray("data_list")
List<String> list = jsonArray.toList(String.class); .forEach(v -> userIdList.add(v.asText()));
userIdList.addAll(list);
Long nextCursor = jsonObject.getJSONObject("result").getLong("next_cursor"); Long nextCursor = jsonNode.path("result").path("next_cursor").asLong();
if (ObjUtil.isNotNull(nextCursor)) { if (ObjUtil.isNotNull(nextCursor)) {
offset = nextCursor; offset = nextCursor;
} else { } else {
...@@ -126,49 +125,50 @@ public class DingMod { ...@@ -126,49 +125,50 @@ public class DingMod {
List<List<String>> userIdListSplit = ListUtil.partition(userIdList, 90); List<List<String>> userIdListSplit = ListUtil.partition(userIdList, 90);
userIdListSplit.forEach(tmpList -> { userIdListSplit.forEach(tmpList -> {
JSONObject paramJson = JSONUtil.ofObj() var paramJson = JsonUtil.createObj()
.set("agentid", 2358374016L) .put("agentid", 2358374016L)
.set("userid_list", String.join(",", tmpList)) .put("userid_list", String.join(",", tmpList))
.set("field_filter_list", "sys00-name,sys00-mobile,sys00-mainDeptId,sys00-mainDept,sys01-employeeStatus"); .put("field_filter_list", "sys00-name,sys00-mobile,sys00-mainDeptId,sys00-mainDept,sys01-employeeStatus");
var jsonObject = oDingRestClient.post() var jsonNode = oDingRestClient.post()
.uri("/topapi/smartwork/hrm/employee/v2/list?access_token=" + accessToken) .uri("/topapi/smartwork/hrm/employee/v2/list?access_token=" + accessToken)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(paramJson.toString()) .body(paramJson.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (jsonObject.getBool("success", false)) { var success = ObjUtil.isNotNull(jsonNode) && jsonNode.path("success").asBoolean(false);
JSONArray resArr = jsonObject.getJSONArray("result"); if (!success) {
for (Object o : resArr) { log.error("获取用户列表失败:{}", jsonNode);
User user = new User(); return;
JSONObject jsonObj = JSONUtil.parseObj(o); }
String userid = jsonObj.getStr("userid"); var resArr = jsonNode.withArray("result");
user.setUserid(userid); for (JsonNode o : resArr) {
User user = new User();
JSONArray dataArr = jsonObj.getJSONArray("field_data_list"); String userid = o.path("userid").asText();
for (Object o1 : dataArr) { user.setUserid(userid);
JSONObject tmpObj = JSONUtil.parseObj(o1);
if (StrUtil.equals("sys00-name", tmpObj.getStr("field_code"))) { var dataArr = o.withArray("field_data_list");
user.setUsername(tmpObj.getJSONArray("field_value_list").getByPath("[0].value", String.class)); for (JsonNode o1 : dataArr) {
} else if (StrUtil.equals("sys00-mobile", tmpObj.getStr("field_code"))) { if (StrUtil.equals("sys00-name", o1.path("field_code").asText())) {
user.setPhone(Opt.ofNullable((String) tmpObj.getJSONArray("field_value_list").getByPath("[0].value", String.class)).orElse("")); user.setUsername(o1.withArray("field_value_list").path(0).path("value").asText());
} else if (StrUtil.equals("sys00-mainDeptId", tmpObj.getStr("field_code"))) { } else if (StrUtil.equals("sys00-mobile", o1.path("field_code").asText())) {
user.setDeptId(tmpObj.getJSONArray("field_value_list").getByPath("[0].value", Long.class)); user.setPhone(o1.withArray("field_value_list").path(0).path("value").asText(""));
} else if (StrUtil.equals("sys01-employeeStatus", tmpObj.getStr("field_code"))) { } else if (StrUtil.equals("sys00-mainDeptId", o1.path("field_code").asText())) {
user.setEmployeeStatus(tmpObj.getJSONArray("field_value_list").getByPath("[0].value", Integer.class)); user.setDeptId(o1.withArray("field_value_list").path(0).path("value").asLong());
} } else if (StrUtil.equals("sys01-employeeStatus", o1.path("field_code").asText())) {
user.setEmployeeStatus(o1.withArray("field_value_list").path(0).path("value").asInt());
} }
userService.lambdaQuery()
.eq(User::getUserid, userid)
.oneOpt()
.ifPresentOrElse(u -> {
user.setId(u.getId());
userService.updateById(user);
}, () -> userService.save(user));
User one = userService.lambdaQuery().eq(User::getUserid, userid).one();
redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_ID.getVal() + one.getId()).set(user);
redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_NAME.getVal() + one.getUsername()).set(user);
} }
userService.lambdaQuery()
.eq(User::getUserid, userid)
.oneOpt()
.ifPresentOrElse(u -> {
user.setId(u.getId());
userService.updateById(user);
}, () -> userService.save(user));
User one = userService.lambdaQuery().eq(User::getUserid, userid).one();
redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_ID.getVal() + one.getId()).set(user);
redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_NAME.getVal() + one.getUsername()).set(user);
} }
}); });
} }
...@@ -184,31 +184,34 @@ public class DingMod { ...@@ -184,31 +184,34 @@ public class DingMod {
while (idx < deptIdList.size()) { while (idx < deptIdList.size()) {
// 2:试用期 3:正式 5:待离职 -1:无状态 // 2:试用期 3:正式 5:待离职 -1:无状态
Long value = deptIdList.get(idx++); Long value = deptIdList.get(idx++);
var jsonObject = oDingRestClient.post() var jsonNode = oDingRestClient.post()
.uri("/topapi/v2/department/listsub?access_token=" + accessToken) .uri("/topapi/v2/department/listsub?access_token=" + accessToken)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(JSONUtil.ofObj().set("dept_id", value).toString()) .body(JsonUtil.createObj().put("dept_id", value).toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (StrUtil.equals("ok", jsonObject.getStr("errmsg"))) { var success = ObjUtil.isNotNull(jsonNode) && StrUtil.equals("ok", jsonNode.path("errmsg").asText());
JSONArray resArr = jsonObject.getJSONArray("result"); if (!success) {
if (CollUtil.isNotEmpty(resArr)) { log.error("获取部门列表失败:{}", jsonNode);
for (Object o : resArr) { return;
Dept dept = new Dept(); }
JSONObject jsonObj = JSONUtil.parseObj(o);
Long deptId = jsonObj.getLong("dept_id"); var resArr = jsonNode.withArray("result");
dept.setDeptId(deptId); if (CollUtil.isNotEmpty(resArr)) {
dept.setParentId(jsonObj.getLong("parent_id")); for (JsonNode o : resArr) {
dept.setDeptName(jsonObj.getStr("name")); Dept dept = new Dept();
deptService.lambdaQuery() var deptId = o.path("dept_id").asLong();
.eq(Dept::getDeptId, deptId) dept.setDeptId(deptId);
.oneOpt() dept.setParentId(o.path("parent_id").asLong());
.ifPresentOrElse(d -> { dept.setDeptName(o.path("name").asText());
dept.setId(d.getId()); deptService.lambdaQuery()
deptService.updateById(dept); .eq(Dept::getDeptId, deptId)
}, () -> deptService.save(dept)); .oneOpt()
deptIdList.add(deptId); .ifPresentOrElse(d -> {
} dept.setId(d.getId());
deptService.updateById(dept);
}, () -> deptService.save(dept));
deptIdList.add(deptId);
} }
} }
} }
...@@ -217,12 +220,12 @@ public class DingMod { ...@@ -217,12 +220,12 @@ public class DingMod {
/** /**
* 钉钉工作消息推送 * 钉钉工作消息推送
*/ */
public String workMsg(JSONObject msg) { public String workMsg(String msg) {
String token = getToken(); String token = getToken();
var res = oDingRestClient.post() var res = oDingRestClient.post()
.uri("/topapi/message/corpconversation/asyncsend_v2?access_token=" + token) .uri("/topapi/message/corpconversation/asyncsend_v2?access_token=" + token)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(msg.toString()) .body(msg)
.retrieve() .retrieve()
.body(String.class); .body(String.class);
log.info("钉钉工作通知消息推送:{}", res); log.info("钉钉工作通知消息推送:{}", res);
...@@ -239,41 +242,41 @@ public class DingMod { ...@@ -239,41 +242,41 @@ public class DingMod {
*/ */
public Object dingCallback(String target, DingDTO dto, HttpServletResponse res) { public Object dingCallback(String target, DingDTO dto, HttpServletResponse res) {
if (StrUtil.equals(target, "login")) { if (StrUtil.equals(target, "login")) {
JSONObject jsonObject = JSONUtil.ofObj() var objNode = JsonUtil.createObj()
.set("clientId", appKey) .put("clientId", appKey)
.set("clientSecret", appSecret) .put("clientSecret", appSecret)
.set("code", dto.getAuthCode()) .put("code", dto.getAuthCode())
.set("grantType", "authorization_code"); .put("grantType", "authorization_code");
var tokenObj = dingRestClient.post() var tokenNode = dingRestClient.post()
.uri("/v1.0/oauth2/userAccessToken") .uri("/v1.0/oauth2/userAccessToken")
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(jsonObject.toString()) .body(objNode.toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (!tokenObj.containsKey("accessToken")) { if (ObjUtil.isNull(tokenNode) || !tokenNode.hasNonNull("accessToken")) {
log.error("钉钉回调接口获取accessToken失败:{}", tokenObj); log.error("钉钉回调接口获取accessToken失败:{}", tokenNode);
return tokenObj; return tokenNode;
} }
String accessToken = tokenObj.getStr("accessToken"); var accessToken = tokenNode.path("accessToken").asText();
var userInfoObj = dingRestClient.get() var userInfoNode = dingRestClient.get()
.uri("/v1.0/contact/users/me") .uri("/v1.0/contact/users/me")
.header("x-acs-dingtalk-access-token", accessToken) .header("x-acs-dingtalk-access-token", accessToken)
.retrieve() .retrieve()
.onStatus(httpStatusCode -> !httpStatusCode.is2xxSuccessful(), (request, response) -> { .onStatus(httpStatusCode -> !httpStatusCode.is2xxSuccessful(), (request, response) -> {
throw new RuntimeException("钉钉回调接口获取unionid失败:" + response.getBody()); throw new RuntimeException("钉钉回调接口获取unionid失败:" + response.getBody());
}) })
.body(JSONObject.class); .body(JsonNode.class);
String unionId = userInfoObj.getStr("unionId"); var unionId = userInfoNode.path("unionId").asText();
var useridObj = oDingRestClient.post() var useridNode = oDingRestClient.post()
.uri("/topapi/user/getbyunionid?access_token=" + getToken()) .uri("/topapi/user/getbyunionid?access_token=" + getToken())
.body(JSONUtil.ofObj().set("unionid", unionId).toString()) .body(JsonUtil.createObj().put("unionid", unionId).toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (!useridObj.containsKey("result")) { if (ObjUtil.isNull(useridNode) || !useridNode.hasNonNull("result")) {
log.error("钉钉回调接口获取userid失败:{}", useridObj); log.error("钉钉回调接口获取userid失败:{}", useridNode);
return useridObj; return useridNode;
} }
String userid = useridObj.getJSONObject("result").getStr("userid"); String userid = useridNode.path("result").path("userid").asText();
User user = userService.lambdaQuery() User user = userService.lambdaQuery()
.select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus, User::getEmployeeStatus) .select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus, User::getEmployeeStatus)
.eq(User::getUserid, userid).one(); .eq(User::getUserid, userid).one();
...@@ -295,29 +298,29 @@ public class DingMod { ...@@ -295,29 +298,29 @@ public class DingMod {
StpUtil.getTokenSession().set("curLoginUser", userVO); StpUtil.getTokenSession().set("curLoginUser", userVO);
return userVO; return userVO;
} else if (StrUtil.equals(target, "inside")) { } else if (StrUtil.equals(target, "inside")) {
var userInfoObj = oDingRestClient.post() var userInfoNode = oDingRestClient.post()
.uri(buildSignUrl()) .uri(buildSignUrl())
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(JSONUtil.ofObj().set("tmp_auth_code", dto.getCode()).toString()) .body(JsonUtil.createObj().put("tmp_auth_code", dto.getCode()).toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (!userInfoObj.containsKey("user_info")) { if (ObjUtil.isNull(userInfoNode) || !userInfoNode.hasNonNull("user_info")) {
log.error("钉钉回调接口获取unionid失败:{}", userInfoObj); log.error("钉钉回调接口获取unionid失败:{}", userInfoNode);
return userInfoObj; return userInfoNode;
} }
String unionId = userInfoObj.getJSONObject("user_info").getStr("unionid"); var unionId = userInfoNode.path("user_info").path("unionid").asText();
JSONObject useridObj = oDingRestClient.post() var useridNode = oDingRestClient.post()
.uri("/topapi/user/getbyunionid?access_token=" + getToken()) .uri("/topapi/user/getbyunionid?access_token=" + getToken())
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(JSONUtil.ofObj().set("unionid", unionId).toString()) .body(JsonUtil.createObj().put("unionid", unionId).toString())
.retrieve() .retrieve()
.body(JSONObject.class); .body(JsonNode.class);
if (!useridObj.containsKey("result")) { if (ObjUtil.isNull(useridNode) || !useridNode.hasNonNull("result")) {
log.error("钉钉回调接口获取userid失败:{}", useridObj); log.error("钉钉回调接口获取userid失败:{}", useridNode);
return useridObj; return useridNode;
} }
String userid = useridObj.getJSONObject("result").getStr("userid"); var userid = useridNode.path("result").path("userid").asText();
User user = userService.lambdaQuery().select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus).eq(User::getUserid, userid).one(); User user = userService.lambdaQuery().select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus).eq(User::getUserid, userid).one();
UserVO userVO = converter.convert(user, UserVO.class); UserVO userVO = converter.convert(user, UserVO.class);
...@@ -361,27 +364,27 @@ public class DingMod { ...@@ -361,27 +364,27 @@ public class DingMod {
* @return java.lang.Object * @return java.lang.Object
*/ */
public Object getPlatformToken(String authCode) { public Object getPlatformToken(String authCode) {
var accessTokenStr = oDingRestClient.get() var accessTokenNode = oDingRestClient.get()
.uri(StrUtil.format("/gettoken?appkey={}&appsecret={}", appKey, appSecret)) .uri("/gettoken?appkey={appKey}&appsecret={appSecret}", appKey, appSecret)
.retrieve() .retrieve()
.body(String.class); .body(JsonNode.class);
if (!StrUtil.contains(accessTokenStr, "access_token")) { if (ObjUtil.isNull(accessTokenNode) || !accessTokenNode.hasNonNull("access_token")) {
log.error("获取钉钉access_token失败:{}", accessTokenStr); log.error("获取钉钉access_token失败:{}", accessTokenNode);
return "获取钉钉access_token失败"; return "获取钉钉access_token失败";
} }
var accessToken = JSONUtil.parseObj(accessTokenStr).getStr("access_token"); var accessToken = accessTokenNode.path("access_token").asText();
var userInfoStr = oDingRestClient.post() var userInfoNode = oDingRestClient.post()
.uri("/topapi/v2/user/getuserinfo?access_token=" + accessToken) .uri("/topapi/v2/user/getuserinfo?access_token=" + accessToken)
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(JSONUtil.ofObj().set("code", authCode).toString()) .body(JsonUtil.createObj().put("code", authCode).toString())
.retrieve() .retrieve()
.body(String.class); .body(JsonNode.class);
if (!StrUtil.contains(userInfoStr, "\"errmsg\":\"ok\"")) { if (ObjUtil.isNull(userInfoNode) || !StrUtil.equalsIgnoreCase(userInfoNode.path("errmsg").asText(), "ok")) {
log.error("获取钉钉用户信息失败:{}", userInfoStr); log.error("获取钉钉用户信息失败:{}", userInfoNode);
return "获取钉钉用户信息失败"; return "获取钉钉用户信息失败";
} }
var userid = JSONUtil.parseObj(userInfoStr).getJSONObject("result").getStr("userid"); var userid = userInfoNode.path("result").path("userid").asText();
User user = userService.lambdaQuery() User user = userService.lambdaQuery()
.select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus, User::getEmployeeStatus) .select(User::getId, User::getUserid, User::getUsername, User::getPhone, User::getStatus, User::getEmployeeStatus)
.eq(User::getUserid, userid).one(); .eq(User::getUserid, userid).one();
......
package vion.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.text.StrUtil;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* JSON 工具类
*
* @author ShuQian_Liu
*/
@Slf4j
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 忽略 null 值
// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 解决 LocalDateTime 的序列化
objectMapper.registerModules(new JavaTimeModule());
}
/**
* 初始化 objectMapper 属性
* <p>
* 通过这样的方式,使用 Spring 创建的 ObjectMapper Bean
*
* @param objectMapper ObjectMapper 对象
*/
public static void init(ObjectMapper objectMapper) {
JsonUtil.objectMapper = objectMapper;
}
public static ObjectNode createObj() {
return objectMapper.createObjectNode();
}
public static ArrayNode createArr() {
return objectMapper.createArrayNode();
}
@SneakyThrows
public static String toJsonString(Object object) {
return objectMapper.writeValueAsString(object);
}
@SneakyThrows
public static byte[] toJsonByte(Object object) {
return objectMapper.writeValueAsBytes(object);
}
@SneakyThrows
public static String toJsonPrettyString(Object object) {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
}
public static <T> T parseObject(String text, Class<T> clazz) {
if (StrUtil.isEmpty(text)) {
return null;
}
try {
return objectMapper.readValue(text, clazz);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, String path, Class<T> clazz) {
if (StrUtil.isEmpty(text)) {
return null;
}
try {
JsonNode treeNode = objectMapper.readTree(text);
JsonNode pathNode = treeNode.path(path);
return objectMapper.readValue(pathNode.toString(), clazz);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, Type type) {
if (StrUtil.isEmpty(text)) {
return null;
}
try {
return objectMapper.readValue(text, objectMapper.getTypeFactory().constructType(type));
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
throw new RuntimeException(e);
}
}
/**
* 将字符串解析成指定类型的对象
* 使用 {@link #parseObject(String, Class)} 时,在@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) 的场景下,
* 如果 text 没有 class 属性,则会报错。此时,使用这个方法,可以解决。
*
* @param text 字符串
* @param clazz 类型
* @return 对象
*/
public static <T> T parseObject2(String text, Class<T> clazz) {
if (StrUtil.isEmpty(text)) {
return null;
}
try {
return objectMapper.readValue(text, clazz);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
if (ArrayUtil.isEmpty(bytes)) {
return null;
}
try {
return objectMapper.readValue(bytes, clazz);
} catch (IOException e) {
log.error("json parse err,json:{}", bytes, e);
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
try {
return objectMapper.readValue(text, typeReference);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
throw new RuntimeException(e);
}
}
/**
* 解析 JSON 字符串成指定类型的对象,如果解析失败,则返回 null
*
* @param text 字符串
* @param typeReference 类型引用
* @return 指定类型的对象
*/
public static <T> T parseObjectQuietly(String text, TypeReference<T> typeReference) {
try {
return objectMapper.readValue(text, typeReference);
} catch (IOException e) {
return null;
}
}
public static <T> List<T> parseArray(String text, Class<T> clazz) {
if (StrUtil.isEmpty(text)) {
return new ArrayList<>();
}
try {
return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
throw new RuntimeException(e);
}
}
public static <T> List<T> parseArray(String text, String path, Class<T> clazz) {
if (StrUtil.isEmpty(text)) {
return null;
}
try {
JsonNode treeNode = objectMapper.readTree(text);
JsonNode pathNode = treeNode.path(path);
return objectMapper.readValue(pathNode.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
throw new RuntimeException(e);
}
}
public static JsonNode parseTree(String text) {
try {
return objectMapper.readTree(text);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
throw new RuntimeException(e);
}
}
public static JsonNode parseTree(byte[] text) {
try {
return objectMapper.readTree(text);
} catch (IOException e) {
log.error("json parse err,json:{}", text, e);
throw new RuntimeException(e);
}
}
public static boolean isJson(String jsonString) {
try {
objectMapper.readTree(jsonString);
return true;
} catch (Exception e) {
return false;
}
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!