ContractRunner.java
24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package vion.cron;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.lang.Opt;
import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
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.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClient;
import vion.constant.RedisKeyEnum;
import vion.model.Dictionary;
import vion.model.*;
import vion.service.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 从crm系统定时同步合同信息
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class ContractRunner {
private final IContractService contractService;
private final IDictionaryService dictionaryService;
private final IContractPaymentService contractPaymentService;
private final IRContractUserService contractUserService;
private final IRContractStoreService contractStoreService;
private final IStoreService storeService;
private final IPaymentService paymentService;
private final IRContractProductService contractProductService;
private final RedissonClient redissonClient;
private final RestClient bongRestClient;
@Value("${xbongbong.token}")
private String token;
@Value("${xbongbong.corpid}")
private String corpId;
@Scheduled(cron = "0 0 8-20 * * *")
@Transactional(rollbackFor = Exception.class)
public void contractSync() {
Long modifyTime = Opt.ofNullable((Long) redissonClient.getBucket(RedisKeyEnum.CONTRACT_SYNC_NEW_TIME.getVal()).get()).orElse(0L);
// 只同步申请日期(原CRM中的签订日期)2024-05-07号(含)之后的合同
var json = JSONUtil.ofObj()
.set("sortMap", JSONUtil.ofObj()
.set("field", "updateTime")
.set("sort", "desc"))
.set("conditions", JSONUtil.ofArray()
.put(JSONUtil.ofObj()
.set("attr", "date_3")
.set("symbol", "greaterequal")
.set("value", new String[]{"1715356800"}))
.put(JSONUtil.ofObj()
.set("attr", "updateTime")
.set("symbol", "greatethan")
.set("value", new String[]{String.valueOf(modifyTime / 1000)}))
)
.set("corpid", corpId)
.set("formId", 8429903)
.set("pageSize", 100);
var jobO = bongRestClient.post()
.uri("/pro/v2/api/contract/list")
.contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json.toString() + token))
.body(json.toString())
.retrieve()
.body(JSONObject.class);
if (jobO.getInt("code") != 1) {
log.error("获取合同列表失败,错误原因:{}", jobO);
return;
}
Integer cnt = jobO.getJSONObject("result").getInt("totalCount");
Integer page = jobO.getJSONObject("result").getInt("totalPage");
if (NumberUtil.equals(cnt, 0)) {
log.info("没有需要插入或更新的合同");
return;
}
var jsonArray = jobO.getJSONObject("result").getJSONArray("list");
// 合同记录唯一 dataId
var dataIdSet = jsonArray.stream().map(v -> JSONUtil.parseObj(v).getInt("dataId")).collect(Collectors.toSet());
for (int i = 2; i <= page; i++) {
var jsonR = JSONUtil.ofObj()
.set("sortMap", JSONUtil.ofObj()
.set("field", "updateTime")
.set("sort", "desc"))
.set("conditions", JSONUtil.ofArray()
.put(JSONUtil.ofObj()
.set("attr", "date_3")
.set("symbol", "greaterequal")
.set("value", new String[]{"1715356800"}))
.put(JSONUtil.ofObj()
.set("attr", "updateTime")
.set("fieldType", "10015")
.set("symbol", "greatethan")
.set("value", new String[]{String.valueOf(modifyTime)}))
)
.set("corpid", corpId)
.set("formId", 8429903)
.set("page", i)
.set("pageSize", 100);
var jobR = bongRestClient.post()
.uri("/pro/v2/api/contract/list")
.contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(jsonR.toString() + token))
.body(jsonR.toString())
.retrieve()
.body(JSONObject.class);
var jsonArrR = jobR.getJSONObject("result").getJSONArray("list");
var dataIdSetR = jsonArrR.stream().map(v -> JSONUtil.parseObj(v).getInt("dataId")).collect(Collectors.toSet());
dataIdSet.addAll(dataIdSetR);
}
Map<String, Integer> contractTypeMap = dictionaryService.lambdaQuery().eq(Dictionary::getType, "contract_type").list().stream().collect(Collectors.toMap(Dictionary::getValue, Dictionary::getKey));
List<Contract> insOrUpdContractList = new ArrayList<>();
List<RContractProduct> productList = new ArrayList<>();
var crmProList = getProductList();
if (CollUtil.isEmpty(crmProList)) {
log.error("获取CRM产品信息为空");
return;
}
dataIdSet.forEach(dataId -> {
var json1 = JSONUtil.ofObj()
.set("corpid", corpId)
.set("dataId", dataId);
var jobj1 = bongRestClient.post()
.uri("/pro/v2/api/contract/detail")
.contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json1.toString() + token))
.body(json1.toString())
.retrieve()
.body(JSONObject.class);
if (jobj1.getInt("code") != 1) {
log.error("获取合同详情失败,错误原因:{}", jobj1);
return;
}
var result = jobj1.getJSONObject("result");
var jsonObj1 = result.getJSONObject("data");
Contract contract = new Contract();
contract.setName(jsonObj1.getStr("text_14"));
contract.setContractNo(jsonObj1.getStr("serialNo"));
contract.setType(contractTypeMap.getOrDefault(jsonObj1.getJSONObject("text_17").getStr("text"), 0));
contract.setSignDate(DateUtil.date(jsonObj1.getLong("date_1") * 1000));
contract.setMaintainSdate(Opt.ofNullable(jsonObj1.getLong("date_4")).map(sec -> DateUtil.date(sec * 1000)).orElse(null));
contract.setMaintainEdate(Opt.ofNullable(jsonObj1.getLong("date_5")).map(sec -> DateUtil.date(sec * 1000)).orElse(null));
String warrantyPeriod = Opt.ofNullable(jsonObj1.getJSONObject("text_23")).map(wp -> wp.getStr("text")).orElse("");
// 23 质保 没有维保开始时间和结束时间 25 维保
if (StrUtil.isNotBlank(warrantyPeriod) && warrantyPeriod.contains("个月")) {
String substring = warrantyPeriod.substring(0, (warrantyPeriod.length() - 2));
contract.setWarrantyPeriod(Integer.parseInt(substring));
}
contract.setStatus(1);
contract.setTotalAmount(jsonObj1.getBigDecimal("num_1"));
contract.setPaidAmount(BigDecimal.ZERO);
contract.setReceivableAmount(BigDecimal.ZERO);
contract.setOutstandingAmount(jsonObj1.getBigDecimal("num_1"));
var paymentForm = jsonObj1.getJSONArray("subForm_1");
if (!paymentForm.isEmpty()) {
paymentForm.forEach(pf -> {
var pfObj = JSONUtil.parseObj(pf);
var ratio = NumberUtil.div(BigDecimal.valueOf(Double.parseDouble(pfObj.getStr("text_1"))), 100);
var date = DateUtil.date(pfObj.getLong("date_1") * 1000);
var stage = pfObj.getJSONObject("text_2").getStr("text");
if (StrUtil.equals(stage, "预付款")) {
contract.setSignRatio(ratio);
contract.setSignDate1(date);
} else if (StrUtil.equals(stage, "到货款")) {
contract.setArriveRatio(ratio);
contract.setArriveDate(date);
} else if (StrUtil.equals(stage, "系统验收款")) {
contract.setSystemCheckRatio(ratio);
contract.setSystemCheckDate(date);
} else if (StrUtil.equals(stage, "项目终验款")) {
contract.setProjectCheckRatio(ratio);
contract.setProjectCheckDate(date);
} else if (StrUtil.equals(stage, "质保款")) {
contract.setWarrantyRatio(ratio);
contract.setWarrantyDate(date);
} else if (StrUtil.equals(stage, "维保第一笔款")) {
contract.setMaintainRatio1(ratio);
contract.setMaintainDate1(date);
} else if (StrUtil.equals(stage, "维保第二笔款")) {
contract.setMaintainRatio2(ratio);
contract.setMaintainDate2(date);
} else if (StrUtil.equals(stage, "维保第三笔款")) {
contract.setMaintainRatio3(ratio);
contract.setMaintainDate3(date);
} else if (StrUtil.equals(stage, "维保进度款")) {
contract.setMaintainProgressRatio(ratio);
contract.setMaintainProgressDate(date);
} else if (StrUtil.equals(stage, "维保验收款")) {
contract.setMaintainAcceptanceRatio(ratio);
contract.setMaintainAcceptanceDate(date);
}
});
}
contract.setSubject("北京文安智能技术股份有限公司");
contract.setCustomerName(jsonObj1.getJSONObject("text_2").getStr("name"));
contract.setSaleName(jsonObj1.getJSONObject("text_8").getStr("name"));
contract.setCreateUser(-1L);
contract.setModifyUser(-1L);
contract.setEntryTime(DateUtil.date(result.getLong("addTime") * 1000));
contract.setOriginalModTime(DateUtil.date(result.getLong("updateTime") * 1000));
insOrUpdContractList.add(contract);
var productArr = jsonObj1.getJSONArray("array_4");
if (!productArr.isEmpty()) {
productArr.forEach(pro -> {
var product = JSONUtil.parseObj(pro);
var crmProJson = crmProList.stream().filter(p -> p.getInt("dataId").equals(product.getInt("text_1"))).toList().getFirst();
var crmPro = crmProJson.getJSONObject("data");
var contractProduct = new RContractProduct();
contractProduct.setContractNo(contract.getContractNo());
contractProduct.setProductName(crmPro.getStr("text_1"));
contractProduct.setProductCode(crmPro.getStr("serialNo"));
contractProduct.setProductModel(crmPro.getStr("text_4"));
contractProduct.setNum(product.getInt("num_3"));
contractProduct.setTaxPrice(product.getBigDecimal("num_1"));
contractProduct.setTaxRate(BigDecimal.valueOf(Integer.parseInt(crmPro.getStr("text_12").replace("%", "")) / 100));
// contractProduct.setNoTaxPrice(product.getBigDecimal("num_6"));
contractProduct.setDiscountRate(NumberUtil.div(product.getBigDecimal("num_4"), 100));
contractProduct.setActualPrice(product.getBigDecimal("num_6"));
// contractProduct.setErase(product);
contractProduct.setTotalPrice(product.getBigDecimal("num_5"));
productList.add(contractProduct);
});
}
});
insOrUpdContractList.sort(Comparator.comparing(Contract::getOriginalModTime).reversed());
var no2ProductMap = productList.stream().collect(Collectors.groupingBy(RContractProduct::getContractNo));
// 已存在的合同列表
Map<String, Contract> no2ContactMap = contractService.list().stream().collect(Collectors.toMap(Contract::getContractNo, Function.identity()));
List<Long> updContractIdList = new ArrayList<>();
insOrUpdContractList.forEach(v -> {
if (no2ContactMap.containsKey(v.getContractNo())) {
Long contractId = no2ContactMap.get(v.getContractNo()).getId();
v.setId(contractId);
// 已有合同不更新状态
v.setStatus(null);
updContractIdList.add(contractId);
// 移除已存在合同的关联产品信息,防止重复插入
no2ProductMap.remove(v.getContractNo());
}
});
contractProductService.saveBatch(no2ProductMap.values().stream().flatMap(Collection::stream).toList());
// 合同更新,同步调用一下更新项目的维保状态
Opt.ofEmptyAble(updContractIdList)
.map(contractIdList -> contractStoreService.lambdaQuery().in(RContractStore::getContractId, contractIdList).list())
.map(csList -> csList.stream().map(RContractStore::getStoreId).collect(Collectors.toList()))
.filter(CollUtil::isNotEmpty)
.ifPresent(storeService::calMaintainStatus);
contractService.saveOrUpdateBatch(insOrUpdContractList, 500);
insOrUpdContractList.forEach(v -> {
// 合同状态不为空,代表此条记录为新增,需要同步销售人信息到 r_contract_user 表中
if (ObjUtil.isNotNull(v.getStatus())) {
RContractUser contractUser = new RContractUser();
String userId = Opt.ofNullable(redissonClient.getBucket(RedisKeyEnum.DING_PREFIX.getVal() + RedisKeyEnum.USER_NAME.getVal() + v.getSaleName()).get())
.map(u -> (User) u)
.map(User::getUserid)
.orElse(null);
contractUser.setUserId(userId);
contractUser.setUsername(v.getSaleName());
contractUser.setEnterDate(v.getSignDate());
contractUser.setContractId(v.getId());
contractUser.setContractNo(v.getContractNo());
contractUserService.save(contractUser);
}
});
List<ContractPayment> existContractPaymentList = contractPaymentService.list();
Map<Long, Map<Integer, Long>> contractId2PaymentMap = existContractPaymentList.stream().collect(Collectors.groupingBy(ContractPayment::getContractId, Collectors.toMap(ContractPayment::getPaymentType, ContractPayment::getId)));
// 合同付款比例处理
contractPaymentHandler(insOrUpdContractList, contractId2PaymentMap);
List<Payment> paymentList = paymentService.list();
Map<String, BigDecimal> no2PaymentMap = paymentList.stream().collect(Collectors.groupingBy(Payment::getContractNo, Collectors.reducing(BigDecimal.ZERO, Payment::getPaymentAmount, BigDecimal::add)));
insOrUpdContractList.forEach(c -> {
String contractNo = c.getContractNo();
Contract exist = contractService.lambdaQuery().eq(Contract::getContractNo, contractNo).one();
Contract updDto = new Contract();
updDto.setId(exist.getId());
updDto.setPaidAmount(no2PaymentMap.getOrDefault(contractNo, BigDecimal.ZERO));
contractPaymentService.calMoney(exist, updDto);
contractService.updateById(updDto);
});
redissonClient.getBucket(RedisKeyEnum.CONTRACT_SYNC_NEW_TIME.getVal()).set(insOrUpdContractList.getFirst().getOriginalModTime().getTime());
log.info("【结束】从crm系统同步合同信息");
}
private void contractPaymentHandler(List<Contract> insOrUpdContractList, Map<Long, Map<Integer, Long>> contractId2PaymentMap) {
List<ContractPayment> contractPaymentList = new ArrayList<>();
for (Contract contract : insOrUpdContractList) {
// 签订
ContractPayment contractSignPayment = new ContractPayment();
contractSignPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(1));
contractSignPayment.setContractId(contract.getId());
contractSignPayment.setPaymentType(1);
contractSignPayment.setPaymentRatio(Opt.ofNullable(contract.getSignRatio()).orElse(BigDecimal.ZERO));
contractSignPayment.setPaymentDate(contract.getSignDate1());
contractSignPayment.setNodeDate(contract.getSignDate());
contractPaymentList.add(contractSignPayment);
// 到货
ContractPayment contractArrivePayment = new ContractPayment();
contractArrivePayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(2));
contractArrivePayment.setContractId(contract.getId());
contractArrivePayment.setPaymentType(2);
contractArrivePayment.setPaymentRatio(Opt.ofNullable(contract.getArriveRatio()).orElse(BigDecimal.ZERO));
contractArrivePayment.setPaymentDate(contract.getArriveDate());
contractPaymentList.add(contractArrivePayment);
// 系统验收
ContractPayment contractSystemCheckPayment = new ContractPayment();
contractSystemCheckPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(3));
contractSystemCheckPayment.setContractId(contract.getId());
contractSystemCheckPayment.setPaymentType(3);
contractSystemCheckPayment.setPaymentRatio(Opt.ofNullable(contract.getSystemCheckRatio()).orElse(BigDecimal.ZERO));
contractSystemCheckPayment.setPaymentDate(contract.getSystemCheckDate());
contractPaymentList.add(contractSystemCheckPayment);
// 项目验收
ContractPayment contractProjectCheckPayment = new ContractPayment();
contractProjectCheckPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(4));
contractProjectCheckPayment.setContractId(contract.getId());
contractProjectCheckPayment.setPaymentType(4);
contractProjectCheckPayment.setPaymentRatio(Opt.ofNullable(contract.getProjectCheckRatio()).orElse(BigDecimal.ZERO));
contractProjectCheckPayment.setPaymentDate(contract.getProjectCheckDate());
contractPaymentList.add(contractProjectCheckPayment);
// 质保
ContractPayment contractWarrantyPayment = new ContractPayment();
contractWarrantyPayment.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(5));
contractWarrantyPayment.setContractId(contract.getId());
contractWarrantyPayment.setPaymentType(5);
contractWarrantyPayment.setPaymentRatio(Opt.ofNullable(contract.getWarrantyRatio()).orElse(BigDecimal.ZERO));
contractWarrantyPayment.setPaymentDate(contract.getWarrantyDate());
contractPaymentList.add(contractWarrantyPayment);
// 第一笔维保款
ContractPayment contractMaintainPayment1 = new ContractPayment();
contractMaintainPayment1.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(6));
contractMaintainPayment1.setContractId(contract.getId());
contractMaintainPayment1.setPaymentType(6);
contractMaintainPayment1.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio1()).orElse(BigDecimal.ZERO));
contractMaintainPayment1.setPaymentDate(contract.getMaintainDate1());
contractPaymentList.add(contractMaintainPayment1);
// 第二笔维保款
ContractPayment contractMaintainPayment2 = new ContractPayment();
contractMaintainPayment2.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(7));
contractMaintainPayment2.setContractId(contract.getId());
contractMaintainPayment2.setPaymentType(7);
contractMaintainPayment2.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio2()).orElse(BigDecimal.ZERO));
contractMaintainPayment2.setPaymentDate(contract.getMaintainDate2());
contractPaymentList.add(contractMaintainPayment2);
// 第三笔维保款
ContractPayment contractMaintainPayment3 = new ContractPayment();
contractMaintainPayment3.setId(contractId2PaymentMap.getOrDefault(contract.getId(), new HashMap<>()).get(8));
contractMaintainPayment3.setContractId(contract.getId());
contractMaintainPayment3.setPaymentType(8);
contractMaintainPayment3.setPaymentRatio(Opt.ofNullable(contract.getMaintainRatio3()).orElse(BigDecimal.ZERO));
contractMaintainPayment3.setPaymentDate(contract.getMaintainDate3());
contractPaymentList.add(contractMaintainPayment3);
}
contractPaymentService.saveOrUpdateBatch(contractPaymentList);
}
/**
* 获取CRM产品列表,若循环调用接口出现一次失败,则直接返回空列表
*
* @return java.util.List<org.dromara.hutool.json.JSONObject>
*/
public List<JSONObject> getProductList() {
List<JSONObject> resList = new ArrayList<>();
var json = JSONUtil.ofObj()
.set("corpid", corpId)
.set("page", 1)
.set("pageSize", 100);
var jobj = bongRestClient.post()
.uri("/pro/v2/api/product/list")
.contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json.toString() + token))
.body(json.toString())
.retrieve()
.body(JSONObject.class);
if (jobj.getInt("code") != 1) {
log.error("获取CRM产品列表失败:{}", jobj);
return List.of();
}
var result = jobj.getJSONObject("result");
var totalPage = result.getInt("totalPage");
result.getJSONArray("list").stream().map(JSONUtil::parseObj).forEach(resList::add);
for (int i = 2; i <= totalPage; i++) {
var json1 = JSONUtil.ofObj()
.set("corpid", corpId)
.set("page", i)
.set("pageSize", 100);
var jobj1 = bongRestClient.post()
.uri("/pro/v2/api/product/list")
.contentType(MediaType.APPLICATION_JSON)
.header("sign", SecureUtil.sha256(json1.toString() + token))
.body(json1.toString())
.retrieve()
.body(JSONObject.class);
if (jobj1.getInt("code") != 1) {
log.error("获取CRM产品列表失败:{}", jobj1);
return List.of();
}
var result1 = jobj1.getJSONObject("result");
result1.getJSONArray("list").stream().map(JSONUtil::parseObj).forEach(resList::add);
}
return resList;
}
@Scheduled(cron = "0 0 1 * * ?")
public void calMaintainStatus() {
log.info("【开始】计算门店维保状态");
storeService.calMaintainStatus(ListUtil.empty());
log.info("【结束】计算门店维保状态");
}
@Scheduled(cron = "0 10 8-20 ? * *")
public void syncContractFile() {
contractService.syncContractFile(null);
}
}