CustomerBaseService.java
82.9 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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
package cn.com.glsx.entmicro.service;
import cn.com.glsx.datahub.dto.*;
import cn.com.glsx.datahub.remote.ChatGroupRemote;
import cn.com.glsx.datahub.remote.UserProfileRemote;
import cn.com.glsx.entmicro.constants.Constants;
import cn.com.glsx.entmicro.entity.Customer;
import cn.com.glsx.entmicro.entity.CustomerBase;
import cn.com.glsx.entmicro.entity.CustomerBaseRelation;
import cn.com.glsx.entmicro.entity.EntmicroCustomerFollow;
import cn.com.glsx.entmicro.entity.mass.MassChatItemEntity;
import cn.com.glsx.entmicro.mapper.CustomerBaseMapper;
import cn.com.glsx.entmicro.mapper.CustomerMapper;
import cn.com.glsx.entmicro.model.BaseCustomerExportModel;
import cn.com.glsx.entmicro.model.BaseStaffExportModel;
import cn.com.glsx.entmicro.model.CustomerBaseCustListExportModel;
import cn.com.glsx.entmicro.model.CustomerBaseListExportModel;
import cn.com.glsx.entmicro.model.customer.SyncCustomerTypeTagModel;
import cn.com.glsx.entmicro.model.request.*;
import cn.com.glsx.entmicro.model.response.*;
import cn.com.glsx.entmicro.model.response.customer.CustomerBaseTagResponse;
import cn.com.glsx.entmicro.service.async.AsyncCustomerService;
import cn.com.glsx.entmicro.util.BeanConverUtil;
import cn.com.glsx.entmicro.util.EmojiUtils;
import cn.com.glsx.entmicro.util.ExcelExportUtils;
import cn.com.glsx.entmicro.util.ListUtils;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
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.workwechat.externalchat.request.GetWorkWechatExternalContactChatListOwnerFilterDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.externalchat.request.GetWorkWechatExternalContactChatListRequestDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.externalchat.request.GetWorkWechatExternalContactChatRequestDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.externalchat.response.*;
import cn.com.glsx.scrm.wechat.remote.WorkWechatExternalContactChatRemote;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.glsx.plat.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author fengzhi
* @Description: 客户群Service
* @date 2021/9/16 14:40
* matches 122
*/
@Service
@Slf4j
public class CustomerBaseService {
@Resource
private CustomerBaseMapper customerBaseMapper;
@Resource
private CustomerMapper customerMapper;
@Autowired
private CustomerBaseRelationService customerBaseRelationService;
@Autowired
private WorkWechatExternalContactChatRemote wechatExternalContactChatRemote;
@Autowired
@Lazy
private SyncDataService syncDataService;
@Autowired
private EntmicroStaffService entmicroStaffService;
@Autowired
private CustomerService customerService;
@Autowired
private GroupOneService groupOneService;
@Autowired
private RopCommonServie ropCommonServie;
@Autowired
private ChatGroupRemote chatGroupRemote;
@Autowired
private UserProfileRemote userProfileRemote;
@Autowired
private Environment environment;
@Resource
private AsyncCustomerService asyncCustomerService;
@Resource
private MerchantService merchantService;
/**
* 同步企微客户群数据(主动)
*/
public void syncEntmicroCustomerBase(Integer merchantId, List<String> userIds) {
List<CustomerBaseRequest> customerList = getCustomerList(merchantId, userIds);
log.info("商户{}获取企微客户群数据{}", merchantId, customerList);
List<CustomerBase> allChant = findAllChant(merchantId, userIds);
List<CustomerBaseRequest> oldCustomerList = allChant.stream().map(index -> {
CustomerBaseRequest customerBaseRequest = new CustomerBaseRequest();
customerBaseRequest.setChatId(index.getChatId());
return customerBaseRequest;
}).collect(Collectors.toList());
//emoji转化
for (CustomerBaseRequest customerBaseRequest : customerList) {
String chatName = EmojiUtils.parseToHtmlHexadecimal((customerBaseRequest.getChatName()));
customerBaseRequest.setChatName(chatName);
}
log.info("商户{}同步企微客户群数据本地数据: {}", merchantId, JSONObject.toJSONString(oldCustomerList));
log.info("同步企微客户群数据企微数据: {}", merchantId, JSONObject.toJSONString(customerList));
List<CustomerBaseRequest> addlist = customerList.stream().filter(index -> !oldCustomerList.contains(index)).collect(Collectors.toList());
List<CustomerBaseRequest> updatelist = customerList.stream().filter(index -> oldCustomerList.contains(index)).collect(Collectors.toList());
List<CustomerBaseRequest> deletelist = oldCustomerList.stream().filter(index -> !customerList.contains(index)).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(addlist)) {
addlist.forEach(index -> {
customerBaseAdd(index);
});
}
if (!CollectionUtils.isEmpty(updatelist)) {
updatelist.forEach(index -> {
customerBaseEdit(index);
});
}
if (!CollectionUtils.isEmpty(deletelist)) {
deletelist.forEach(index -> {
customerBaseDelete(index.getChatId());
});
}
}
private List<CustomerBase> findAllChant(Integer merchantId, List<String> userIds) {
return customerBaseMapper.findAllChantByUserIds(merchantId, userIds);
}
private List<CustomerBase> findByCustBaseIds(Integer merchantId) {
return customerBaseMapper.findAllChant(merchantId);
}
/**
* 客户群列表分页查询
*/
public Page<CustomerBaseListResponse> customerBasePageQuery(RpcPagination<CustomerBaseSearchRequest> request) {
//设置分页数据
PageHelper.startPage(request.getPageNum(), request.getPageSize());
CustomerBaseSearchRequest condition = request.getCondition();
Date endTime = condition.getEndTime();
if (null != endTime) {
condition.setEndTime(DateUtils.addDays(endTime, 1));
}
log.info("客户列表分页数据:{}", JSONArray.toJSONString(request));
//查询客户群列表
Page<CustomerBaseListResponse> list = customerBaseMapper.getCustomerBaseByPage(condition);
//数据组装
setCustomerBasePage(list, condition);
log.info("客户列表分页数据:{}", list);
return list;
}
/**
* 根据标签查询客户群列表
*/
public Page<CustomerBaseListResponse> getCustomerPageByTag(RpcPagination<CustomerBaseSearchRequest> request) {
// 根据标签查询群ID
log.info("根据标签查询chatId列表 request:{}", JSON.toJSONString(request));
long sta = System.currentTimeMillis();
ChatIdListQueryByGroupLabelDTO.ChatIdListQueryByGroupLabeRet res = chatGroupRemote.queryChatIdListByLabel(
convertToChatIdListQueryByGroupLabelReq(request));
long end = System.currentTimeMillis();
log.info("标签查询耗时:{}", (end - sta));
log.info("根据标签查询chatId列表 res:{}", JSON.toJSONString(res));
if (null == res || res.getCode() != 0) {
return new Page<>();
}
if (CollectionUtils.isEmpty(res.getChatIdList())) {
return new Page<>();
}
request.getCondition().setChatIdList(res.getChatIdList());
return customerBasePageQuery(request);
}
private ChatIdListQueryByGroupLabelDTO.ChatIdListQueryByGroupLabeReq convertToChatIdListQueryByGroupLabelReq(RpcPagination<CustomerBaseSearchRequest> request) {
ChatIdListQueryByGroupLabelDTO.ChatIdListQueryByGroupLabeReq req = new ChatIdListQueryByGroupLabelDTO.ChatIdListQueryByGroupLabeReq();
CustomerBaseSearchRequest condition = request.getCondition();
req.setPageNum(1);
req.setPageSize(Integer.MAX_VALUE);
req.setMerchantId(condition.getMerchantId());
req.setCombineType(condition.getCombineType());
if (!CollectionUtils.isEmpty(condition.getTagLists())) {
req.setLabelInfoList(condition.getTagLists().stream()
.map(p -> {
UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo conver = BeanConverUtil.conver(p, UserQueryByLabelDTO.UserQueryByLabelReq.LabelInfo.class);
conver.setLabelId(Integer.parseInt(p.getLabelId()));
return conver;
})
.collect(Collectors.toList()));
}
return req;
}
/**
* 客户群分页列表数据组装
*
* @param list
* @param condition
* @return
*/
private Page<CustomerBaseListResponse> setCustomerBasePage(Page<CustomerBaseListResponse> list, CustomerBaseSearchRequest condition) {
if (!CollectionUtils.isEmpty(list)) {
List<Integer> collect = list.stream().map(CustomerBaseListResponse::getId).collect(Collectors.toList());
//查询成员总数,包括客户和员工
List<GetCustomerTotalResponse> allMemberList = customerBaseMapper.getAllMembers(collect);
//查询客群中的跟进员工数
List<GetCustomerTotalResponse> staffList = customerBaseMapper.getStaffs(collect);
//查询所有客户总数(仅客户)
List<GetCustomerTotalResponse> customerList = customerBaseMapper.countAllBaseCustomerNum(collect);
//今日新增人数
List<GetCustomerTotalResponse> todayCustomer = customerBaseMapper.getTodayCustomer(condition.getMerchantId());
//查出所有入群记录(退群记录) 用customerId和customerBaseId做匹配取差异数据
//今日退群记录
Set<StatisticsCustomerBaseInfoResponse> todayRemoveCustomerList = customerBaseMapper.getTodayRemoveList(collect);
//今日入群记录
Set<StatisticsCustomerBaseInfoResponse> todayAddCustomerList = customerBaseMapper.getTodayAddList(collect);
//取出差异化数据
//今天退群列表
Set<StatisticsCustomerBaseInfoResponse> removeList = new HashSet<>();
if (!CollectionUtils.isEmpty(todayRemoveCustomerList)) {
if (CollectionUtils.isEmpty(todayAddCustomerList)) {
removeList = todayRemoveCustomerList;
} else {
removeList = todayRemoveCustomerList.stream().filter(index -> !todayAddCustomerList.contains(index)).collect(Collectors.toSet());
}
}
//人数赋值
for (CustomerBaseListResponse customerBaseListResponse : list) {
parseChatName(customerBaseListResponse);
//成员总数
for (GetCustomerTotalResponse members : allMemberList) {
if (customerBaseListResponse.getChatId().equals(members.getChatId())) {
customerBaseListResponse.setAllMembers(members.getTotal());
break;
}
}
if (null == customerBaseListResponse.getAllMembers()) {
customerBaseListResponse.setAllMembers(0);
}
//跟进员工数
for (GetCustomerTotalResponse staffs : staffList) {
if (customerBaseListResponse.getChatId().equals(staffs.getChatId())) {
customerBaseListResponse.setStaffs(staffs.getTotal());
break;
}
}
if (null == customerBaseListResponse.getStaffs()) {
customerBaseListResponse.setStaffs(0);
}
//群客户总数
for (GetCustomerTotalResponse customer : customerList) {
if (customerBaseListResponse.getId().equals(customer.getCustomerBaseId())) {
customerBaseListResponse.setTotalCount(customer.getTotal());
break;
}
}
if (null == customerBaseListResponse.getStaffs()) {
customerBaseListResponse.setStaffs(0);
}
//入群人数
for (GetCustomerTotalResponse todayAddList : todayCustomer) {
if (customerBaseListResponse.getChatId().equals(todayAddList.getChatId())) {
customerBaseListResponse.setNewCustomerCount(todayAddList.getTotal());
break;
}
}
//退群人数
if (CollectionUtils.isEmpty(removeList)) {
customerBaseListResponse.setNewCustomerCount(0);
} else {
List<StatisticsCustomerBaseInfoResponse> removeTotal = new ArrayList<>();
for (StatisticsCustomerBaseInfoResponse ind : removeList) {
if (customerBaseListResponse.getId().equals(ind.getCustomerBaseId())) {
removeTotal.add(ind);
}
}
customerBaseListResponse.setDelCustomerCount(removeTotal.size());
}
}
}
return list;
}
/**
* 客户群详情
*/
public CustomerBaseInfoResponse getCustomerBaseDetail(CustBaseDetailRpcRequest custBaseDetailRpcRequest) {
log.info("客户群详情入参:{}", JSONArray.toJSONString(custBaseDetailRpcRequest));
List<Integer> authorizeMerchants = entmicroStaffService.findAuthorizeMerchantNo(entmicroStaffService.findSupMerchantNo(custBaseDetailRpcRequest.getMerchantId()));
log.info("授权商户{}", authorizeMerchants);
if (com.glsx.plat.common.utils.StringUtils.isNotEmpty(custBaseDetailRpcRequest.getChatId())) {
CustomerBaseInfoResponse byChatId = customerBaseMapper.findByChatId(custBaseDetailRpcRequest.getChatId());
if (null == byChatId) {
log.info("客户群详情入参chatId:{}本地数据不存在", custBaseDetailRpcRequest.getChatId());
return null;
}
custBaseDetailRpcRequest.setId(byChatId.getId());
}
CustomerBaseInfoResponse infoResponse = customerBaseMapper.getCustomerBaseInfo(custBaseDetailRpcRequest.getId(), authorizeMerchants);
if (!StringUtils.isEmpty(infoResponse)) {
//emoji转化
infoResponse.setGroupHostDepart(infoResponse.getGroupHostDepart() != null ? EmojiUtils.parseToUnicode(infoResponse.getGroupHostDepart()) : null);
infoResponse.setGroupAdmin(infoResponse.getGroupAdmin() != null ? EmojiUtils.parseToUnicode(infoResponse.getGroupAdmin()) : null);
infoResponse.setGroupHostName(infoResponse.getGroupHostName() != null ? EmojiUtils.parseToUnicode(infoResponse.getGroupHostName()) : null);
infoResponse.setGroupName(infoResponse.getGroupName() != null ? EmojiUtils.parseToUnicode(infoResponse.getGroupName()) : null);
}
//获取列表客户数
RpcPagination<CustBaseCustSearchRequest> request = new RpcPagination<>();
CustBaseCustSearchRequest custBaseCustSearchRequest = new CustBaseCustSearchRequest();
request.setPageNum(custBaseDetailRpcRequest.getPageNum());
request.setPageSize(custBaseDetailRpcRequest.getPageSize());
custBaseCustSearchRequest.setId(custBaseDetailRpcRequest.getId());
custBaseCustSearchRequest.setMerchantId(custBaseDetailRpcRequest.getMerchantId());
custBaseCustSearchRequest.setDatalist(custBaseDetailRpcRequest.getDatalist());
request.setCondition(custBaseCustSearchRequest);
//查询所有客户总数(仅客户)
Integer allCount = 0;
List<GetCustomerTotalResponse> customerList = customerBaseMapper.countAllBaseCustomerNum(
Collections.singletonList(custBaseDetailRpcRequest.getId()));
if (!CollectionUtils.isEmpty(customerList)) {
allCount = customerList.get(0).getTotal();
}
infoResponse.setAllCount(allCount);
//员工数
Page<CustomerBaseStaffListResponse> customerBaseStaffList = customerBaseStaffList(request);
if (null != customerBaseStaffList) {
Integer staffCount = (int) customerBaseStaffList.getTotal();
infoResponse.setStaffCount(staffCount);
} else {
infoResponse.setStaffCount(0);
}
//退群客户数
int quitCount = 0;
Set<StatisticsCustomerBaseInfoResponse> allRemoveList = customerBaseMapper.getAllRemoveList(
Collections.singletonList(custBaseDetailRpcRequest.getId()));
if (!CollectionUtils.isEmpty(allRemoveList)) {
quitCount = allRemoveList.size();
}
infoResponse.setQuitCount(quitCount);
//潜在客户数
Page<CustomerBaseCustListResponse> customerBasePotentialCustList = customerBasePotentialCustList(request);
if (null != customerBasePotentialCustList) {
Integer potentialCount = (int) customerBasePotentialCustList.getTotal();
infoResponse.setPotentialCount(potentialCount);
} else {
infoResponse.setPotentialCount(0);
}
// 群标签
try {
String property = environment.getProperty("entmicro.gh.flag");
if (StringUtils.isEmpty(property)) {
infoResponse.setTagCount(countCustomerBaseTag(custBaseDetailRpcRequest.getId()));
}
} catch (Exception e) {
log.error("群标签获取失败", e);
}
return infoResponse;
}
/**
* 客户群的客户列表
*/
public Page<CustomerBaseCustListResponse> customerBaseCustList(RpcPagination<CustBaseCustSearchRequest> request) {
//设置分页数据
PageHelper.startPage(request.getPageNum(), request.getPageSize());
CustBaseCustSearchRequest condition = request.getCondition();
log.info("客户群的客户列表入参: {}", JSONArray.toJSONString(condition));
Date endTime = condition.getEndTime();
if (null != endTime) {
condition.setEndTime(DateUtils.addDays(endTime, 1));
}
//客户数据
Page<CustomerBaseCustListResponse> list = customerBaseMapper.getGroupCustomerByPage(condition);
if (!CollectionUtils.isEmpty(list)) {
List<String> collect = list.stream().map(CustomerBaseCustListResponse::getLord).collect(Collectors.toList());
Integer authorizeEnt = entmicroStaffService.findSupMerchantNo(condition.getMerchantId());
Map<String, EntmicroStaffResponse> idsByUserIds = entmicroStaffService.getIdsByUserIds(collect, authorizeEnt);
list.stream().forEach(cust -> {
//emoji转化
cust.setCustomerName(cust.getCustomerName() != null ? EmojiUtils.parseToUnicode(cust.getCustomerName()) : null);
cust.setGroupNickName(cust.getGroupNickName() != null ? EmojiUtils.parseToUnicode(cust.getGroupNickName()) : null);
cust.setInvitorName(cust.getInvitorName() != null ? EmojiUtils.parseToUnicode(cust.getInvitorName()) : null);
if (!CollectionUtils.isEmpty(idsByUserIds) && idsByUserIds.containsKey(cust.getLord())) {
cust.setLordName(idsByUserIds.get(cust.getLord()).getStaffName());
}
});
}
return list;
}
/**
* 客户群创建
*/
@Transactional(rollbackFor = RpcServiceException.class)
public void customerBaseAdd(CustomerBaseRequest request) {
log.info("客户群创建入参: {}", JSONArray.toJSONString(request));
CustomerBase cust = customerBaseMapper.getByChatId(request.getChatId());
if (null != cust) {
log.info("客户群新增,chatId存在:{}", cust.getChatId());
return;
}
CustomerBase customerBase = BeanConverUtil.conver(request, CustomerBase.class);
customerBase.setCreatedBy(request.getCreatedBy());
customerBase.setDelFlag(Constants.NORMAL_FLAG);
customerBaseMapper.insertUseGeneratedKeys(customerBase);
log.info("客户群新增,data:{}", customerBase);
List<CustomerBaseRelationRequest> relationRequestList = request.getCustomerBaseRelationRequestList();
List<CustomerBaseRelation> buildCustomerRel = buildCustomerRel(relationRequestList, customerBase.getId());
customerBaseRelationService.insertList(buildCustomerRel);
// 暂时不做处理,交由大数据端同步
// // 同步客户群标签
// if (!CollectionUtils.isEmpty(request.getCustomerBaseRelationRequestList())) {
// request.getCustomerBaseRelationRequestList().stream()
// .filter(p -> p.getType() == Constants.CUSTOMER_BASE_CONSTANTS.MEMBER_CUSTOMER)
// .min(Comparator.comparing(CustomerBaseRelationRequest::getJoinTime, Comparator.nullsLast(Date::compareTo)))
// .ifPresent(p -> {
// List<Integer> tagList = getCustomerTag(p.getCustomerId());
// syncChatTag(customerBase.getMerchantid(), customerBase.getChatId(), tagList, null);
// });
// }
List<String> userIds = relationRequestList.stream().map(CustomerBaseRelationRequest::getUserId).collect(Collectors.toList());
asyncCustomerService.syncCustomerTypeTag(new SyncCustomerTypeTagModel(
request.getMerchantid(), 1, request.getUpdateDetail(), request.getChatId(), userIds));
}
/**
* 调用远程服务,同步客户群标签
*/
public boolean syncChatTag(Integer merchantId, String chatId, List<Integer> addTagList, List<Integer> delTagList) {
if (CollectionUtils.isEmpty(addTagList) && CollectionUtils.isEmpty(delTagList)) {
return false;
}
ChatGroupLabelEditDTO.ChatGroupLabelEditReq chatLabelReq = new ChatGroupLabelEditDTO.ChatGroupLabelEditReq();
chatLabelReq.setChatId(chatId);
chatLabelReq.setMerchantId(merchantId);
chatLabelReq.setLabelIdAddList(addTagList);
chatLabelReq.setLabelIdDelList(delTagList);
log.info("editChatGroupLabel chatLabelReq:{}", JSON.toJSONString(chatLabelReq));
ChatGroupLabelEditDTO.ChatGroupLabelEditRet res = chatGroupRemote.editChatGroupLabel(chatLabelReq);
log.info("editChatGroupLabel res:{}", JSON.toJSONString(res));
if (res == null || res.getCode() != 0) {
log.error("sync chat tag failed, response is {}", res);
return false;
}
return true;
}
/**
* 获取指定客户的‘系统’标签ID列表,同步到群
*/
public List<Integer> getCustomerTag(Integer customerId) {
Customer customer = customerMapper.selectByPrimaryKey(customerId);
if (customer == null) {
return null;
}
UserLabelDTO.UserLabelReq userLabelReq = new UserLabelDTO.UserLabelReq();
userLabelReq.setMerchantIdsStr(customer.getMerchantid() + "");
userLabelReq.setOneId(customer.getOneId());
UserLabelDTO.UserLabelRet userLabelRes = userProfileRemote.getUserLabel(userLabelReq);
if (userLabelRes == null || userLabelRes.getCode() != 0) {
return null;
}
return parseSyncSysTag(userLabelRes.getUserLabelUnitList());
}
/**
* 获取客户群特定的标签列表(同步自第一入群外部联系人)
*/
public List<UserLabelDTO.UserLabelRet.UserLabelUnit> getCustomerBaseSyncTag(Integer merchantId, String chatId) {
return getCustomerBaseSyncTag(merchantId, chatId, 0);
}
public List<UserLabelDTO.UserLabelRet.UserLabelUnit> getCustomerBaseSyncTag(Integer merchantId, String chatId, Integer filterType) {
ChatGroupLabelGetDTO.ChatGroupLabelGetReq getChatReq = new ChatGroupLabelGetDTO.ChatGroupLabelGetReq();
getChatReq.setChatId(chatId);
getChatReq.setMerchantId(merchantId);
getChatReq.setFilterType(filterType);
log.info("编辑客户群标签 getChatReq:{}", JSON.toJSONString(getChatReq));
ChatGroupLabelGetDTO.ChatGroupLabelGetRet getChatRes = chatGroupRemote.getChatGroupLabel(getChatReq);
log.info("编辑客户群标签 getChatRes:{}", JSON.toJSONString(getChatRes));
if (getChatRes == null || getChatRes.getCode() != 0) {
return null;
}
return getChatRes.getUserLabelUnitList();
}
/**
* 获取指定范围的系统标签
*/
public List<Integer> parseSyncSysTag(List<UserLabelDTO.UserLabelRet.UserLabelUnit> labelUnitList) {
if (CollectionUtils.isEmpty(labelUnitList)) {
return null;
}
List<Integer> tagIDList = Lists.newArrayList();
labelUnitList.stream()
.filter(p -> !CollectionUtils.isEmpty(p.getLabelInfoList()))
.forEach(t -> {
t.getLabelInfoList().stream()
.filter(l -> Constants.CUSTOMER_BASE_CONSTANTS.CHAT_ALLOW_TAG_NAME.contains(l.getLabelName()))
.forEach(l -> tagIDList.add(l.getLabelId()));
});
return tagIDList;
}
/**
* 客户群编辑
*/
@Transactional(rollbackFor = RpcServiceException.class)
public void customerBaseEdit(CustomerBaseRequest request) {
String chatId = request.getChatId();
CustomerBase customerBase = customerBaseMapper.getByChatId(chatId);
if (null == customerBase) {
log.info("客户群编辑,chatId不存在:{}", chatId);
return;
}
CustomerBase customerBaseUpdate = BeanConverUtil.conver(request, CustomerBase.class);
customerBaseUpdate.setId(customerBase.getId());
customerBaseUpdate.setUpdatedBy(request.getCreatedBy());
customerBaseUpdate.setUpdatedTime(new Date());
customerBaseMapper.updateByPrimaryKeySelective(customerBaseUpdate);
log.info("客户群编辑,data:{}", customerBaseUpdate);
List<CustomerBaseRelationRequest> relationRequestList = request.getCustomerBaseRelationRequestList();
List<CustomerBaseRelation> customerBaseRelations = buildCustomerRel(relationRequestList, customerBase.getId());
List<CustomerBaseRelation> list = customerBaseRelationService.findByCustomerId(customerBase.getId());
log.info("客户群:{},客户:{}", request.getChatName(), customerBaseRelations);
List<CustomerBaseRelation> addlist = customerBaseRelations.stream().filter(index -> !list.contains(index)).collect(Collectors.toList());
List<CustomerBaseRelation> updatelist = customerBaseRelations.stream().filter(index -> list.contains(index)).collect(Collectors.toList());
List<CustomerBaseRelation> deletelist = list.stream().filter(index -> (index.getDelFlag() == null || index.getDelFlag() != -1)
&& !customerBaseRelations.contains(index)).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(addlist)) {
log.info("有客户入群:{}", addlist);
customerBaseRelationService.insertList(addlist);
reportCustomerJoinGroupType(request, addlist);
}
if (!CollectionUtils.isEmpty(updatelist)) {
log.info("有客户修改群信息:{}", updatelist);
customerBaseRelationService.updatelist(updatelist);
reportCustomerJoinGroupType(request, updatelist);
}
if (!CollectionUtils.isEmpty(deletelist)) {
log.info("有客户退群:{}", deletelist);
customerBaseRelationService.deletelist(deletelist);
reportCustomerJoinGroupType(request, deletelist);
}
// 暂时不做处理,交由大数据端同步
// // 同步客户群标签
// boolean noChange = CollectionUtils.isEmpty(addlist) && CollectionUtils.isEmpty(updatelist) && CollectionUtils.isEmpty(deletelist);
// if (!noChange) {
// // 查询第一入群外部联系人是否发生改变
// CustomerBaseRelation oldFirstCustomer = list.stream()
// .filter(p -> p.getType() == Constants.CUSTOMER_BASE_CONSTANTS.MEMBER_CUSTOMER)
// .min(Comparator.comparing(CustomerBaseRelation::getJoinTime, Comparator.nullsLast(Date::compareTo))).orElse(null);
// CustomerBaseRelation newFirstCustomer = customerBaseRelationService.getFirstCustomerByCustomerId(customerBase.getId());
// int oldFirstCustomerId = oldFirstCustomer != null ? oldFirstCustomer.getCustomerId() : 0;
// int newFirstCustomerId = newFirstCustomer != null ? newFirstCustomer.getCustomerId() : 0;
// if (oldFirstCustomerId != newFirstCustomerId) {
// List<Integer> addTagIDList = null;
// List<Integer> delTagIDList = null;
// // 取消标签列表
// if (oldFirstCustomerId != 0) {
// delTagIDList = parseSyncSysTag(getCustomerBaseSyncTag(customerBase.getMerchantid(), customerBase.getChatId()));
// }
// // 新增标签列表
// if (newFirstCustomerId != 0) {
// addTagIDList = getCustomerTag(newFirstCustomer.getCustomerId());
// }
// syncChatTag(customerBase.getMerchantid(), customerBase.getChatId(), addTagIDList, delTagIDList);
// }
// }
}
private void reportCustomerJoinGroupType(CustomerBaseRequest request, List<CustomerBaseRelation> addlist) {
List<Integer> customerIds = addlist.stream().map(CustomerBaseRelation::getCustomerId).collect(Collectors.toList());
List<String> userIds = customerMapper.findUserIdByCustomerId(customerIds);
asyncCustomerService.syncCustomerTypeTag(new SyncCustomerTypeTagModel(
request.getMerchantid(), 1, request.getChatId(), userIds));
}
/**
* 构建客户群
*
* @param baseRelationRequests 入参
* @param customerId id
* @return
*/
public List<CustomerBaseRelation> buildCustomerRel(List<CustomerBaseRelationRequest> baseRelationRequests, Integer customerId) {
List<CustomerBaseRelation> collect = null;
if (!CollectionUtils.isEmpty(baseRelationRequests)) {
collect = baseRelationRequests.stream().map(index -> {
CustomerBaseRelation customerBaseRelation = new CustomerBaseRelation();
BeanUtils.copyProperties(index, customerBaseRelation);
customerBaseRelation.setCustomerBaseId(customerId);
//群昵称emoji转化
customerBaseRelation.setGroupNickname(!StringUtils.isEmpty(customerBaseRelation.getGroupNickname()) ? EmojiUtils.parseToHtmlHexadecimal(customerBaseRelation.getGroupNickname()) : "");
customerBaseRelation.setDelFlag(Constants.NORMAL_FLAG);
return customerBaseRelation;
}).collect(Collectors.toList());
}
return collect;
}
/**
* 客户群删除
*/
@Transactional(rollbackFor = RpcServiceException.class)
public void customerBaseDelete(String chatId) {
log.info("客户群删除,chatId:{}", chatId);
CustomerBase customerBase = customerBaseMapper.getByChatId(chatId);
if (null == customerBase) {
log.info("客户群删除,chatId不存在:{}", chatId);
return;
}
customerBase.setUpdatedTime(new Date());
customerBase.setDelFlag(Constants.DEL_FLAG);
//客户群删除
customerBaseMapper.updateByPrimaryKeySelective(customerBase);
//客户,客户群关联解除
Integer customerBaseId = customerBase.getId();
customerBaseRelationService.deleteByCustomerBaseId(customerBaseId);
}
public List<CustomerBaseRequest> getCustomerList(Integer merchantId, List<String> userIds) {
if (CollectionUtils.isEmpty(userIds)) {
return getCustomerBaseList(merchantId, userIds);
} else {
List<CustomerBaseRequest> totalCustomerBaseList = new ArrayList<>();
List<List<String>> partition = org.apache.commons.collections4.ListUtils.partition(userIds, 100);
partition.forEach(index -> {
List<CustomerBaseRequest> customerBaseList = getCustomerBaseList(merchantId, index);
totalCustomerBaseList.addAll(customerBaseList);
});
return totalCustomerBaseList;
}
}
public List<CustomerBaseRequest> getCustomerBaseList(Integer merchantId, List<String> userIds) {
List<WorkWechatExternalContactChatDTO> customerBase = getCustomerBase(null, new ArrayList<>(), merchantId, userIds);
List<CustomerBaseRequest> list = new ArrayList<>();
if (!CollectionUtils.isEmpty(customerBase)) {
customerBase.forEach(index -> {
try {
list.add(getCustomerBase(index.getChatId(), merchantId));
} catch (Exception e) {
log.info("{} 客户群获取异常", index.getChatId());
e.printStackTrace();
}
});
}
return list;
}
/**
* 获取企微客户群详情
*
* @param chantId
* @param merchantId
* @return
*/
public CustomerBaseRequest getCustomerBase(String chantId, Integer merchantId) {
GetWorkWechatExternalContactChatRequestDTO getWorkWechatExternalContactChatRequestDTO = new GetWorkWechatExternalContactChatRequestDTO();
getWorkWechatExternalContactChatRequestDTO.setChatId(chantId);
getWorkWechatExternalContactChatRequestDTO.setMerchantId(merchantId);
//企微返回群客户名字 0-不返回 1-返回
getWorkWechatExternalContactChatRequestDTO.setNeedName(1);
log.info("客户群入参{}", JSONArray.toJSONString(getWorkWechatExternalContactChatRequestDTO));
RpcResponse<WorkWechatExternalContactChatResponseDTO> externalContactChat = wechatExternalContactChatRemote.getExternalContactChat(getWorkWechatExternalContactChatRequestDTO);
log.info("客户群返回结果{}", JSONArray.toJSONString(externalContactChat));
if (!externalContactChat.isSuccess()) {
throw new RpcServiceException(externalContactChat.getException().getErrId(), externalContactChat.getMessage());
}
WorkWechatExternalContactChatResponseDTO result = externalContactChat.getResult();
return buildCustomerBase(result.getGroupChat(), merchantId);
}
/**
* 构建群成员参数
*
* @param groupChat 入参
* @return
*/
private CustomerBaseRequest buildCustomerBase(WorkWechatExternalContactChatDetailDTO groupChat, Integer merchantId) {
log.info("客户群构建参数入参:{}", groupChat);
if (null == groupChat) {
return null;
}
CustomerBaseRequest customerBaseRequest = new CustomerBaseRequest();
//判断创建方式
List<GroupOneResponse> groupOneByChatId = groupOneService.getGroupOneByChatId(groupChat.getChatId());
if (CollectionUtils.isEmpty(groupOneByChatId)) {
//手动拉群
customerBaseRequest.setCreationMethod(Constants.CUSTOMER_BASE_CONSTANTS.SCRM_CUSTOMER_BASE);
} else {
//一客一群
customerBaseRequest.setCreationMethod(Constants.CUSTOMER_BASE_CONSTANTS.SCRM_GROUP_ONE);
}
//群聊id
customerBaseRequest.setChatId(groupChat.getChatId());
//群主
customerBaseRequest.setLord(groupChat.getOwner());
//群聊名
customerBaseRequest.setChatName(EmojiUtils.parseToHtmlHexadecimal(groupChat.getName()));
//商户号
customerBaseRequest.setMerchantid(merchantId);
//创建时间
customerBaseRequest.setCreatedTime(new Date(groupChat.getCreateTime() * 1000));
//管理员
List<WorkWechatExternalContactChatAdminDTO> adminList = groupChat.getAdminList();
if (!CollectionUtils.isEmpty(adminList)) {
//根据userId查询本地员工名称
List<String> collect = adminList.stream().map(WorkWechatExternalContactChatAdminDTO::getUserId).collect(Collectors.toList());
List<EntmicroStaffResponse> listByUserIds = entmicroStaffService.getListByUserIds(collect, merchantId);
if (!CollectionUtils.isEmpty(listByUserIds)) {
List<String> staffName = listByUserIds.stream().map(EntmicroStaffResponse::getStaffName).collect(Collectors.toList());
customerBaseRequest.setChatManage(ListUtils.listToString(staffName, ','));
}
}
//群聊成员
List<WorkWechatExternalContactChatMemberDTO> memberList = groupChat.getMemberList();
if (CollectionUtils.isEmpty(memberList)) {
log.info("群聊chatId:{}的memberList为空", groupChat.getChatId());
return customerBaseRequest;
}
log.info("客户群成员列表:data:{}", JSONArray.toJSONString(memberList));
//群成员userId
List<String> stringList = memberList.stream().map(WorkWechatExternalContactChatMemberDTO::getUserId).collect(Collectors.toList());
//邀请人信息
List<WorkWechatExternalContactChatMemberInvitorDTO> invitorDTOS = memberList.stream().map(WorkWechatExternalContactChatMemberDTO::getInvitor).collect(Collectors.toList());
Map<String, EntmicroStaffResponse> invitorMap = new HashMap<>();
if (!CollectionUtils.isEmpty(invitorDTOS)) {
//获取邀请人信息
log.info("客户群邀请人信息:data:{}", JSONArray.toJSONString(invitorDTOS));
List<String> collect = new ArrayList<>();
invitorDTOS.forEach(index -> {
if (null != index) {
collect.add(index.getUserId());
}
});
if (!CollectionUtils.isEmpty(collect)) {
invitorMap = entmicroStaffService.getIdsByUserIds(collect, merchantId);
}
}
//获取本地客户信息
Map<String, Customer> customersByUserId = syncDataService.getCustomersByUserId(stringList);
//获取员工本地信息
Map<String, EntmicroStaffResponse> staffsExist = entmicroStaffService.getIdsByUserIds(stringList, merchantId);
List<CustomerBaseRelationRequest> customerBaseRelationRequests = new ArrayList<>();
//数据入库构建
for (WorkWechatExternalContactChatMemberDTO ind : memberList) {
CustomerBaseRelationRequest customerBaseRelationRequest = new CustomerBaseRelationRequest();
//1 - 员工
//2 - 客户
if (ind.getType() == Constants.CUSTOMER_BASE_CONSTANTS.MEMBER_STAFF) {
if (!CollectionUtils.isEmpty(staffsExist)) {
EntmicroStaffResponse entmicroStaffResponse = staffsExist.get(ind.getUserId());
if (entmicroStaffResponse == null) {
log.info("员工{}不存在", ind);
continue;
}
customerBaseRelationRequest.setCustomerId(entmicroStaffResponse.getId());
}
} else {
Customer customer = customersByUserId.get(ind.getUserId());
if (customer == null) {
CustomerAddBaseRequest customerAddBaseRequest = new CustomerAddBaseRequest();
//存入本地 并同步到数据中台
customerAddBaseRequest.setUserId(ind.getUserId());
customerAddBaseRequest.setMerchantId(merchantId);
customerAddBaseRequest.setCreatedTime(new Date(ind.getJoinTime() * 1000L));
Customer customerAddBase = customerService.customerAddBase(customerAddBaseRequest);
customerBaseRelationRequest.setCustomerId(customerAddBase.getId());
} else {
customerBaseRelationRequest.setCustomerId(customer.getId());
}
}
//群昵称为空则使用微信昵称
if (!StringUtils.isEmpty(ind.getGroupNickname())) {
//emoji解码
String groupNickname = EmojiUtils.parseToHtmlHexadecimal((ind.getGroupNickname()));
customerBaseRelationRequest.setGroupNickname(groupNickname);
} else {
//emoji解码
String groupNickname = EmojiUtils.parseToHtmlHexadecimal((ind.getName()));
customerBaseRelationRequest.setGroupNickname(groupNickname);
}
log.info("企微群客户信息{}", ind);
customerBaseRelationRequest.setJoinScene(ind.getJoinScene());
customerBaseRelationRequest.setType(ind.getType());
customerBaseRelationRequest.setJoinTime(new Date(ind.getJoinTime() * 1000L));
//邀请人信息
if (!CollectionUtils.isEmpty(invitorMap)) {
WorkWechatExternalContactChatMemberInvitorDTO invitor = ind.getInvitor();
if (null != invitor) {
if (invitorMap.containsKey(invitor.getUserId())) {
customerBaseRelationRequest.setInvitor(invitorMap.get(invitor.getUserId()).getId());
}
}
}
customerBaseRelationRequest.setUserId(ind.getUserId());
customerBaseRelationRequests.add(customerBaseRelationRequest);
}
customerBaseRequest.setCustomerBaseRelationRequestList(customerBaseRelationRequests);
return customerBaseRequest;
}
/**
* 企微客户群数据获取(主动)
*/
public List<WorkWechatExternalContactChatDTO> getCustomerBase(String cursor, List<WorkWechatExternalContactChatDTO> list, Integer merchantId, List<String> userIds) {
GetWorkWechatExternalContactChatListRequestDTO requestDTO = new GetWorkWechatExternalContactChatListRequestDTO();
if (StrUtil.isNotEmpty(cursor)) {
requestDTO.setCursor(cursor);
}
requestDTO.setLimit(1000);
requestDTO.setMerchantId(merchantId);
if (!CollectionUtils.isEmpty(userIds)) {
GetWorkWechatExternalContactChatListOwnerFilterDTO getWorkWechatExternalContactChatListOwnerFilterDTO = new GetWorkWechatExternalContactChatListOwnerFilterDTO();
getWorkWechatExternalContactChatListOwnerFilterDTO.setUseridList(userIds);
requestDTO.setOwnerFilter(getWorkWechatExternalContactChatListOwnerFilterDTO);
}
RpcResponse<WorkWechatExternalContactChatListResponseDTO> externalContactChatList = wechatExternalContactChatRemote.getExternalContactChatList(requestDTO);
log.info("同步企微客户群数据,getCustomerBase:{}", JSONObject.toJSONString(externalContactChatList));
if (!externalContactChatList.isSuccess()) {
return list;
}
WorkWechatExternalContactChatListResponseDTO result = externalContactChatList.getResult();
List<WorkWechatExternalContactChatDTO> groupChatList = result.getGroupChatList();
list.addAll(groupChatList);
if (groupChatList.size() < 1000) {
return list;
} else {
return getCustomerBase(result.getNextCursor(), list, merchantId, userIds);
}
}
public List<CustomerBaseInfoResponse> findCustBaseByContion(CustBaseSearchRequest custBaseSearchRequest) {
return customerBaseMapper.findCustBaseByContion(custBaseSearchRequest);
}
/**
* 查询当前商户的所有客户群
*
* @param merchantId
* @return
*/
public List<CustomerBaseInfoResponse> findCusBaseByMerchantId(Integer merchantId) {
return customerBaseMapper.findCusBaseByMerchantId(merchantId);
}
/**
* staffIds查询当前商户的所有客户群
*
* @param staffIds 员工id
* @param merchantId
* @return
*/
public List<CustomerBaseInfoResponse> findCusBaseByStaffIds(List<Integer> staffIds, Integer merchantId) {
if (merchantId == null) {
return new ArrayList<>();
}
if (staffIds == null || staffIds.isEmpty()) {
return customerBaseMapper.findCusBaseByMerchantId(merchantId);
}
return customerBaseMapper.findCusBaseByStaffIds(staffIds, merchantId);
}
/**
* 根据客户群表主键查询群名称、群成员数量
*
* @param ids
* @param merchantId
* @return
*/
public Map<Integer, MassChatItemEntity> getMassChatItemEntityInfoByIds(List<Integer> ids, Integer merchantId) {
if (ids == null) {
return null;
}
List<MassChatItemEntity> list = customerBaseMapper.getMassChatItemEntityInfoByIds(ids);
if (list == null || list.isEmpty()) {
return null;
}
list.forEach(index -> {
String groupName = index.getGroupName() != null ? EmojiUtils.parseToUnicode(index.getGroupName()) : null;
index.setGroupName(groupName);
});
return list.stream().collect(Collectors.toMap(MassChatItemEntity::getStaffId, Function.identity(), (item1, item2) -> item1));
}
/**
* 客户群的跟进员工列表
*
* @param request
* @return
*/
public Page<CustomerBaseStaffListResponse> customerBaseStaffList(RpcPagination<CustBaseCustSearchRequest> request) {
//分页条件
PageHelper.startPage(request.getPageNum(), request.getPageSize());
CustBaseCustSearchRequest condition = request.getCondition();
log.info("客户群员工列表分页条件:{}", condition);
Date endTime = condition.getEndTime();
if (endTime != null) {
condition.setEndTime(DateUtils.addDays(endTime, 1));
}
//列表数据
Page<CustomerBaseStaffListResponse> list = customerBaseMapper.getFollowStaffByPage(condition);
if (!CollectionUtils.isEmpty(list)) {
list.stream().forEach(cust -> {
//emoji转化
cust.setStaffName(cust.getStaffName() != null ? EmojiUtils.parseToUnicode(cust.getStaffName()) : null);
cust.setGroupNickName(cust.getGroupNickName() != null ? EmojiUtils.parseToUnicode(cust.getGroupNickName()) : null);
});
}
return list;
}
/**
* 客户群的潜在客户列表
*
* @param request
* @return
*/
public Page<CustomerBaseCustListResponse> customerBasePotentialCustList(RpcPagination<CustBaseCustSearchRequest> request) {
//设置分页数据
PageHelper.startPage(request.getPageNum(), request.getPageSize());
CustBaseCustSearchRequest condition = request.getCondition();
Date endTime = condition.getEndTime();
if (null != endTime) {
condition.setEndTime(DateUtils.addDays(endTime, 1));
}
//客户数据
Page<CustomerBaseCustListResponse> list = customerBaseMapper.getGroupCustomerByPage(condition);
Page<CustomerBaseCustListResponse> collect1 = new Page<>();
collect1.setPageNum(request.getPageNum());
collect1.setPageSize(request.getPageSize());
if (!CollectionUtils.isEmpty(list)) {
list.stream().forEach(cust -> {
//emoji转化
cust.setCustomerName(cust.getCustomerName() != null ? EmojiUtils.parseToUnicode(cust.getCustomerName()) : null);
cust.setGroupNickName(cust.getGroupNickName() != null ? EmojiUtils.parseToUnicode(cust.getGroupNickName()) : null);
});
//TODO 查出当前群的所有客户 ,过滤没有跟进人的客户,
List<String> collect = list.stream().map(CustomerBaseCustListResponse::getId).collect(Collectors.toList());
Map<String, CustomerFollowStaffResponse> customerStaffByOneId = customerService.getCustomerStaffByOneId(collect, condition.getMerchantId());
if (!CollectionUtils.isEmpty(customerStaffByOneId)) {
List<CustomerBaseCustListResponse> collect2 = list.stream().filter(index -> !customerStaffByOneId.containsKey(index.getId())).collect(Collectors.toList());
collect1.addAll(collect2);
}
}
return collect1;
}
/**
* 客户群的退群客户列表
*
* @param request
* @return
*/
public Page<CustomerBaseCustListResponse> customerBaseQuitCustList(RpcPagination<CustBaseCustSearchRequest> request) {
//设置分页数据
PageHelper.startPage(request.getPageNum(), request.getPageSize());
CustBaseCustSearchRequest condition = request.getCondition();
Date endTime = condition.getEndTime();
if (null != endTime) {
condition.setEndTime(DateUtils.addDays(endTime, 1));
}
//客户数据
Page<CustomerBaseCustListResponse> list = customerBaseMapper.getQuitCustomerByPage(condition);
if (!CollectionUtils.isEmpty(list)) {
list.stream().forEach(cust -> {
//emoji转化
cust.setCustomerName(cust.getCustomerName() != null ? EmojiUtils.parseToUnicode(cust.getCustomerName()) : null);
cust.setGroupNickName(cust.getGroupNickName() != null ? EmojiUtils.parseToUnicode(cust.getGroupNickName()) : null);
});
}
return list;
}
/**
* 群全部客户导出
*
* @param request
* @return
*/
public String baseCustomerExport(CustBaseCustSearchRequest request) {
//获取群详情
CustomerBaseInfoResponse customerBase = getCustomerBase(request);
//获取群客户列表数据
RpcPagination<CustBaseCustSearchRequest> pagination = new RpcPagination<>();
pagination.setPageSize(999);
pagination.setPageNum(1);
pagination.setCondition(request);
Page<CustomerBaseCustListResponse> groupCustomerByPage = customerBaseCustList(pagination);
log.info("群全部客户导出列表数据:{}", JSONArray.toJSONString(groupCustomerByPage));
List<CustomerBaseCustListResponse> result = groupCustomerByPage.getResult();
//导出模板数据组装
List<BaseCustomerExportModel> exportList = new ArrayList<>();
BaseCustomerExportModel baseCustomerExportModel;
if (!CollectionUtils.isEmpty(result)) {
for (CustomerBaseCustListResponse index : result) {
baseCustomerExportModel = new BaseCustomerExportModel();
//常量数据组装
buildExportModel(baseCustomerExportModel, index, customerBase);
exportList.add(baseCustomerExportModel);
}
}
//导出到广联服务器
String url = exportUpload(exportList, request.getGroupName(), Constants.CUSTOMER_BASE_CONSTANTS.BASE_CUSTOMER, Constants.CUSTOMER_BASE_CONSTANTS.MEMBER_CUSTOMER);
return url;
}
/**
* 群员工导出
*
* @param request
* @return
*/
public String baseStaffExport(CustBaseCustSearchRequest request) {
//获取群详情
CustomerBaseInfoResponse customerBase = getCustomerBase(request);
//获取群客户列表数据
RpcPagination<CustBaseCustSearchRequest> pagination = new RpcPagination<>();
pagination.setPageSize(999);
pagination.setPageNum(1);
pagination.setCondition(request);
Page<CustomerBaseStaffListResponse> staffListResponses = customerBaseStaffList(pagination);
List<CustomerBaseStaffListResponse> result = staffListResponses.getResult();
log.info("群员工导出列表数据:{}", JSONArray.toJSONString(staffListResponses));
//导出模板数据组装
List<BaseStaffExportModel> exportList = new ArrayList<>();
BaseStaffExportModel baseStaffExportModel;
CustomerBaseCustListResponse baseCustListResponse;
BaseCustomerExportModel baseCustomerExportModel;
if (!CollectionUtils.isEmpty(result)) {
for (CustomerBaseStaffListResponse index : result) {
baseStaffExportModel = new BaseStaffExportModel();
baseCustomerExportModel = new BaseCustomerExportModel();
baseCustListResponse = new CustomerBaseCustListResponse();
BeanUtils.copyProperties(index, baseCustListResponse);
baseCustListResponse.setCustomerPhone(index.getStaffPhone());
baseCustListResponse.setCustomerSex(index.getStaffSex());
baseCustListResponse.setCustomerName(index.getStaffName());
//常量数据组装
buildExportModel(baseCustomerExportModel, baseCustListResponse, customerBase);
//客户模型类转员工模型类
BeanUtils.copyProperties(baseCustomerExportModel, baseStaffExportModel);
baseStaffExportModel.setStaffName(index.getStaffName());
exportList.add(baseStaffExportModel);
}
}
//导出到广联服务器
String url = exportUpload(exportList, request.getGroupName(), Constants.CUSTOMER_BASE_CONSTANTS.BASE_STAFF, Constants.CUSTOMER_BASE_CONSTANTS.MEMBER_STAFF);
return url;
}
/**
* 群潜在客户导出
*
* @param request
* @return
*/
public String basePotentialExport(CustBaseCustSearchRequest request) {
CustomerBaseInfoResponse customerBase = getCustomerBase(request);
//获取群客户列表数据
RpcPagination<CustBaseCustSearchRequest> pagination = new RpcPagination<>();
pagination.setPageSize(999);
pagination.setPageNum(1);
pagination.setCondition(request);
Page<CustomerBaseCustListResponse> groupCustomerByPage = customerBasePotentialCustList(pagination);
log.info("群员工导出列表数据:{}", JSONArray.toJSONString(groupCustomerByPage));
List<CustomerBaseCustListResponse> result = groupCustomerByPage.getResult();
//导出模板数据组装
List<BaseCustomerExportModel> exportList = new ArrayList<>();
BaseCustomerExportModel baseCustomerExportModel;
if (!CollectionUtils.isEmpty(result)) {
for (CustomerBaseCustListResponse index : result) {
baseCustomerExportModel = new BaseCustomerExportModel();
//常量数据组装
buildExportModel(baseCustomerExportModel, index, customerBase);
exportList.add(baseCustomerExportModel);
}
}
//导出到广联服务器
String url = exportUpload(exportList, request.getGroupName(), Constants.CUSTOMER_BASE_CONSTANTS.BASE_POTENTIAL_CUSTOMER, Constants.CUSTOMER_BASE_CONSTANTS.MEMBER_CUSTOMER);
return url;
}
/**
* 群退群客户导出
*
* @param request
* @return
*/
public String baseQuitExport(CustBaseCustSearchRequest request) {
CustomerBaseInfoResponse customerBase = getCustomerBase(request);
//获取群客户列表数据
RpcPagination<CustBaseCustSearchRequest> pagination = new RpcPagination<>();
pagination.setPageSize(999);
pagination.setPageNum(1);
pagination.setCondition(request);
Page<CustomerBaseCustListResponse> groupCustomerByPage = customerBaseQuitCustList(pagination);
log.info("群员工导出列表数据:{}", JSONArray.toJSONString(groupCustomerByPage));
List<CustomerBaseCustListResponse> result = groupCustomerByPage.getResult();
//导出模板数据组装
List<BaseCustomerExportModel> exportList = new ArrayList<>();
BaseCustomerExportModel baseCustomerExportModel;
if (!CollectionUtils.isEmpty(result)) {
for (CustomerBaseCustListResponse index : result) {
baseCustomerExportModel = new BaseCustomerExportModel();
//常量数据组装
buildExportModel(baseCustomerExportModel, index, customerBase);
exportList.add(baseCustomerExportModel);
}
}
//导出到广联服务器
String url = exportUpload(exportList, request.getGroupName(), Constants.CUSTOMER_BASE_CONSTANTS.BASE_QUIT_CUSTOMER, Constants.CUSTOMER_BASE_CONSTANTS.MEMBER_CUSTOMER);
return url;
}
/**
* 文件名组装和导出文件
*
* @param exportList
* @param groupName
* @param type 列表类型
* @return
*/
public String exportUpload(List<? extends Object> exportList, String groupName, String listName, Integer type) {
StringBuilder stringBuilder = new StringBuilder();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String date = format.format(new Date());
StringBuilder append = stringBuilder.append(StringUtils.isEmpty(groupName) ? "群聊默认" : groupName).append("-").append(listName).append("-").append(date);
String fileName = append.toString();
String url = null;
log.info("客户群客户列表导出数据: {}", JSONArray.toJSONString(exportList));
if (type == Constants.CUSTOMER_BASE_CONSTANTS.MEMBER_CUSTOMER) {
url = ExcelExportUtils.excelExport(fileName, exportList, BaseCustomerExportModel.class, null);
} else {
url = ExcelExportUtils.excelExport(fileName, exportList, BaseStaffExportModel.class, null);
}
return url;
}
/**
* 导出模板数据组装
*
* @param baseCustomerExportModel 导出模板信息
* @param index 群客户信息
* @param infoResponse 群详情信息
* @return 导出模板信息
*/
private BaseCustomerExportModel buildExportModel(BaseCustomerExportModel baseCustomerExportModel,
CustomerBaseCustListResponse index,
CustomerBaseInfoResponse infoResponse) {
//客户信息
BeanUtils.copyProperties(index, baseCustomerExportModel);
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Long time = null != index.getJoinTime() ? index.getJoinTime().getTime() : null;
String joinDate = null;
if (null != time) {
joinDate = format.format(time);
}
baseCustomerExportModel.setJoinTime(joinDate);
//客户性别
if (null != index.getCustomerSex()) {
switch (index.getCustomerSex()) {
case Constants.CUSTOMER_SEX_MAN:
baseCustomerExportModel.setCustomerSex(Constants.SEX_MAN);
break;
case Constants.CUSTOMER_SEX_WOMEN:
baseCustomerExportModel.setCustomerSex(Constants.SEX_WOMEN);
break;
default:
baseCustomerExportModel.setCustomerSex(Constants.SEX_UNKNOWN);
break;
}
}
//客户入群方式
if (null != index.getJoinScene()) {
switch (index.getJoinScene()) {
case Constants.CUSTOMER_BASE_CONSTANTS.JOIN_SCENE_INVITATION:
baseCustomerExportModel.setJoinScene(Constants.CUSTOMER_BASE_CONSTANTS.JOIN_BY_INVITATION);
break;
case Constants.CUSTOMER_BASE_CONSTANTS.JOIN_SCENE_LINK:
baseCustomerExportModel.setJoinScene(Constants.CUSTOMER_BASE_CONSTANTS.JOIN_BY_LINK);
break;
case Constants.CUSTOMER_BASE_CONSTANTS.JOIN_SCENE_QRCODE:
baseCustomerExportModel.setJoinScene(Constants.CUSTOMER_BASE_CONSTANTS.JOIN_BY_QRCODE);
break;
default:
baseCustomerExportModel.setJoinScene(Constants.SEX_UNKNOWN);
break;
}
}
//用户类型
if (null != index.getType()) {
switch (index.getJoinScene()) {
case Constants.USER_TYPE_WECHAT:
baseCustomerExportModel.setType(Constants.USER_TYPE_WECHAT_STRING);
break;
case Constants.USER_TYPE_ENTERPRISE:
baseCustomerExportModel.setType(Constants.USER_TYPE_ENTERPRISE_STRING);
break;
default:
baseCustomerExportModel.setType(null);
break;
}
}
//群信息
//群管理员
baseCustomerExportModel.setGroupAdmin(infoResponse.getGroupAdmin());
//群聊名
baseCustomerExportModel.setGroupName(infoResponse.getGroupName());
//群主手机
baseCustomerExportModel.setGroupHostPhone(infoResponse.getGroupHostPhone());
//群主名
baseCustomerExportModel.setGroupHostName(infoResponse.getGroupHostName());
return baseCustomerExportModel;
}
/**
* 获取群详情
*
* @param request
* @return
*/
public CustomerBaseInfoResponse getCustomerBase(CustBaseCustSearchRequest request) {
//获取群详情
List<Integer> authorizeMerchants = entmicroStaffService.findAuthorizeMerchantNo(entmicroStaffService.findSupMerchantNo(request.getMerchantId()));
log.info("授权商户{}", authorizeMerchants);
CustomerBaseInfoResponse infoResponse = customerBaseMapper.getCustomerBaseInfo(request.getId(), authorizeMerchants);
if (!StringUtils.isEmpty(infoResponse)) {
//emoji转化
infoResponse.setGroupHostDepart(infoResponse.getGroupHostDepart() != null ? EmojiUtils.parseToUnicode(infoResponse.getGroupHostDepart()) : null);
infoResponse.setGroupAdmin(infoResponse.getGroupAdmin() != null ? EmojiUtils.parseToUnicode(infoResponse.getGroupAdmin()) : null);
infoResponse.setGroupHostName(infoResponse.getGroupHostName() != null ? EmojiUtils.parseToUnicode(infoResponse.getGroupHostName()) : null);
infoResponse.setGroupName(infoResponse.getGroupName() != null ? EmojiUtils.parseToUnicode(infoResponse.getGroupName()) : null);
}
return infoResponse;
}
/**
* 客群列表导出
*
* @param request
* @return
*/
public String customerBaseListExport(CustomerBaseSearchRequest request) {
//获取群列表
RpcPagination<CustomerBaseSearchRequest> pagination = new RpcPagination<>();
pagination.setPageSize(10000);
pagination.setPageNum(1);
pagination.setCondition(request);
Page<CustomerBaseListResponse> page = customerBasePageQuery(pagination);
log.info("客群列表导出数据: {}", JSONArray.toJSONString(page));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
List<CustomerBaseListResponse> result = page.getResult();
CustomerBaseListExportModel exportModel;
List<CustomerBaseListExportModel> exportModelList = new ArrayList<>();
if (!CollectionUtils.isEmpty(result)) {
for (CustomerBaseListResponse index : result) {
exportModel = new CustomerBaseListExportModel();
BeanUtils.copyProperties(index, exportModel);
Long time = null != index.getAddTime() ? index.getAddTime().getTime() : null;
String format = null != time ? dateFormat.format(time) : null;
exportModel.setAddTime(format);
if (null != index.getCreationMethod()) {
exportModel.setCreationMethod(index.getCreationMethod().equals(Constants.CUSTOMER_BASE_CONSTANTS.SCRM_CUSTOMER_BASE) ? "手动拉群" : "一客一群");
}
exportModelList.add(exportModel);
}
}
log.info("客群列表组装excel数据: {}", JSONArray.toJSONString(exportModelList));
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String date = format.format(new Date());
String url = ExcelExportUtils.excelExport("客户群" + "-" + date, exportModelList, CustomerBaseListExportModel.class, null);
return url;
}
/**
* 客户群的客户列表
*/
public List<CustomerBaseCustListResponse> customerBaseCustList(CustBaseCustSearchRequest custBaseCustSearchRequest) {
Date endTime = custBaseCustSearchRequest.getEndTime();
if (null != endTime) {
custBaseCustSearchRequest.setEndTime(DateUtils.addDays(endTime, 1));
}
//客户数据
List<CustomerBaseCustListResponse> customerBaseCustListResponses = customerBaseMapper.getCustomerByGroup(custBaseCustSearchRequest);
if (!CollectionUtils.isEmpty(customerBaseCustListResponses)) {
customerBaseCustListResponses.stream().forEach(index -> {
//emoji转化
index.setCustomerName(index.getCustomerName() != null ? EmojiUtils.parseToUnicode(index.getCustomerName()) : null);
index.setInvitorName(index.getInvitorName() != null ? EmojiUtils.parseToUnicode(index.getInvitorName()) : null);
index.setGroupNickName(index.getGroupNickName() != null ? EmojiUtils.parseToUnicode(index.getGroupNickName()) : null);
index.setChatName(!StringUtils.isEmpty(index.getChatName()) ? EmojiUtils.parseToUnicode(index.getChatName()) : "群聊(默认)");
});
}
return customerBaseCustListResponses;
}
/**
* 客户群的客户列表导出
*/
public String customerBaseCustListExport(CustBaseCustSearchRequest custBaseCustSearchRequest) {
List<CustomerBaseCustListExportModel> customerBaseCustListExportModels = new ArrayList<>();
RpcPagination<CustBaseCustSearchRequest> rpcPagination = new RpcPagination<>();
rpcPagination.setCondition(custBaseCustSearchRequest);
rpcPagination.setPages(999);
rpcPagination.setPageNum(1);
//群客户数据
List<CustomerBaseCustListResponse> customerBaseCustListResponses = customerBaseCustList(rpcPagination);
if (!CollectionUtils.isEmpty(customerBaseCustListResponses)) {
List<String> collect = customerBaseCustListResponses.stream().map(CustomerBaseCustListResponse::getLord).collect(Collectors.toList());
Integer authorizeEnt = entmicroStaffService.findSupMerchantNo(custBaseCustSearchRequest.getMerchantId());
Map<String, EntmicroStaffResponse> idsByUserIds = entmicroStaffService.getIdsByUserIds(collect, authorizeEnt);
customerBaseCustListExportModels = customerBaseCustListResponses.stream().map(index -> {
CustomerBaseCustListExportModel customerBaseCustListExportModel = new CustomerBaseCustListExportModel();
BeanUtils.copyProperties(index, customerBaseCustListExportModel);
if (!CollectionUtils.isEmpty(idsByUserIds) && null != idsByUserIds.get(index.getLord())) {
customerBaseCustListExportModel.setLordName(idsByUserIds.get(index.getLord()).getStaffName());
}
customerBaseCustListExportModel.setJoinTime(index.getJoinTime() != null ? DateUtils.format(index.getJoinTime()) : null);
return customerBaseCustListExportModel;
}).collect(Collectors.toList());
}
String fileUrl = ExcelExportUtils.excelExport("客户群客户列表" + System.currentTimeMillis(), customerBaseCustListExportModels, CustomerBaseCustListExportModel.class, null);
return fileUrl;
}
/**
* 客户群的客户列表 企微端
*/
public List<CustomerBaseCustListResponse> customerBaseCustListToC(CustBaseCustSearchRequest custBaseCustSearchRequest) {
//chatId查询群信息
if (com.glsx.plat.common.utils.StringUtils.isNotEmpty(custBaseCustSearchRequest.getChatId())) {
log.info("企微端客户群的客户列表入参: {}", JSONArray.toJSONString(custBaseCustSearchRequest));
CustomerBaseInfoResponse byChatId = customerBaseMapper.findByChatId(custBaseCustSearchRequest.getChatId());
if (null == byChatId) {
log.info("企微端客户群的客户列表chatId:{}本地数据为空", JSONArray.toJSONString(custBaseCustSearchRequest));
return null;
}
custBaseCustSearchRequest.setId(byChatId.getId());
}
//uuid获取员工信息
StaffRequestDTO staffRequestDTO = new StaffRequestDTO();
staffRequestDTO.setUserUuid(custBaseCustSearchRequest.getUuid());
EntmicroStaffResponse staffDetail = entmicroStaffService.findStaffDetail(staffRequestDTO);
//客户数据
List<CustomerBaseCustListResponse> customerBaseCustListResponses = customerBaseCustList(custBaseCustSearchRequest);
if (CollectionUtils.isEmpty(customerBaseCustListResponses)) {
log.info("企微端客户数据为空");
return customerBaseCustListResponses;
}
if (null != staffDetail) {
//查询当前员工的客户
List<EntmicroCustomerFollow> byStaffId = customerService.findByStaffId(staffDetail.getId());
if (!CollectionUtils.isEmpty(byStaffId)) {
//比对我的客户
for (CustomerBaseCustListResponse customer : customerBaseCustListResponses) {
for (EntmicroCustomerFollow follow : byStaffId) {
if (follow.getCustomerId().equals(customer.getCustomerId())) {
customer.setIsMyCustomer(Constants.CUSTOMER_BASE_CONSTANTS.IS_MY_CUSTOMER);
break;
}
}
}
}
} else {
log.info("请求企微端群成员列表的员工本地数据为空, uuid: {}", custBaseCustSearchRequest.getUuid());
}
return customerBaseCustListResponses;
}
/**
* 客户群员工列表
*
* @param custBaseCustSearchRequest
* @return
*/
public List<CustomerBaseStaffListResponse> getBaseFollowStaffList(CustBaseCustSearchRequest custBaseCustSearchRequest) {
log.info("客户群员工列表入参:{}", JSONArray.toJSONString(custBaseCustSearchRequest));
CustomerBaseInfoResponse byChatId = customerBaseMapper.findByChatId(custBaseCustSearchRequest.getChatId());
if (null == byChatId) {
log.info("客户群员工列表入参chatId:{}本地数据为空", JSONArray.toJSONString(custBaseCustSearchRequest));
return null;
}
custBaseCustSearchRequest.setId(byChatId.getId());
List<CustomerBaseStaffListResponse> baseFollowStaffList = customerBaseMapper.getBaseFollowStaffList(custBaseCustSearchRequest);
log.info("客户群员工列表结果:{}", JSONArray.toJSONString(baseFollowStaffList));
if (CollectionUtils.isEmpty(baseFollowStaffList)) {
log.info("客户群员工列表数据为空");
return baseFollowStaffList;
}
CustomerBaseStaffListResponse index;
for (int i = 0; i < baseFollowStaffList.size(); i++) {
index = baseFollowStaffList.get(i);
//emoji转化
index.setGroupNickName(com.glsx.plat.common.utils.StringUtils.isNotEmpty(index.getGroupNickName()) ? EmojiUtils.parseToUnicode(index.getGroupNickName()) : "");
//筛选群主 0群主
if (index.getIsLord().equals(Constants.CUSTOMER_BASE_CONSTANTS.IS_LORD)) {
//调换元素到首位
Collections.swap(baseFollowStaffList, i, 0);
break;
}
}
return baseFollowStaffList;
}
/**
* 获取当前客户群的统计详情
*
* @return
*/
public CustomerBaseStaticsRpcResponse getBaseDetailStatics(CustBaseCustSearchRequest custBaseCustSearchRequest) {
CustomerBaseStaticsRpcResponse response = new CustomerBaseStaticsRpcResponse();
CustomerBaseInfoResponse byChatId = customerBaseMapper.findByChatId(custBaseCustSearchRequest.getChatId());
if (null == byChatId) {
log.info("客户群chatId:{}本地数据为空", JSONArray.toJSONString(custBaseCustSearchRequest));
return null;
}
custBaseCustSearchRequest.setId(byChatId.getId());
//查询今天入群总数
List<GetCustomerTotalResponse> todayCustomer = customerBaseMapper.getTodayCustomer(custBaseCustSearchRequest.getMerchantId());
Optional<GetCustomerTotalResponse> any = todayCustomer.stream().filter(index -> custBaseCustSearchRequest.getChatId().equals(index.getChatId())).findAny();
GetCustomerTotalResponse getCustomerTotalResponse;
if (any.isPresent()) {
getCustomerTotalResponse = any.get();
response.setAddNum(getCustomerTotalResponse.getTotal());
} else {
response.setAddNum(0);
}
//今日退群记录
Set<StatisticsCustomerBaseInfoResponse> todayRemoveCustomerList = customerBaseMapper.getTodayRemoveList(Arrays.asList(custBaseCustSearchRequest.getId()));
//今日入群记录
Set<StatisticsCustomerBaseInfoResponse> todayAddCustomerList = customerBaseMapper.getTodayAddList(Arrays.asList(custBaseCustSearchRequest.getId()));
//今天退群列表
Set<StatisticsCustomerBaseInfoResponse> removeTotal = new HashSet<>();
if (!CollectionUtils.isEmpty(todayRemoveCustomerList)) {
Set<StatisticsCustomerBaseInfoResponse> removeList;
if (CollectionUtils.isEmpty(todayAddCustomerList)) {
removeList = todayRemoveCustomerList;
} else {
//重写了HashCode和equals取出差异化数据
removeList = todayRemoveCustomerList.stream().filter(index -> !todayAddCustomerList.contains(index)).collect(Collectors.toSet());
}
if (!CollectionUtils.isEmpty(removeList)) {
for (StatisticsCustomerBaseInfoResponse ind : removeList) {
if (byChatId.getId().equals(ind.getCustomerBaseId())) {
removeTotal.add(ind);
}
}
}
}
response.setRemoveNum(removeTotal.size());
//全部成员数
List<GetCustomerTotalResponse> allMembers = customerBaseMapper.getAllMembers(Arrays.asList(byChatId.getId()));
Optional<GetCustomerTotalResponse> allTotal = allMembers.stream().filter(index -> custBaseCustSearchRequest.getChatId().equals(index.getChatId())).findAny();
if (allTotal.isPresent()) {
GetCustomerTotalResponse getCustomerTotalResponse1 = allTotal.get();
response.setTotal(getCustomerTotalResponse1.getTotal());
} else {
response.setTotal(0);
}
return response;
}
/**
* oneId批量获取群客户列表标签
*
* @param customerBaseCustListResponses
* @param custBaseCustSearchRequest
* @return
*/
public List<CustomerBaseCustListResponse> getBatchLabelByOneId(List<CustomerBaseCustListResponse> customerBaseCustListResponses,
CustBaseCustSearchRequest custBaseCustSearchRequest) {
//TODO 批量获取客户标签接口
//获取staffId
log.info("oneId批量获取群客户列表标签入参, oneId: {}, request:{}", customerBaseCustListResponses, JSONArray.toJSONString(custBaseCustSearchRequest));
StaffRequestDTO staffRequestDTO = new StaffRequestDTO();
staffRequestDTO.setUserUuid(custBaseCustSearchRequest.getUuid());
EntmicroStaffResponse staffDetail = entmicroStaffService.findStaffDetail(staffRequestDTO);
log.info("oneId批量获取群客户列表标签员工数据: {}", JSONArray.toJSONString(staffDetail));
List<Integer> datalist = custBaseCustSearchRequest.getDatalist();
String merchantIds = com.glsx.plat.common.utils.StringUtils.join(datalist, ",");
//轮询获取标签
log.info("开始批量请求标签===");
customerBaseCustListResponses.forEach(customer -> {
if (!StringUtils.isEmpty(customer.getId())) {
CustDetailRopRes labelVehicleInfo = ropCommonServie.getLabelVehicleInfo(customer.getId(), merchantIds, custBaseCustSearchRequest.getMerchantId(), null != staffDetail ? staffDetail.getId() : null);
customer.setLabels(labelVehicleInfo.getLabelInfoList());
}
});
log.info("批量请求标签结束===");
return customerBaseCustListResponses;
}
public List<CustomerBaseInfoResponse> findCusBaseByChatId(List<String> request) {
Example example = new Example(CustomerBase.class);
example.createCriteria().andIn("chatId", request);
return customerBaseMapper.selectByExample(example).stream().map(index -> {
CustomerBaseInfoResponse customerBaseInfoResponse = new CustomerBaseInfoResponse();
BeanUtils.copyProperties(index, customerBaseInfoResponse);
return customerBaseInfoResponse;
}).collect(Collectors.toList());
}
public Boolean editCustomerBaseTag(CustomerBaseEditRequest request) {
CustomerBase exist = customerBaseMapper.selectByPrimaryKey(request.getId());
RpcAssert.assertNotNull(exist, DefaultErrorEnum.DATA_NOT_EXIST);
log.info("编辑客户群标签 request:{}", JSON.toJSONString(request));
List<UserLabelDTO.UserLabelRet.UserLabelUnit> allTags = getCustomerBaseSyncTag(request.getMerchantId(), exist.getChatId(), 1);
log.info("编辑客户群标签 allTags:{}", JSON.toJSONString(allTags));
// 只能操作自定标签
ArrayList<Integer> normalTags = Lists.newArrayList();
if (!CollectionUtils.isEmpty(allTags)) {
allTags.forEach(p -> p.getLabelInfoList().forEach(l -> normalTags.add(l.getLabelId())));
}
List<Integer> newNormalTags = request.getTagIds();
List<Integer> addTags = newNormalTags.stream().filter(p -> !normalTags.contains(p)).collect(Collectors.toList());
List<Integer> delTags = normalTags.stream().filter(p -> !newNormalTags.contains(p)).collect(Collectors.toList());
return syncChatTag(request.getMerchantId(), exist.getChatId(), addTags, delTags);
}
public int countCustomerBaseTag(int custId) {
CustIdRequest req = new CustIdRequest();
req.setId(custId);
List<CustomerBaseTagResponse> res = getCustomerBaseTag(req);
if (CollectionUtils.isEmpty(res)) {
return 0;
}
return res.stream()
.filter(p -> !CollectionUtils.isEmpty(p.getLabelInfoList()))
.mapToInt(p -> p.getLabelInfoList().size()).sum();
}
/**
* 获取群标签列表
*/
public List<CustomerBaseTagResponse> getCustomerBaseTag(CustIdRequest request) {
CustomerBase exist = customerBaseMapper.selectByPrimaryKey(request.getId());
RpcAssert.assertNotNull(exist, DefaultErrorEnum.DATA_NOT_EXIST);
log.info("获取群标签列表 request:{}", request);
List<UserLabelDTO.UserLabelRet.UserLabelUnit> res = getCustomerBaseSyncTag(request.getMerchantId(), exist.getChatId());
log.info("获取群标签列表 res:{}", res);
if (CollectionUtils.isEmpty(res)) {
return null;
}
return res.stream().map(p -> {
CustomerBaseTagResponse item = new CustomerBaseTagResponse();
item.setLabelGroupInfo(BeanConverUtil.conver(p.getLabelGroupInfo(), CustomerBaseTagResponse.LabelGroupInfoDTO.class));
item.setLabelInfoList(BeanConverUtil.converList(p.getLabelInfoList(), CustomerBaseTagResponse.LabelInfoDTO.class));
return item;
}).collect(Collectors.toList());
}
private void parseChatName(CustomerBaseListResponse re) {
//空值默认群名称
re.setCustGroupName(StringUtils.isEmpty(re.getCustGroupName()) ? "群聊(默认)" : re.getCustGroupName());
//emoji转化
re.setGroupHostName(!StringUtils.isEmpty(re.getGroupHostName()) ? EmojiUtils.parseToUnicode(re.getGroupHostName()) : null);
re.setGroupAdminName(!StringUtils.isEmpty(re.getGroupAdminName()) ? EmojiUtils.parseToUnicode(re.getGroupAdminName()) : null);
re.setCustGroupName(!StringUtils.isEmpty(re.getCustGroupName()) ? EmojiUtils.parseToUnicode(re.getCustGroupName()) : null);
}
public List<CustomerBaseListResponse> getGroupOneByCustomer(CustGroupOneSearchRequest request) {
//查询客户群列表
List<CustomerBaseListResponse> res = customerBaseMapper.findGroupOneByFirstCustomer(request);
if (!CollectionUtils.isEmpty(res)) {
res.forEach(this::parseChatName);
}
return res;
}
/**
* 根据chatId查询客户数
*
* @param chatIds
* @return
*/
public Map<String, List<CustomerBaseInfoResponse>> findCustomerByChatIds(List<String> chatIds) {
List<CustomerBaseInfoResponse> customerBaseInfoResponses = customerBaseMapper.getCustomerByChatIds(chatIds);
return customerBaseInfoResponses.stream().collect(Collectors.groupingBy(CustomerBaseInfoResponse::getChatId));
}
/**
* 获取客户群基础列表
*
* @param request 请求参数
* @return 客户群信息
*/
public List<CustomerBaseInfoResponse> getSimpleCustomerBaseList(CustBaseSimpleSearchRequest request) {
List<Integer> idList = request.getIdList();
List<Integer> merchantIdList = request.getMerchantIdList();
Example example = new Example(CustomerBase.class);
Example.Criteria criteria = example.createCriteria().andEqualTo("delFlag", Constants.NORMAL_FLAG);
if (!CollectionUtils.isEmpty(idList)) {
criteria.andIn("id", idList);
}
Set<Integer> merchantIdSet = new HashSet<>();
if (!CollectionUtils.isEmpty(merchantIdList)) {
for (Integer merchantId : merchantIdList) {
Integer supMerchantNo = entmicroStaffService.findSupMerchantNo(merchantId);
log.info("获取客户群基础列表-授权商户 supMerchantNo:{}",supMerchantNo);
merchantIdSet.add(supMerchantNo);
}
criteria.andIn("merchantid", merchantIdSet);
}
List<CustomerBase> customerBaseList = customerBaseMapper.selectByExample(example);
log.info("CustomerBaseService#getSimpleCustomerBaseList result:{}", JSON.toJSONString(customerBaseList));
if (CollectionUtils.isEmpty(customerBaseList)) return new ArrayList<>();
return customerBaseList.stream().map(index -> {
CustomerBaseInfoResponse customerBaseInfoResponse = new CustomerBaseInfoResponse();
BeanUtils.copyProperties(index, customerBaseInfoResponse);
customerBaseInfoResponse.setGroupName(index.getChatName());
return customerBaseInfoResponse;
}).collect(Collectors.toList());
}
}