SyncDataService.java
44.5 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
package cn.com.glsx.entmicro.service;
import cn.com.glsx.entmicro.config.RedisLock;
import cn.com.glsx.entmicro.constants.Constants;
import cn.com.glsx.entmicro.dto.CustomerKafkaDTO;
import cn.com.glsx.entmicro.entity.*;
import cn.com.glsx.entmicro.kafka.producer.ProducerComponent;
import cn.com.glsx.entmicro.manager.QyMediaUplaodComponent;
import cn.com.glsx.entmicro.manager.WeekReportRemindStaffComponent;
import cn.com.glsx.entmicro.mapper.*;
import cn.com.glsx.entmicro.model.MerchantRopResponse;
import cn.com.glsx.entmicro.model.request.CustomerFollowerStaffRequest;
import cn.com.glsx.entmicro.model.request.CustomerInfoRequest;
import cn.com.glsx.entmicro.model.request.CustomerStandardRequest;
import cn.com.glsx.entmicro.model.response.EntmicroDepartmentResponse;
import cn.com.glsx.entmicro.model.response.EntmicroStaffResponse;
import cn.com.glsx.entmicro.service.common.MessageService;
import cn.com.glsx.entmicro.service.drainage.DracImService;
import cn.com.glsx.entmicro.util.RemarkUtils;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.framework.core.util.RpcAssert;
import cn.com.glsx.scrm.wechat.dto.WechatAccessBatchUserInfoResponseDTO;
import cn.com.glsx.scrm.wechat.dto.WechatAccessUserInfoResponseDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.external.request.BatchGetWorkWechatExternalContactRequestDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.external.request.GetWorkWechatExternalContactRequestDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.external.response.*;
import cn.com.glsx.scrm.wechat.dto.workwechat.user.request.WorkWechatConvertToOpenIdRequestDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.user.response.GetWechatAccessUserOpenIdListResponseDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.user.response.WechatAccessUserOpenIdResponseDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.user.response.WorkWechatConvertToOpenIdResponseDTO;
import cn.com.glsx.scrm.wechat.remote.WechatAccessRemote;
import cn.com.glsx.scrm.wechat.remote.WechatUserInfoRemote;
import cn.com.glsx.scrm.wechat.remote.WorkWechatExternalContactRemote;
import cn.com.glsx.scrm.wechat.remote.WorkWechatUserRemote;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Component
public class SyncDataService {
@Autowired
private EntmicroAuthorizeMapper entmicroAuthorizeMapper;
@Autowired
private CustomerService customerService;
@Autowired
private EntmicroStaffService entmicroStaffService;
private final static String LOCK_ID_SYNC_CUST = "sync_customer";
@Autowired
private CustomerMapper customerMapper;
@Autowired
private WorkWechatExternalContactRemote contactRemote;
@Autowired
private CustomerReportService customerReportService;
@Autowired
private CustomerStatisticsService customerStatisticsService;
@Autowired
private CustomerReportMapper customerReportMapper;
@Autowired
private WeekReportRemindStaffComponent weekReportRemindStaffComponent;
@Autowired
private CustomerBaseService customerBaseService;
@Value("${custsync.time}")
private Integer custsyncTime;
@Autowired
private RedisLock redisLock;
@Resource
private QyMediaUplaodComponent qyMediaUplaodComponent;
@Resource
private Environment environment;
@Autowired
private MessageService messageService;
@Resource
private MerchantService merchantService;
@Resource
private DracImService dracImService;
@Autowired
private EntmicroCustomerFollowMapper entmicroCustomerFollowMapper;
@Resource
private ProducerComponent producerComponent;
@Resource
private WechatUserInfoRemote wechatUserInfoRemote;
@Resource
private WorkWechatUserRemote workWechatUserRemote;
@Resource
private WechatAccessRemote wechatAccessRemote;
@Value("${wechat_official_account_app_id}")
private String officialAccountAppId;
@Value("${wechat_official_account_app_secret}")
private String officialAccountAppSecret;
@Value("${scrm_subscribe_job_enabled}")
private Boolean subscribeJobEnabled;
// 取关公众号状态
private final static Integer UN_SUBSCRIBE = 0;
// 关注公众号状态
private final static Integer IS_SUBSCRIBE = 1;
private static final String PUSH_TITLE = "查看详情\t\t\t\t\t\t\t\t\t\t\t>";
@Autowired
private ScrmCompareLogMapper scrmCompareLogMapper;
public void setMerchantListener(MerchantListener listener) {
List<EntmicroAuthorize> entmicroAuthorizes = entmicroAuthorizeMapper.selectAll();
if (CollectionUtils.isEmpty(entmicroAuthorizes)) {
return;
}
log.info("授权的商户{}", entmicroAuthorizes);
entmicroAuthorizes.forEach(index -> {
if (index.getMerchantId() != null) {
listener.excute(Integer.valueOf(index.getMerchantId()));
}
});
}
public Map<String, Customer> getCustomersByUserId(List<String> userid) {
return customerMapper.getCustomersByUserId(userid);
}
/**
* 同步企微客户数据(主动)
*/
public void syncEntmicroCustomer(Integer merchantId, List<String> useridList, Boolean syncUpdateCustomer) {
if (null == merchantId) {
return;
}
// 分布式锁添加
boolean lock = redisLock.getLock(LOCK_ID_SYNC_CUST + merchantId, custsyncTime);
if (lock) {
try {
//调用接口获取企微客户
// 获取员工id列表
Integer supMerchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
List<WorkWechatExternalContactListDTO> allCustomers = batchGetCustomerByStaff(useridList, supMerchantNo);
if (!CollectionUtils.isEmpty(allCustomers)) {
log.info("门店{}企微客户总数{}", merchantId, allCustomers.size());
for (WorkWechatExternalContactListDTO allCustomer : allCustomers) {
WorkWechatExternalContactFollowUserDTO follow = allCustomer.getFollowInfo();
WorkWechatExternalContactDTO cust = allCustomer.getExternalContact();
log.info("企微同步获取客户===cust:{},follow:{}", cust, follow);
}
}
// 判断客户新增删除修改
List<CustomerStandardRequest> customerCompareModels = entrepConvert(allCustomers, merchantId);
List<CustomerStandardRequest> customerStandardRequests = findAllCustomerByMerchantId(merchantId, useridList);
List<CustomerStandardRequest> addlist = customerCompareModels.stream().filter(index -> !customerStandardRequests.contains(index)).collect(Collectors.toList());
List<CustomerStandardRequest> deletelist = customerStandardRequests.stream().filter(index -> !customerCompareModels.contains(index)).collect(Collectors.toList());
List<CustomerStandardRequest> updatelist = customerCompareModels.stream().filter(index -> customerStandardRequests.contains(index)).collect(Collectors.toList());
if (CollectionUtils.isEmpty(allCustomers)) {
return;
}
if (!CollectionUtils.isEmpty(addlist)) {
log.info("门店{}新增客户总数{}", merchantId, addlist.size());
addlist.forEach(index -> {
try {
customerService.customerAdd(index, false, merchantId);
} catch (Exception e) {
log.info("新增客户异常{}", e.getMessage());
e.printStackTrace();
}
});
}
if (!CollectionUtils.isEmpty(updatelist) && !syncUpdateCustomer) {
updatelist.forEach(index -> {
customerService.customerEdit(index, false, merchantId);
});
}
if (!CollectionUtils.isEmpty(deletelist)) {
deletelist.forEach(index -> {
customerService.customerFollowDelete(index.getUserId(), index.getExternalUserId(), false, merchantId, false);
});
}
} catch (Exception e) {
log.info("更新客户信息异常{}", e);
} finally {
redisLock.releaseLock(LOCK_ID_SYNC_CUST + merchantId);
}
}
}
public List<CustomerStandardRequest> findAllCustomerByMerchantId(int merchantId, List<String> userIds) {
return customerMapper.findAllCustomerByMerchantId(merchantId, userIds);
}
public List<CustomerStandardRequest> entrepConvert(List<WorkWechatExternalContactListDTO> useridList, Integer merchantId) {
return useridList.stream().map(index -> {
WorkWechatExternalContactResponseDTO workWechatExternalContactResponseDTO = new WorkWechatExternalContactResponseDTO();
List<WorkWechatExternalContactFollowUserDTO> workWechatExternalContactFollowUserDTOS = new ArrayList<>();
WorkWechatExternalContactDTO externalContact = index.getExternalContact();
WorkWechatExternalContactFollowUserDTO followInfo = index.getFollowInfo();
workWechatExternalContactResponseDTO.setExternalContact(externalContact);
workWechatExternalContactFollowUserDTOS.add(followInfo);
workWechatExternalContactResponseDTO.setFollowUser(workWechatExternalContactFollowUserDTOS);
return customerService.buildCustomerParam(workWechatExternalContactResponseDTO, merchantId);
}).collect(Collectors.toList());
}
/**
* 批量获取企微端客户数据
*
* @param batchUseridList
* @param supMerchantNo
* @param allCustomers
* @param cursor
*/
public void batchGetCustomer(List batchUseridList, Integer supMerchantNo, List<WorkWechatExternalContactListDTO> allCustomers, String cursor) {
BatchGetWorkWechatExternalContactRequestDTO batchContactRequest = new BatchGetWorkWechatExternalContactRequestDTO();
batchContactRequest.setUseridList(batchUseridList);
batchContactRequest.setMerchantId(supMerchantNo);
if (!"".equals(cursor)) {
batchContactRequest.setCursor(cursor);
}
batchContactRequest.setLimit(100);
RpcResponse<WorkWechatExternalContactBatchListResponseDTO> response = contactRemote.batchGetExternalContact(batchContactRequest);
log.info("批量调取客户详情:{}", JSONArray.toJSONString(response));
if (!response.isSuccess()) {
log.info("调用客戶详情失败入參{}", batchContactRequest);
throw new RpcServiceException(response.getException().getErrId(), response.getMessage());
}
WorkWechatExternalContactBatchListResponseDTO batchResult = response.getResult();
List<WorkWechatExternalContactListDTO> externalContactList = batchResult.getExternalContactList();
String nextCursor = batchResult.getNextCursor();
allCustomers.addAll(externalContactList);
if (!StringUtils.isEmpty(nextCursor)) {
batchGetCustomer(batchUseridList, supMerchantNo, allCustomers, nextCursor);
} else {
return;
}
}
public void pushMonthlyReport() {
Date today = new Date();
Calendar monthCalendar = Calendar.getInstance();
monthCalendar.setTime(today);
monthCalendar.add(Calendar.MONTH, -1);
Date monthDate = monthCalendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("MM");
String month = format.format(monthDate);
monthCalendar.set(Calendar.DAY_OF_MONTH, monthCalendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date startDate = monthCalendar.getTime();
monthCalendar.set(Calendar.DAY_OF_MONTH, monthCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date endDate = monthCalendar.getTime();
String monthReportName = customerReportService.buildReportName(startDate, endDate, false);
List<Integer> merchantList = customerReportMapper.selectMerchantIdListByReportName(monthReportName);
int currentMonth = monthCalendar.get(Calendar.MONTH) + 1;
String picurl = environment.getProperty("report.month.picurl." + currentMonth);
merchantList.stream().forEach(merchantId -> {
Integer merchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
String entmicroId = entmicroAuthorizeMapper.findEntmicroId(merchantNo);
String url = environment.getProperty("report.month.url") + entmicroId;
String smsUrl = environment.getProperty("report.month.url.sms") + entmicroId;
boolean success = weekReportRemindStaffComponent.remindStaffForWeekReport(merchantId, PUSH_TITLE, null, url, picurl);
log.info(monthReportName + merchantId + "商户的月报推送" + (success ? "成功" : "失败,请确认") + ",entmicroId:{}" + ",URL:{}", entmicroId, url);
try {
url = dracImService.buildUrlMini(smsUrl);
} catch (Exception e) {
log.info("该商户短信短链转换失败:{}", smsUrl);
e.printStackTrace();
}
String content = "【嘀加企微管家】您旗下的门店运营月报- " + month + " 月,请查收!月报地址: " + url + "; 退订回T";
sendReportSMS(merchantId, content);
});
}
public void pushWeeklyReport() {
Date monday = getMonday();
Date endDate = DateUtils.addDays(monday, -1);
Date startDate = DateUtils.addDays(endDate, -6);
String weekName = customerReportService.buildReportName(startDate, endDate, false);
List<Integer> merchantList = customerReportMapper.selectMerchantIdListByReportName(weekName);
String picurl = environment.getProperty("report.week.picurl");
merchantList.stream().forEach(merchantId -> {
Integer merchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
String entmicroId = entmicroAuthorizeMapper.findEntmicroId(merchantNo);
String url = environment.getProperty("report.week.url") + entmicroId;
String smsUrl = environment.getProperty("report.week.url.sms") + entmicroId;
boolean success = weekReportRemindStaffComponent.remindStaffForWeekReport(merchantId, PUSH_TITLE, null, url, picurl);
log.info(weekName + merchantId + "商户的周报推送" + (success ? "成功" : "失败,请确认") + ",entmicroId:{}" + ",URL:{}", entmicroId, url);
try {
url = dracImService.buildUrlMini(smsUrl);
} catch (Exception e) {
log.info("该商户短信短链转换失败:{}", merchantId);
e.printStackTrace();
}
String content = "【嘀加企微管家】您旗下的门店运营周报,请查收!周报地址:" + url + "; 拒收请回复R";
sendReportSMS(merchantId, content);
});
}
public boolean sendReportSMS(Integer merchantId, String content) {
MerchantRopResponse merchantByMerchantNo = merchantService.findMerchantByMerchantNo(merchantId);
if (ObjectUtils.isEmpty(merchantByMerchantNo) || Constants.STORE_MODEL != merchantByMerchantNo.getMerchantModel()) {
log.info("短信发送失败,该商户非单店模式:{}", merchantId);
return false;
}
List<MerchantRopResponse> superiorList = merchantService.findSuperiorList(merchantId);
List<MerchantRopResponse> list = JSONArray.parseArray(JSON.toJSONString(superiorList), MerchantRopResponse.class);
if (CollectionUtils.isEmpty(list)) {
log.info("短信发送失败,该商户无上级商户:{}", merchantId);
return false;
}
String messageSource = environment.getProperty("message.source.drac");
Set<String> hasBeenSent = new HashSet<>();
list.stream().filter(index -> !merchantId.equals(index.getMerchantNo())).forEach(item -> {
String phone = item.getMerchantLegalPersonPhone();
if (!StringUtils.isEmpty(phone) && !hasBeenSent.contains(phone)) {
log.info(item + "商户的短信开始发送,短信内容:{}", content);
messageService.sendMessage(phone, messageSource, "1", content);
hasBeenSent.add(phone);
}
List<EntmicroStaffResponse> remindStaff = weekReportRemindStaffComponent.getRemindStaff(item.getMerchantNo());
if (!CollectionUtils.isEmpty(remindStaff)) {
for (EntmicroStaffResponse staff : remindStaff) {
String staffPhone = staff.getStaffPhone();
if (!StringUtils.isEmpty(staffPhone) && !hasBeenSent.contains(staffPhone)) {
log.info(staff + "管理员的短信开始发送,短信内容:{}", content);
messageService.sendMessage(phone, messageSource, "1", content);
hasBeenSent.add(staffPhone);
}
}
}
});
return true;
}
private Date getMonday() {
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek == 0) dayOfWeek = 7;
calendar.add(Calendar.DATE, -dayOfWeek + 1);
Date monday = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
monday = format.parse(format.format(monday));
} catch (ParseException e) {
e.printStackTrace();
}
return monday;
}
/**
* 同步授权的部门的员工以及客户客户群(广汇)
*
* @param merchantId
* @return
*/
public void syncDepStaCustAndCustGroup(Integer merchantId) {
// 查询同步的部门
List<EntmicroDepartmentResponse> authorizeDepartment = entmicroStaffService.findAuthorizeDepartment(merchantId);
if (!CollectionUtils.isEmpty(authorizeDepartment)) {
authorizeDepartment.forEach(index -> {
Integer relevanceMerchant = index.getRelevanceMerchant();
if (relevanceMerchant != null && merchantId.intValue() != relevanceMerchant) {
try {
syncStaffCust(relevanceMerchant, index.getDepartmentId(), merchantId);
} catch (Exception e) {
log.info("同步{}员工客户数据异常{}", index.getMerchantId(), e.getMessage());
}
}
});
}
}
/**
* 增量同步员工客户客户群数据(广汇)
*
* @param merchantId 授权商户号
* @param departmentId 部门id
* @param relevanceMerchant 关联的商户
*/
public void syncStaffCust(Integer relevanceMerchant, Integer departmentId, Integer merchantId) {
// 同步部门下面的员工
List<EntmicroStaff> entmicroStaffList = entmicroStaffService.syncEntmicroStaff(merchantId, true, departmentId, false);
List<String> userIds = entmicroStaffList.stream().map(EntmicroStaff::getUserId).collect(Collectors.toList());
// 同步部门下面新增员工的客户
if (!CollectionUtils.isEmpty(userIds)) {
syncEntmicroCustomer(relevanceMerchant, userIds, false);
// 同步部门下面新增员工的客户群
customerBaseService.syncEntmicroCustomerBase(merchantId, userIds);
}
log.info("增量同步员工客户客户群数据完成{}", departmentId);
}
/**
* 同步提取备注内容中的手机号、车牌号、车架号
*
* @param merchantId
*/
public void syncCustomerRemarkInfo(Integer merchantId, List<String> useridList) {
//TODO 客户信息缺少车牌号 、车架号字段
Integer supMerchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
log.info("同步客户:{},授权商户:{},获取企微客户数据{}", merchantId, supMerchantNo);
//批量获取数据
List<WorkWechatExternalContactListDTO> allCustomers = batchGetCustomerByStaff(useridList, supMerchantNo);
if (CollectionUtils.isEmpty(allCustomers)) {
log.info("========allCustomers is empty");
return;
}
//数据转化
List<CustomerStandardRequest> customerCompareModels = entrepConvert(allCustomers, merchantId);
//解析数据
customerCompareModels.forEach(index -> {
//客户数据
CustomerInfoRequest customerInfo = index.getCustomerInfo();
//跟进员工数据
List<CustomerFollowerStaffRequest> followerStaff = index.getFollowerStaff();
if (null != customerInfo) {
//多员工有备注内容时候,取最晚添加时间员工的备注内容为主;
if (!CollectionUtils.isEmpty(followerStaff) && followerStaff.size() > 0) {
Optional<CustomerFollowerStaffRequest> max = followerStaff.stream()
.max(Comparator.comparing(CustomerFollowerStaffRequest::getCreatedTime));
max.ifPresent(u -> {
CustomerFollowerStaffRequest customerFollowerStaffRequest = max.get();
//解析备注(业务优先以备注内容为主)
CustomerKafkaDTO customerKafkaDTO = RemarkUtils.distinguishMethod(customerFollowerStaffRequest.getRemark());
//解析描述
CustomerKafkaDTO customerKafkaDTO1 = RemarkUtils.distinguishMethod(customerFollowerStaffRequest.getDescription());
//手机号(业务优先以备注内容为主)
if (!StringUtils.isEmpty(customerKafkaDTO.getCustomerPhone())) {
customerInfo.setCustomerPhone(customerKafkaDTO.getCustomerPhone());
} else if (!StringUtils.isEmpty(customerKafkaDTO1.getCustomerPhone())) {
customerInfo.setCustomerPhone(customerKafkaDTO1.getCustomerPhone());
}
//车牌号(业务优先以备注内容为主)
if (!StringUtils.isEmpty(customerKafkaDTO.getCarNumber())) {
customerInfo.setCarNumber(customerKafkaDTO.getCarNumber());
} else if (!StringUtils.isEmpty(customerKafkaDTO1.getCarNumber())) {
customerInfo.setCarNumber(customerKafkaDTO1.getCarNumber());
}
//车架号(业务优先以备注内容为主)
if (!StringUtils.isEmpty(customerKafkaDTO.getCarVin())) {
customerInfo.setCarVin(customerKafkaDTO.getCarVin());
} else if (!StringUtils.isEmpty(customerKafkaDTO1.getCarVin())) {
customerInfo.setCarVin(customerKafkaDTO1.getCarVin());
}
});
}
}
});
List<CustomerInfoRequest> customerArrayList = new ArrayList<>();
List<CustomerInfoRequest> collect = customerCompareModels.stream().filter(index -> null != index.getCustomerInfo()).map(CustomerStandardRequest::getCustomerInfo).collect(Collectors.toList());
Map<String, List<CustomerInfoRequest>> map = collect.stream().collect(Collectors.groupingBy(item -> item.getUserid()));
//取出最晚客户数据
for (String key : map.keySet()) {
List<CustomerInfoRequest> customers = map.get(key);
Optional<CustomerInfoRequest> max = customers.stream()
.max(Comparator.comparing(CustomerInfoRequest::getCreatedTime));
max.ifPresent(cust -> {
customerArrayList.add(cust);
});
}
//过滤userId
List<String> userIdList = customerCompareModels.stream().map(CustomerStandardRequest::getCustomerInfo)
.map(CustomerInfoRequest::getUserid).collect(Collectors.toList());
//获取本地客户信息
Map<String, Customer> customersByUserId = getCustomersByUserId(userIdList);
//入库数据组装
List<Customer> customerList = new ArrayList<>();
for (CustomerInfoRequest customerInfoRequest : customerArrayList) {
if ((!StringUtils.isEmpty(customerInfoRequest.getUserid())) && customersByUserId.containsKey(customerInfoRequest.getUserid())) {
if (!StringUtils.isEmpty(customerInfoRequest.getCustomerPhone())) {
Customer customer = customersByUserId.get(customerInfoRequest.getUserid());
customer.setCustomerPhone(customerInfoRequest.getCustomerPhone());
customerList.add(customer);
}
}
}
if (CollectionUtils.isEmpty(customerList)) {
log.info("========customerList is empty");
return;
}
log.info("同步提取备注内容的客户数据: {}", customerList);
//更新手机号
customerMapper.updatePhoneByUserId(customerList);
//更新员工关联表
entmicroCustomerFollowMapper.updateBatchInfo(customerList);
//查找客户关联数据
List<EntmicroCustomerFollow> batchRelationInfo = entmicroCustomerFollowMapper.findBatchRelationInfo(userIdList);
// //回填企微端 影响范围:所有添加了该客户的员工备注 风险:有可能会把客户原来的备注更新掉,原因:无法判断哪个员工对客户进行了手机号备注。
// batchRelationInfo.forEach(index -> {
// RemarkWorkWechatExternalContactRequestDTO remarkWorkWechatExternalContactRequestDTO = new RemarkWorkWechatExternalContactRequestDTO();
// //备注的手机号
// remarkWorkWechatExternalContactRequestDTO.setRemarkMobiles(Arrays.asList(index.getRemarkMobiles()));
// //根据关联表id查询 客户 和 员工的userId
// remarkWorkWechatExternalContactRequestDTO.setUserId(index.getUserid());
// remarkWorkWechatExternalContactRequestDTO.setExternalUserId(index.getExternalUserId());
// remarkWorkWechatExternalContactRequestDTO.setMerchantId(supMerchantNo);
// try {
// log.info("提取备注内容修改企微端备注手机号入参: {}", JSONArray.toJSONString(remarkWorkWechatExternalContactRequestDTO));
// RpcResponse<BaseResponseDTO> baseResponseDTORpcResponse = contactRemote.remarkExternalContact(remarkWorkWechatExternalContactRequestDTO);
// log.info("提取备注内容修改企微端备注手机号结果: {}", JSONArray.toJSONString(baseResponseDTORpcResponse));
// } catch (RpcServiceException e) {
// log.info("同步提取备注内容回调备注手机号失败");
// e.printStackTrace();
// }
// });
//同步大数据 更新合并表
customerService.syncCustomerData(batchRelationInfo, "1", null, null);
//TODO 异步推送车辆数据到kafka
// producerComponent.sendKafkaMessageCustomerInfo();
}
/**
* 通过获取员工数据分批获取企微端客户数据
*
* @param
* @param useridList
* @param supMerchantNo
* @return
*/
public List<WorkWechatExternalContactListDTO> batchGetCustomerByStaff(List<String> useridList, Integer supMerchantNo) {
List<WorkWechatExternalContactListDTO> allCustomers = new ArrayList<>();
if (CollectionUtils.isEmpty(useridList)) {
List<EntmicroStaff> entmicroStaffs = entmicroStaffService.getEntmicroStaff(supMerchantNo, 1);
if (CollectionUtils.isEmpty(entmicroStaffs)) {
return allCustomers;
}
useridList = entmicroStaffs.stream().map(EntmicroStaff::getUserId).collect(Collectors.toList());
}
//100个数量限制,分批处理
int listSize = useridList.size();
int toIndex = 100;
for (int i = 0; i < listSize; i += 100) {
//作用为toIndex最后没有100条数据则剩余几条newList中就装几条
if (i + 100 > listSize) {
toIndex = listSize - i;
}
List batchUseridList = useridList.subList(i, i + toIndex);
//批量获取客户详情
batchGetCustomer(batchUseridList, supMerchantNo, allCustomers, "");
}
return allCustomers;
}
/**
* 保存同步日志
*/
public void saveLog(Integer merchantNo) {
List<Integer> allAuthMerchant = new ArrayList<>();
// 查询同步的门店
if (merchantNo == null) {
allAuthMerchant = entmicroAuthorizeMapper.findAllAuthMerchant();
} else {
allAuthMerchant.add(merchantNo);
}
if (!CollectionUtils.isEmpty(allAuthMerchant)) {
List<Integer> allAddLog = new ArrayList<>();
String date = com.glsx.plat.common.utils.DateUtils.format(new Date());
for (Integer merchantId : allAuthMerchant) {
if (allAddLog.contains(merchantId)) {
continue;
}
MerchantRopResponse merchantByMerchantNo = merchantService.findMerchantByMerchantNo(merchantId);
log.info("{}账户中心返回状态{}", merchantId, merchantByMerchantNo);
if (merchantByMerchantNo != null) {
Integer merchantModel = merchantByMerchantNo.getMerchantModel();
if (merchantModel == 1) {
Integer supMerchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
// 查询同步的部门
List<EntmicroDepartmentResponse> authorizeDepartment = entmicroStaffService.findAuthorizeDepartment(supMerchantNo);
if (!CollectionUtils.isEmpty(authorizeDepartment)) {
for (EntmicroDepartmentResponse index : authorizeDepartment) {
Integer relevanceMerchant = index.getRelevanceMerchant();
if (allAddLog.contains(relevanceMerchant)) {
continue;
}
try {
Integer departmentId = index.getDepartmentId();
if (relevanceMerchant != null && supMerchantNo.intValue() != relevanceMerchant) {
log.info("商户{}部门id{}", supMerchantNo, departmentId);
List<EntmicroStaff> remoteList = entmicroStaffService.getEntmicroStaff(supMerchantNo, departmentId == null ? 1 : departmentId);
log.info("部门{}企微员工size{}", departmentId, remoteList.size());
List<EntmicroStaffResponse> localList = entmicroStaffService.findStaffByEntDepartment(relevanceMerchant, departmentId);
log.info("部门{}本地员工size{}", departmentId, localList.size());
// 入库员工比对记录
insertLog(remoteList, localList, date, relevanceMerchant, 1);
List<String> useridList = remoteList.stream().map(EntmicroStaff::getUserId).collect(Collectors.toList());
List<WorkWechatExternalContactListDTO> allCustomers = batchGetCustomerByStaff(useridList, supMerchantNo);
log.info("部门{}企微员工size{}", departmentId, allCustomers.size());
List<CustomerStandardRequest> customerStandardRequests = findAllCustomerByMerchantId(relevanceMerchant, useridList);
log.info("部门{}本地客户size{}", departmentId, customerStandardRequests.size());
// 入库客户比对记录
insertLog(allCustomers, customerStandardRequests, date, relevanceMerchant, 2);
allAddLog.add(relevanceMerchant);
}
} catch (Exception e) {
e.printStackTrace();
log.info("统计异常{}", relevanceMerchant);
}
}
}
} else {
try {
List<EntmicroStaff> remoteList = entmicroStaffService.getEntmicroStaff(merchantId, 1);
List<EntmicroStaffResponse> localList = entmicroStaffService.findStaffByEntDepartment(merchantId, null);
// 入库员工比对记录
insertLog(remoteList, localList, date, merchantId, 1);
List<WorkWechatExternalContactListDTO> allCustomers = batchGetCustomerByStaff(null, merchantId);
List<CustomerStandardRequest> customerStandardRequests = findAllCustomerByMerchantId(merchantId, null);
// 入库客户比对记录
insertLog(allCustomers, customerStandardRequests, date, merchantId, 2);
allAddLog.add(merchantId);
} catch (Exception e) {
e.printStackTrace();
log.info("统计异常{}", merchantId);
}
}
}
}
}
}
/**
* 插入日志服务
*
* @param lista 集合
* @param listb 结合
* @param date 日期
* @param relevanceMerchant 门店
* @param type 类型
*/
public void insertLog(List<?> lista, List<?> listb, String date, Integer relevanceMerchant, Integer type) {
ScrmCompareLog scrmCompareLogStaff = new ScrmCompareLog();
scrmCompareLogStaff.setStaticTime(date);
scrmCompareLogStaff.setType(type);
scrmCompareLogStaff.setMerchantId(relevanceMerchant);
if (CollectionUtils.isEmpty(lista)) {
scrmCompareLogStaff.setEntmicroCount(0);
} else {
scrmCompareLogStaff.setEntmicroCount(lista.size());
}
if (CollectionUtils.isEmpty(listb)) {
scrmCompareLogStaff.setErpCount(0);
} else {
scrmCompareLogStaff.setErpCount(listb.size());
}
scrmCompareLogMapper.insertUseGeneratedKeys(scrmCompareLogStaff);
}
/**
* 同步客户关注公众号状态
*/
public void syncCustomerSubscribe(Integer merchantId) {
customerService.updateCustomerMergeSubscribe(officialAccountAppId, merchantId);
}
/**
* 同步公众号关注用户映射表
*/
public void syncWechatSubscriberMapping() {
RpcResponse<String> response = wechatAccessRemote.getAccessToken(officialAccountAppId);
log.info("公众号accessToken response:{}", response);
if (response == null || !response.isSuccess() || response.getResult() == null) {
return;
}
String accessToken = response.getResult();
// 获取公众号关注用户openId
List<String> wechatOpenIdList = getUserOpenIdListAll(accessToken);
log.info("公众号关注用户oenIdList:{}", wechatOpenIdList);
List<WechatSubscriberMappingDO> mappingDOList = customerService.findWechatSubscriberListByAppId(officialAccountAppId);
List<String> dbOpenIdList = mappingDOList.stream().map(WechatSubscriberMappingDO::getOpenId).collect(Collectors.toList());
List<String> unDbOpenIdList = mappingDOList.stream().filter(s -> Objects.equals(s.getSubscribe(), UN_SUBSCRIBE))
.map(WechatSubscriberMappingDO::getOpenId).collect(Collectors.toList());
List<String> isDbOpenIdList = mappingDOList.stream().filter(s -> Objects.equals(s.getSubscribe(), IS_SUBSCRIBE))
.map(WechatSubscriberMappingDO::getOpenId).collect(Collectors.toList());
// 新关注用户
List<String> newOpenIdList = wechatOpenIdList.stream().filter(s -> !dbOpenIdList.contains(s)).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(newOpenIdList)) {
log.info("公众号新关注用户 appId:{}, newOpenIdList:{}", officialAccountAppId, newOpenIdList);
List<WechatAccessUserInfoResponseDTO> userInfoAll = getUserInfoAll(newOpenIdList, accessToken);
if (!CollectionUtils.isEmpty(userInfoAll)) {
userInfoAll = userInfoAll.stream().filter(s -> Objects.equals(s.getSubscribe(), IS_SUBSCRIBE)).collect(Collectors.toList());
List<WechatSubscriberMappingDO> insertMappingDOList = new ArrayList<>();
for (WechatAccessUserInfoResponseDTO dto : userInfoAll) {
WechatSubscriberMappingDO mappingDO = new WechatSubscriberMappingDO();
mappingDO.setDelFlag((byte) 0);
mappingDO.setCreatedTime(new Date());
mappingDO.setAppId(officialAccountAppId);
mappingDO.setOpenId(dto.getOpenId());
mappingDO.setUnionId(dto.getUnionId());
mappingDO.setSubscribe(dto.getSubscribe());
mappingDO.setSubscribeTime(dto.getSubscribeTime());
insertMappingDOList.add(mappingDO);
}
customerService.insertWechatSubscriberMapping(insertMappingDOList);
}
}
// 已取关用户
List<String> unOpenIdList = isDbOpenIdList.stream().filter(s -> !wechatOpenIdList.contains(s)).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(unOpenIdList)) {
log.info("公众号取关用户 appId:{}, unOpenIdList:{}", officialAccountAppId, unOpenIdList);
customerService.updateWechatSubscriberMapping(unOpenIdList, officialAccountAppId, UN_SUBSCRIBE);
}
// 重新关注用户
List<String> backOpenIdList = unDbOpenIdList.stream().filter(wechatOpenIdList::contains).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(backOpenIdList)) {
log.info("公众号重新关注用户 appId:{}, backOpenIdList:{}", officialAccountAppId, backOpenIdList);
customerService.updateWechatSubscriberMapping(backOpenIdList, officialAccountAppId, IS_SUBSCRIBE);
}
}
/**
* 获取所有公众号openId用户信息
*
* @param openIdList 公众号openId
* @param accessToken 公众号调用接口凭证
* @return 用户信息
*/
public List<WechatAccessUserInfoResponseDTO> getUserInfoAll(List<String> openIdList, String accessToken) {
RpcAssert.assertNotEmpty(accessToken, DefaultErrorEnum.PARAMETER_NULL, "accessToken is not be null");
if (CollectionUtils.isEmpty(openIdList)) {
return null;
}
List<WechatAccessUserInfoResponseDTO> allUserInfoList = new ArrayList<>();
for (int i = 0; i < openIdList.size(); i = i + 100) {
int j = Math.min(i + 100, openIdList.size());
List<String> list = openIdList.subList(i, j);
RpcResponse<WechatAccessBatchUserInfoResponseDTO> batchUserInfo = wechatUserInfoRemote.getBatchUserInfo(list, accessToken);
log.info("公众号关注用户信息 batchUserInfo:{}", batchUserInfo);
if (batchUserInfo != null && batchUserInfo.isSuccess()) {
WechatAccessBatchUserInfoResponseDTO result = batchUserInfo.getResult();
if (result != null && (result.getErrCode() == null || Objects.equals(result.getErrCode(), 0))) {
List<WechatAccessUserInfoResponseDTO> userInfoList = result.getUserInfoList();
if (!CollectionUtils.isEmpty(userInfoList)) {
allUserInfoList.addAll(userInfoList);
}
}
}
}
return allUserInfoList;
}
public List<String> getUserOpenIdListAll(String accessToken) {
return getUserOpenIdListAll(accessToken, null, null, null);
}
/**
* 获取公众号所有关注用户openId
*
* @param accessToken 公众号调用凭证
* @param finalList openId列表
* @param nextOpenId 拉取列表的最后一个用户的OPENID
* @param count 拉取的 OPENID 个数,最大值为10000
* @return openId列表
*/
public List<String> getUserOpenIdListAll(String accessToken, List<String> finalList, String nextOpenId, Integer count) {
log.info("获取公众号所有关注用户openId nextOpenId:{},count:{}", nextOpenId, count);
finalList = finalList == null ? new ArrayList<>() : finalList;
count = count == null ? 0 : count;
RpcResponse<GetWechatAccessUserOpenIdListResponseDTO> response = wechatUserInfoRemote.getUserOpenIdList(nextOpenId, accessToken);
log.info("获取关注公众号用户openId response:{}", response);
if (response != null && response.isSuccess()) {
GetWechatAccessUserOpenIdListResponseDTO result = response.getResult();
if (result != null && (result.getErrCode() == null || Objects.equals(result.getErrCode(), 0))) {
WechatAccessUserOpenIdResponseDTO userOpenIdList = result.getUserOpenIdList();
List<String> openId = userOpenIdList.getOpenId();
finalList.addAll(openId);
count = count + result.getCount();
if (count < result.getTotal()) {
return getUserOpenIdListAll(accessToken, finalList, result.getNextOpenId(), count);
}
}
}
return finalList;
}
public void syncCustomerUnionId(Integer merchantId, String external_userid) {
GetWorkWechatExternalContactRequestDTO getWorkWechatExternalContactRequestDTO = new GetWorkWechatExternalContactRequestDTO();
getWorkWechatExternalContactRequestDTO.setMerchantId(merchantId);
getWorkWechatExternalContactRequestDTO.setExternalUserId(external_userid);
log.info("获取企微客户详情入参:{}", JSONArray.toJSONString(getWorkWechatExternalContactRequestDTO));
RpcResponse<WorkWechatExternalContactResponseDTO> externalContact = contactRemote.getExternalContact(getWorkWechatExternalContactRequestDTO);
log.info("获取企微客户详情:{}", JSONArray.toJSONString(externalContact));
if (externalContact == null || !externalContact.isSuccess()) {
return;
}
WorkWechatExternalContactResponseDTO result = externalContact.getResult();
if (result == null || !(result.getErrCode() == null || Objects.equals(result.getErrCode(), 0))) {
return;
}
WorkWechatExternalContactDTO contact = result.getExternalContact();
if (contact == null) {
return;
}
String unionid = contact.getUnionid();
if (StringUtils.isEmpty(unionid)) {
return;
}
customerService.updateCustomerUnionIdByUserId(external_userid, unionid);
}
/**
* 同步企微客户数据(主动)
*/
public List<CustomerStandardRequest> getEntmicroCustomer(Integer merchantId, List<String> useridList) {
if (null == merchantId) {
return null;
}
//调用接口获取企微客户
// 获取员工id列表
Integer supMerchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
List<WorkWechatExternalContactListDTO> allCustomers = batchGetCustomerByStaff(useridList, supMerchantNo);
if (!CollectionUtils.isEmpty(allCustomers)) {
log.info("门店{}企微客户总数{}", merchantId, allCustomers.size());
return entrepConvert(allCustomers, merchantId);
}
return null;
}
}