Customer.php
69 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
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
<?php
namespace app\admin\controller\antis\customer;
use addons\antis\model\AdminConfig;
use addons\antis\model\BusinessStatus;
use addons\antis\model\ContactsOther;
use addons\antis\model\FormField;
use addons\antis\model\Remind;
use addons\antis\model\Seastype;
use addons\antis\model\WordTemplate;
use app\admin\controller\antis\Base;
use addons\antis\model\CustomerOther;
use addons\antis\model\Form;
use addons\antis\model\Record;
use addons\antis\model\Staff;
use addons\antis\model\Consume;
use addons\antis\model\Contacts;
use addons\antis\model\Contract;
use addons\antis\model\Receivables;
use addons\antis\model\ReceivablesPlan;
use addons\antis\model\CustomerFile;
use addons\antis\model\StaffSignIn;
use addons\antis\model\File;
use app\admin\model\fastflow\bill\Czgprz;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use addons\antis\model\Business;
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\Settings;
use think\Db;
use think\Exception;
/**
* 客户管理
* 操作文档:https://doc.fastadmin.net/antis
* 软件介绍:https://www.fastadmin.net/store/antis.html
* 售后微信:qingdong_crm
*/
class Customer extends Base
{
protected $noNeedLogin = ['getContacts','index2','save_customer_quotation_link'];
protected $relationSearch = true;
protected $searchFields = 'id,name';
/**
* @var \addons\antis\model\Customer
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \addons\antis\model\Customer;
}
/**
* 查看
*/
public function index()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
if ($this->request->request('keyField')) {
return $this->selectpage();
}
//0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
$type = input('type', 0);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$staff = Staff::info();
$staff_id = $staff->id;
switch ($type) {
case 1://我负责
$wheres['owner_staff_id'] = $staff_id;
break;
case 2://下属负责
$wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
break;
case 3:
$start = date('Y-m-d 00:00:00');
$end = date('Y-m-d 23:59:59');
$record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
$relationId = [];
foreach ($record as $k => $v) {
$whereRe['id'] = array('gt', $v['id']);
$whereRe['relation_id'] = $v['relation_id'];
$recordData = Record::where($whereRe)->count();
if ($recordData == 0) {
$relationId[] = $v['relation_id'];
}
}
$wheres['id'] = array('in', $relationId);
$staff = Staff::info();
$wheres['owner_staff_id'] = $staff->id;
break;
case 4:
$start = date('Y-m-d 00:00:00');
$end = date('Y-m-d 23:59:59');
$record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
$relationId = [];
foreach ($record as $k => $v) {
$whereRe['id'] = array('gt', $v['id']);
$whereRe['relation_id'] = $v['relation_id'];
$recordData = Record::where($whereRe)->count();
if ($recordData >= 1) {
$relationId[] = $v['relation_id'];
}
}
$wheres['id'] = array('in', $relationId);
$staff = Staff::info();
$wheres['owner_staff_id'] = $staff->id;
break;
case 5:
$record = collection(Record::where(array('relation_type' => 1, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
$wheres['id'] = array('not in', $record);
$staff = Staff::info();
$wheres['owner_staff_id'] = $staff->id;
break;
default:
$wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
break;
}
$owner_staff_id = $wheres['owner_staff_id'];
unset($wheres['owner_staff_id']);
$list = $this->model->where($where)->with(['ownerStaff'])
->where($wheres)->where(function ($query) use ($staff_id, $owner_staff_id, $type) {
if ($type == 0) {//全部
$query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
->whereOr(['owner_staff_id' => $owner_staff_id]);
} else {
$query->where(['owner_staff_id' => $owner_staff_id]);
}
})
->where('owner_staff_id != 0 and owner_staff_id is not null')
->order($sort, $order)->paginate($limit);
$rows = $list->items();
foreach ($rows as &$v) {
$v['operation_team'] = 'read';
if ($v['owner_staff_id'] == $this->_staff->id ||
in_array($v['owner_staff_id'], Staff::getLowerStaffId()) ||
in_array($this->_staff->id, explode(',', $v['rw_staff_id']))) {
if (in_array($this->_staff->id, explode(',', $v['rw_staff_id']))) {
$v['operation_team'] = 'update';//可修改客户不可操作其他
}
$v['operation'] = 'update';//修改权限
} else {
$v['operation'] = 'read';//只读权限
}
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
$field = FormField::getFields(FormField::CUSTOMER_TYPE);
$this->assignconfig('fields', $field);
return $this->view->fetch();
}
public function index2(){
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
if ($this->request->request('keyField')) {
//halt(111);
return $this->selectpage2(1);
}
}
}
public function getContacts(){
$param = $this->request->param();
$model = new \app\admin\model\qingdong\Contacts();
$id = $model->where('customer_id',$param['id'])->value('id');
$this->success('','',['id'=>$id]);
//halt($param['id']);
}
//出仓清单
public function tmrxyoList($customer_id = null){
$customers_id = (new \app\admin\model\kuerp\Customers)->where('customer_id',$customer_id)->value('id');
if($customers_id){
$list = (new \app\admin\model\kuerp\GoodsSales())->where('customers_id',$customers_id)->select();
$tmrxyoModel = new \app\admin\model\fastflow\bill\Tmrxyo();
$contractModel = new \addons\qingdong\model\Contract();
$businessModel = new \addons\qingdong\model\Business();
$amodelModel = new \addons\qingdong\model\Amodela;
foreach ($list as &$item){
$contract_id = $tmrxyoModel->where('id',$item['tmrxyo_id'])->value('contract_id');
if($contract_id){
$contract = $contractModel->where('id',$contract_id)->find();
if($contract){
$item['contract_name'] = $contract['name']??'';
if($contract['offer_id']){
$amodel = $amodelModel->where('id',$contract['offer_id'])->find();
$item['amodel_name'] = $amodel['name']??'';
$item['business_name'] = $amodel['business_name']??'';
}
}else{
$item['contract_name'] = $item['amodel_name'] = $item['business_name'] = '';
}
}else{
$item['contract_name'] = $item['amodel_name'] = $item['business_name'] = '';
}
}
}else{
$list = [];
}
$result = array("total" => count($list), "rows" => $list);
return json($result);
}
//出仓详情
public function tmrxyoDetail($ids = null){
$infoModel = new \app\admin\model\kuerp\GoodsSalesInfo();
$salesModel = new \app\admin\model\kuerp\GoodsSales();
$find = $salesModel->where('id',$ids)->find();
$list = $infoModel->with(['goods'])->where('purchase_code',$find['purchase_code'])->select();
foreach ($list as &$item){
if($item['goods_type'] == '1'){
$item['goods_type'] = '待发货';
}elseif ($item['goods_type'] == '2'){
$item['goods_type'] = '已发货';
}else{
$item['goods_type'] = '';
}
}
$this->assign('list', $list);
return $this->view->fetch('tmrxyodetail');
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
// 表单验证
if (($result = $this->qingdongValidate($params, 'Customer', 'create')) !== true) {
$this->error($result);
}
$mobile='';
if(isset($params['mobile']) && $params['mobile']){
$mobile = $params['mobile'];
}
if(isset($params['name']) && $params['name']){
$customerData = $this->model->where(['name'=>$params['name']])->find();
if($customerData){
$this->error('客户名称已存在');
}
}
$result = FormField::checkFields(FormField::CUSTOMER_TYPE, $params);
if ($result !== true) {
$this->error($result);
}
$result = false;
Db::startTrans();
try {
$params = Form::updateFormParams(Form::CUSTOMER_TYPE, $params);
$result = $this->model::createCustomer($params);
if($mobile){
$retC = array(
'customer_id'=>$result,
'is_major'=>1,
'name'=>$params['main_zxfpre'],
'mobile'=>$mobile,
'role'=>$params['main_kxtecc'] ??'',
'post'=>$params['other_zjldyu'] ??'',
'next_time'=>date('Y-m-d H:i:s'),
'create_staff_id'=>$this->_staff->id,
'owner_staff_id'=>$this->_staff->id,
);
Contacts::create($retC);
}
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->assign('form_data', Form::getDataValue(Form::CUSTOMER_TYPE));
$remind = Remind::where(['type' => Remind::CUSTOMER_TYPE])->find();
$staff_ids = $remind['staff_ids'] ?? '';
$this->assign('seastype', Seastype::where([])->column('name', 'id'));
$this->assign('staff_ids', $staff_ids);
$this->assign('staff', Staff::where([])->column('name', 'id'));
return $this->view->fetch();
}
/**
* 修改
*/
public function edit($ids = null)
{
$row = $this->model->where([
'id' => $ids,
])->find();
if (empty($row)) {
$this->error(__('No Results were found'));
}
if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) &&
!in_array($this->_staff->id, explode(',', $row['ro_staff_id']))) {//是否在团队内
$this->error('权限不足');
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
// 表单验证
if (($result = $this->qingdongValidate($params, 'Customer', 'create')) !== true) {
$this->error($result);
}
$result = FormField::checkFields(FormField::CUSTOMER_TYPE, $params,$ids);
if ($result !== true) {
$this->error($result);
}
$mobile='';
if(isset($params['mobile']) && $params['mobile']){
$mobile = $params['mobile'];
}
$result = false;
Db::startTrans();
try {
$params = Form::updateFormParams(Form::CUSTOMER_TYPE, $params);
$params['id'] = $ids;
$result = $this->model::updateCustomer($params);
if($mobile){
Contacts::where(array('customer_id'=>$ids,'is_major'=>1))->update(array('mobile'=>$mobile,'updatetime'=>time()));
}
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$row = $row->toArray();
$row = CustomerOther::getOther($row);
$form = Form::getDataValue(Form::CUSTOMER_TYPE, $row);
$this->assign('seastype', Seastype::where([])->column('name', 'id'));
$this->assign('row', $row);
$this->assign('form_data', $form);
return $this->view->fetch();
}
/**
* 搜索下拉列表
*/
public function stafflist()
{
$data = ['searchlist' => Staff::getList()];
$this->success('', null, $data);
}
/**
* 转移客户
*/
public function change($ids = null)
{
$row = $this->model->where([
'id' => $ids,
])->find();
if (empty($row)) {
$this->error(__('No Results were found'));
}
if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) &&
!in_array($this->_staff->id, explode(',', $row['ro_staff_id']))) {//是否在团队内
$this->error('权限不足');
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try {
$result = $this->model::transfer($ids, $params['owner_staff_id']);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$staffs = Staff::getList();
$this->assign('staffs', $staffs);
$this->assign('row', $row);
return $this->view->fetch();
}
/**
* 批量转移客户
*/
public function batch_change($ids = null)
{
$ids = json_decode($ids, true);
$ids = $this->model->where([
'id' => ['in', $ids]
])->column('id');
if (empty($ids)) {
$this->error(__('No Results were found'));
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try {
$result = $this->model::batchTransfer($ids, $params['owner_staff_id']);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$staffs = Staff::getList();
$this->assign('staffs', $staffs);
$this->assign('ids', json_encode($ids));
return $this->view->fetch();
}
/**
* 客户详情
*/
public function detail($ids = null)
{
$row = $this->model->with(['create_staff', 'owner_staff'])->where([
'id' => $ids,
])->find();
if (empty($row)) {
$this->error(__('No Results were found'));
}
if (!in_array($row['owner_staff_id'], Staff::getMyStaffIds()) && $row['owner_staff_id'] != 0) {
if (!in_array($this->_staff->id, explode(',', $row['rw_staff_id'])) &&
!in_array($this->_staff->id, explode(',', $row['ro_staff_id']))) {//是否在团队内
$this->error('权限不足');
}
}
$row = $row->toArray();
$row = CustomerOther::getOther($row);
$row['operation_team'] = 'read';
if ($row['owner_staff_id'] == $this->_staff->id ||
in_array($row['owner_staff_id'], Staff::getLowerStaffId()) ||
in_array($this->_staff->id, explode(',', $row['rw_staff_id']))) {
if (in_array($this->_staff->id, explode(',', $row['rw_staff_id']))) {
$row['operation_team'] = 'update';//可修改客户不可操作其他
}
$row['operation'] = 'update';//修改权限
} else {
$row['operation'] = 'read';//只读权限
}
$form = Form::getDataValue(Form::CUSTOMER_TYPE, $row);
foreach ($form as $ks => $vs) {
//备注显示
if ($vs['component'] == 'textarea' && ($vs['config']['label'] == '备注信息' || $vs['config']['label'] == '备注')) {
$row[$vs['id']] = isset($row[$vs['id']]) ? $row[$vs['id']] : $row['remarks'];
}
}
$this->assign('records', Record::getList(Record::CUSTOMER_TYPE, $ids));
$this->assign('form_data', $form);
$this->assign('row', $row);
$this->assign('ids', $ids);
$this->assignconfig("idinfo", ['id' => $ids, 'operation' => $row['operation'], 'operation_team' => $row['operation_team']]);
return $this->view->fetch();
}
public function get_customer_bill(){
$param = $this->request->param();
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$czgprzModel = new Czgprz();
// 查询PHP项目的报价单
$czgprzList = $czgprzModel->where('customer_id',$param['customer_id'])->select();
// 查询用友集成的报价单(通过该客户下的项目)
$businessModel = new \addons\antis\model\Business();
$businessIds = $businessModel->where('customer_id', $param['customer_id'])->column('id');
$amodelaList = [];
if (!empty($businessIds)) {
$amodelaModel = new \addons\qingdong\model\Amodela();
// 查询用友集成的报价单(name中包含 quotation_ 标记)
$amodelaList = $amodelaModel->where('business_id', 'in', $businessIds)
->where('name', 'like', '%(quotation_%')
->select();
}
// 合并两个列表
$allItems = [];
foreach ($czgprzList as $item) {
$allItems[] = [
'id' => $item['id'],
'name' => $item['name'],
'customer_id' => $item['customer_id'],
'is_yongyou' => false
];
}
foreach ($amodelaList as $item) {
$quotationId = null;
if (preg_match('/\(quotation_(\d+)\)/', $item['name'], $matches)) {
$quotationId = $matches[1];
}
$allItems[] = [
'id' => $item['id'],
'name' => $item['name'],
'customer_id' => $param['customer_id'],
'is_yongyou' => true,
'quotation_id' => $quotationId,
'external_url' => $quotationId ? get_yongyou_integration_full_url('quotation', ['id' => $quotationId, 'mode' => 'view']) : ''
];
}
// 按ID倒序排序
usort($allItems, function($a, $b) {
return $b['id'] - $a['id'];
});
// 分页处理
$total = count($allItems);
$offset = ($offset / $limit) * $limit; // 确保offset是limit的倍数
$items = array_slice($allItems, $offset, $limit);
$result = array("total" => $total, "rows" => $items);
return json($result);
}
/**
* 获取相关联系人
* @param null $ids
* @return \think\response\Json
*/
public function get_contacts($ids = null)
{
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = Contacts::where(['customer_id' => $ids])->order('id desc')->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 获取相关合同
*/
public function get_contract($ids = null)
{
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = Contract::where([
'customer_id' => $ids,
])->with('customer')->order('id desc')->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 添加费用
*/
public function add_consume($ids = null)
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
// 表单验证
if (($result = $this->qingdongValidate($params, 'Consume', 'create')) !== true) {
$this->error($result);
}
Db::startTrans();
try {
$result = Consume::createConsume($params);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result) {
$this->success('添加费用成功');
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$customer = $this->model->where(['id' => $ids])->find();
$this->assign('staff', Staff::where([])->column('name', 'id'));
$this->view->assign('customer', $customer);
return $this->view->fetch();
}
/**
* 获取费用
*/
public function get_consume($ids = null)
{
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = Consume::where([
'customer_id' => $ids,
])->with('follow_staff')->order('id desc')->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 获取团队成员
* @param null $ids
*/
public function getteam($ids = null)
{
$customer = $this->model::get($ids);
if (empty($customer)) {
$this->error('客户不存在');
}
$where = [];
if ($keyValue = $this->request->request("keyValue")) {
$where['id'] = ['eq', $keyValue];
}
if ($where) {
$owner_staff = Staff::where($where)->find();
$rw_staffs = [];
$ro_staffs = [];
} else {
$owner_staff = Staff::where(['id' => $customer->owner_staff_id])->find();
$rw_staffs = Staff::where(['id' => ['in', explode(',', $customer->rw_staff_id)]])->select();
$ro_staffs = Staff::where(['id' => ['in', explode(',', $customer->ro_staff_id)]])->select();
}
$staffs = [];
if ($owner_staff) {
$staffs[] = [
'id' => $owner_staff->id,
'name' => $owner_staff->name,
'img' => $owner_staff->img,
'post' => $owner_staff->post,
'roles' => '负责人',
'is_edit' => '读写',
'customer_id' => $customer->id,
];
}
foreach ($rw_staffs as $v) {
$staffs[] = [
'id' => $v->id,
'name' => $v->name,
'img' => $v->img,
'post' => $v->post,
'roles' => '普通员工',
'is_edit' => '读写',
'customer_id' => $customer->id,
];
}
foreach ($ro_staffs as $v) {
$staffs[] = [
'id' => $v->id,
'name' => $v->name,
'img' => $v->img,
'post' => $v->post,
'roles' => '普通员工',
'is_edit' => '只读',
'customer_id' => $customer->id,
];
}
$result = array("total" => count($staffs), "rows" => $staffs);
return json($result);
}
/**
* 添加团队成员
*/
public function addteam($ids = null)
{
$customer = \addons\antis\model\Customer::get($ids);
if (empty($customer)) {
$this->error('客户不存在');
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
$staff_ids = $params['staff_id'];
if (empty($staff_ids)) {
$this->error('员工不存在');
}
$staff_ids = explode(',', $staff_ids);
foreach ($staff_ids as $k => $id) {
if ($id == $customer->owner_staff_id) {
unset($staff_ids[$k]);
}
}
$ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
$rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
if ($params['rules'] == 1) {//读写
$rw_staff_id = array_merge($rw_staff_id, $staff_ids);
$rw_staff_id = array_unique($rw_staff_id);
} else {
$ro_staff_id = array_merge($ro_staff_id, $staff_ids);
$ro_staff_id = array_unique($ro_staff_id);
}
$ro_staff_id = array_diff($ro_staff_id, $rw_staff_id);
$rw_staff_id = implode(',', $rw_staff_id);
$ro_staff_id = implode(',', $ro_staff_id);
$result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
'ro_staff_id' => ",{$ro_staff_id},"]);
if ($result === false) {
$this->error('修改失败');
}
$this->success('修改成功');
}
$owner_staff = Staff::where(['id' => $customer->owner_staff_id])->find();
$rw_staffs = Staff::where(['id' => ['in', explode(',', $customer->rw_staff_id)]])->select();
$ro_staffs = Staff::where(['id' => ['in', explode(',', $customer->ro_staff_id)]])->select();
$staffs = [];
if ($owner_staff) {
$staffs[] = [
'id' => $owner_staff->id,
'name' => $owner_staff->name,
'img' => $owner_staff->img,
'post' => $owner_staff->post,
'mobile' => $owner_staff->mobile,
'roles' => 1,
'is_edit' => 1,
];
}
foreach ($rw_staffs as $v) {
$staffs[] = [
'id' => $v->id,
'name' => $v->name,
'img' => $v->img,
'post' => $v->post,
'mobile' => $v->mobile,
'roles' => 2,
'is_edit' => 1,
];
}
foreach ($ro_staffs as $v) {
$staffs[] = [
'id' => $v->id,
'name' => $v->name,
'img' => $v->img,
'post' => $v->post,
'mobile' => $v->mobile,
'roles' => 2,
'is_edit' => 0,
];
}
$this->assign('staffs', $staffs);
return $this->view->fetch();
}
/**
* 修改团队成员
*/
public function editteam($ids = null)
{
$customer_id = input('customer_id');
$customer = $this->model->get($customer_id);
if (empty($customer)) {
$this->error('客户不存在');
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
$staff_id = $params['staff_id'];
if (empty($staff_id)) {
$this->error('员工不存在');
}
$ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
$rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
if ($params['rules'] == 1) {//读写
$rw_staff_id[] = $staff_id;
$rw_staff_id = array_unique($rw_staff_id);
} else {
foreach ($rw_staff_id as $k => $id) {
if ($id == $staff_id) {
unset($rw_staff_id[$k]);
}
}
$ro_staff_id[] = $staff_id;
$ro_staff_id = array_unique($ro_staff_id);
}
$ro_staff_id = array_diff($ro_staff_id, $rw_staff_id);
$rw_staff_id = implode(',', $rw_staff_id);
$ro_staff_id = implode(',', $ro_staff_id);
$result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
'ro_staff_id' => ",{$ro_staff_id},"]);
if ($result === false) {
$this->error('修改失败');
}
$this->success('修改成功');
$this->success('修改成功');
}
if (in_array($ids, explode(',', $customer->rw_staff_id))) {
$is_edit = 1;
} else {
$is_edit = 0;
}
$this->assign('is_edit', $is_edit);
$this->assign('staff_id', $ids);
return $this->view->fetch();
}
/**
* 删除团队成员
*/
public function delteam()
{
$customer_id = input('customer_id');
$customer = $this->model->get($customer_id);
if (empty($customer)) {
$this->error('客户不存在');
}
if ($this->request->isPost()) {
$staff_id = input('staff_id');
if (empty($staff_id)) {
$this->error('员工不存在');
}
$ro_staff_id = explode(',', trim($customer->ro_staff_id, ','));
$rw_staff_id = explode(',', trim($customer->rw_staff_id, ','));
foreach ($ro_staff_id as $k => $id) {
if ($id == $staff_id || empty($id)) {
unset($ro_staff_id[$k]);
}
}
foreach ($rw_staff_id as $k => $id) {
if ($id == $staff_id || empty($id)) {
unset($rw_staff_id[$k]);
}
}
$rw_staff_id = implode(',', $rw_staff_id);
$ro_staff_id = implode(',', $ro_staff_id);
$result = $customer->save(['rw_staff_id' => ",{$rw_staff_id},",
'ro_staff_id' => ",{$ro_staff_id},"]);
if ($result === false) {
$this->error('删除失败');
}
$this->success('删除成功');
}
}
/**
* 获取回款计划
* @param null $ids
*/
public function get_receivables_plan($ids = null)
{
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = ReceivablesPlan::where(['customer_id' => $ids])->with([
'customer',
'contract'
])->order('id desc')->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 获取回款记录
*/
public function get_receivables($ids = null)
{
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = Receivables::where(['customer_id' => $ids])->with([
'customer',
'contract',
'ownerStaff',
])->order('id desc')->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 获取附件记录
*/
public function get_file($ids = null)
{
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = CustomerFile::where(['customer_id' => $ids])->with(['file'])->order('id desc')->field('file_id')->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 移入公海
*/
public function seas($ids = "")
{
$row = $this->model->where([
'id' => $ids,
'owner_staff_id' => ['in', Staff::getMyStaffIds()]
])->find();
if (empty($row)) {
$this->error(__('No Results were found'));
}
if ($this->request->isPost()) {
$result = false;
Db::startTrans();
try {
$result = $this->model::moveSeas($ids);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
$this->error(__('Parameter %s can not be empty', ''));
}
}
/**
* 领取客户
*/
public function receive($ids = "")
{
$row = $this->model->where([
'id' => $ids,
'owner_staff_id' => 0
])->find();
if (empty($row)) {
$this->error(__('No Results were found'));
}
if ($this->request->isPost()) {
$result = false;
Db::startTrans();
try {
$result = $this->model::receive($ids);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success('领取客户成功');
}
$this->error(__('Parameter %s can not be empty', ''));
}
}
/**
* 删除
*/
public function del($ids = "")
{
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ? $ids : $this->request->post("ids");
$row = $this->model->where([
'id' => $ids,
'owner_staff_id' => ['in', Staff::getMyStaffIds()]
])->find();
$this->modelValidate = true;
if (!$row) {
$this->error(__('No Results were found'));
}
//如果有合同和回款,不可删除客户
$Contract = Contract::where(array('customer_id' => $ids))->find();
if ($Contract) {
$this->error('已创建合同不可删除');
}
$Receivables = Receivables::where(array('customer_id' => $ids))->find();
if ($Receivables) {
$this->error('已创建回款不可删除');
}
$map['id'] = $ids;
$result = $this->model->destroy($map);
if (!$result) {
$this->error('删除失败');
}
$this->success();
}
/**
* 获取团队人员列表
*/
public function getstaff()
{
$pageSize = input('pageSize');
$pageNumber = input('pageNumber');
$where = [];
if ($keyValue = $this->request->request("keyValue")) {
$where['id'] = ['in', $keyValue];
}
$name = input('name');
if (!empty($name)) {
$where['name'] = ['like', '%' . $name . '%'];
}
$staff = Staff::where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
return json(['list' => $staff->items(), 'total' => $staff->total()]);
}
/**
* 地图
*/
public function map()
{
$key = AdminConfig::getConfigValue('map_key', 'wechat');
$this->assign('key', $key);
return $this->view->fetch();
}
/**
* 获取签到记录
*/
public function get_sign()
{
$customerId = input('customer_id', '');
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = StaffSignIn::where([
'customer_id' => $customerId,
])->order('id desc')->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 获取签到记录
*/
public function get_sign_detail($ids = null)
{
$staffSign = StaffSignIn::where(['id' => $ids])->find();
if (empty($staffSign)) {
$this->error('数据不存在');
}
if ($staffSign['other']) {
$other = json_decode($staffSign['other'], true);
$form = Form::getDataValue(Form::SIGNIN_TYPE);
foreach ($form as $k => $v) {
if ($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile') {
$other[$v['id'] . '_str'] = '';
if (key_exists($v['id'], $other)) {
if (isset($other[$v['id']]) && $other[$v['id']]) {
$whereT['id'] = array('in', $other[$v['id']]);
$fileinfo = File::where($whereT)->field('id,name,file_path,save_name')->select();
if ($fileinfo) {
$other[$v['id']] = $fileinfo;
$fileinfodata = '';
foreach ($fileinfo as $kss => $vss) {
$fileinfodata = $vss['save_name'] . ',' . $fileinfodata;
}
$other[$v['id'] . '_str'] = rtrim($fileinfodata, ',');
}
}
}
}
}
$staffSign['other'] = $other;
}
$this->assign('form_data', Form::getDataValue(Form::SIGNIN_TYPE, $staffSign['other']));
$this->assign('row', $staffSign['other']);
return $this->view->fetch();
}
/**
* 获取相关商机
* @param null $ids
* @return \think\response\Json
*/
public function get_business()
{
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$customer_id = input('customer_id');
$list = Business::where(['customer_id' => $customer_id])->order('id desc')->paginate($limit);
foreach ($list as $k => $v) {
$types = BusinessStatus::where(array('business_id' => $v['id']))->order('id desc')->value('type');
$list[$k]['type'] = $types ? (int)$types : 0;
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 导入客户
* @return string|void
*/
public function import()
{
set_time_limit(0);
if ($this->request->isPost()) {
$file = $this->request->request('file');
$staff_id = $this->request->request('staff_id', 0);
$seas_type_id = input('seas_type_id',0);
if (!$file) {
$this->error(__('Parameter %s can not be empty', 'file'));
}
$filePath = ROOT_PATH . 'public' . $file;
if (!is_file($filePath)) {
$this->error(__('No results were found'));
}
//实例化reader
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
$this->error(__('Unknown data format'));
}
if ($ext === 'csv') {
$file = fopen($filePath, 'r');
$filePath = tempnam(sys_get_temp_dir(), 'import_csv');
$fp = fopen($filePath, "w");
$n = 0;
while ($line = fgets($file)) {
$line = rtrim($line, "\n\r\0");
$encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
if ($encoding != 'utf-8') {
$line = mb_convert_encoding($line, 'utf-8', $encoding);
}
if ($n == 0 || preg_match('/^".*"$/', $line)) {
fwrite($fp, $line . "\n");
} else {
fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
}
$n++;
}
fclose($file) || fclose($fp);
$reader = new Csv();
} elseif ($ext === 'xls') {
$reader = new Xls();
} else {
$reader = new Xlsx();
}
if (!$PHPExcel = $reader->load($filePath)) {
$this->error(__('Unknown data format'));
}
$currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
$allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
$maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
//开始读取数据
$fields = [];
for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$fields[$currentRow][] = $val;
if ($val instanceof RichText) {//富文本转换字符串
$val = $val->__toString();
}
$values[] = is_null($val) ? '' : trim($val);
}
}
if (!isset($fields[1])) {
$this->error('导入文件第一行没有数据');
}
$lastid = $this->model->withTrashed()->order('id desc')->value('id');
$lastid = $lastid + 5;//防止重复
$customerRow = [];
$errorInfo = [];
$formrow = [];
$names = $this->model->where([])->column('name');
$fieldnames = FormField::where(['types' => FormField::CUSTOMER_TYPE])->column('field', 'name');
if(!$fieldnames){
$this->error('请在系统管理->字段管理中保存客户管理表单生成客户导入字段');
}
$forms = Form::getDataValue(Form::CUSTOMER_TYPE);
foreach($forms as $k=>$v){
$formrow[$v['id']] = $v['name'];
}
$fn = [];
for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
$values = [];
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$values[] = is_null($val) ? '' : $val;
}
foreach ($values as $l) {
$fn[] = $fieldnames[$l] ?? '';
}
}
for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
$values = [];
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
if ($val instanceof RichText) {//富文本转换字符串
$val = $val->__toString();
}
$values[] = is_null($val) ? NULL : trim($val);
}
$lastid++;
$addCustomers = ['id' => $lastid, 'owner_staff_id' => $staff_id, 'create_staff_id' => $staff_id];
foreach ($values as $kv => $value) {
if (!isset($fn[$kv]) || empty($fn[$kv])) {
continue;
}
$addCustomers[$fn[$kv]] = $value;
}
//日期格式处理
foreach($formrow as $k=>$v){
if($v=='日期选择框'){
if(isset($addCustomers[$k]) && $addCustomers[$k]){
$addCustomers[$k] =date("Y-m-d", ($addCustomers[$k] - 25569) * 24 * 3600);
}
}
if($v=='时间选择框'){
if(isset($addCustomers[$k]) && $addCustomers[$k]){
$addCustomers[$k] =date("Y-m-d H:i:s", ($addCustomers[$k] - 25569) * 24 * 3600);
}
}
}
if (empty($addCustomers['name'])) {
$errorInfo[] = "第{$currentRow}行,客户名称不能为空;";
continue;
}
if (in_array($addCustomers['name'], $names)) {
$errorInfo[] = "第{$currentRow}行,客户名称`{$addCustomers['name']}`已存在;";
continue;
}
$addCustomers['seas_id']=",{$seas_type_id},";
$customerRow[] = $addCustomers;
}
if (!empty($errorInfo)) {
$this->error(implode(',', $errorInfo));
}
Db::startTrans();
try {
$this->model::importCustomer($customerRow);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success('导入成功');
}
$this->assign('seas_type', Seastype::where([])->field('id,name')->select());
$this->assign('staffs', Staff::getList());
return $this->view->fetch();
}
/**
* 模板
*/
public function template()
{
$title = [];
$dataValue = Form::getDataValue(Form::CUSTOMER_TYPE);
foreach ($dataValue as $val) {
$title[] = $val['config']['label'];
}
$file = export_excel($title, [], '客户');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename=' . $file['fileName']);
header('Cache-Control: max-age=0');
$obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
// 以下内容是excel文件的信息描述信息
$obj->getProperties()->setTitle('导出文件'); //设置标题
$obj->setActiveSheetIndex(0);
$obj->getActiveSheet()->setTitle('导出文件');
/* 循环读取每个单元格的数据 */
$a = 'A';
$currentSheet = $obj->getActiveSheet();
foreach ($title as $key => $value) {
//读取工作表1
// 设置第一行加粗
$obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
//这里是设置单元格的内容
$currentSheet->getCell($a . '1')->setValue($value);
$a++;
}
$PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
$PHPWriter->save('php://output');
}
/**
* 导出信息
*/
public function export()
{
$this->request->filter(['strip_tags', 'trim']);
$ids = input('ids');
$isall = input('isall');
$wheres = array();
//导出其中几条
if (isset($ids)) {
$wheres['id'] = array('in', $ids);
}
//导出全部
if (isset($isall)) {
if ($isall == 3) {
unset($wheres['id']);
}
}
//0:全部 1:我负责的 2:下属负责的 3:今日待跟进 4:今日已跟进 5:从未跟进的
$type = input('type', 0);
$staff = Staff::info();
$staff_id = $staff->id;
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
switch ($type) {
case 1://我负责
$wheres['owner_staff_id'] = $staff_id;
break;
case 2://下属负责
$wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
break;
case 3:
$start = date('Y-m-d 00:00:00');
$end = date('Y-m-d 23:59:59');
$record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
$relationId = [];
foreach ($record as $k => $v) {
$whereRe['id'] = array('gt', $v['id']);
$whereRe['relation_id'] = $v['relation_id'];
$recordData = Record::where($whereRe)->count();
if ($recordData == 0) {
$relationId[] = $v['relation_id'];
}
}
$wheres['id'] = array('in', $relationId);
$staff = Staff::info();
$wheres['owner_staff_id'] = $staff->id;
break;
case 4:
$start = date('Y-m-d 00:00:00');
$end = date('Y-m-d 23:59:59');
$record = collection(Record::where(array('relation_type' => 1, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
$relationId = [];
foreach ($record as $k => $v) {
$whereRe['id'] = array('gt', $v['id']);
$whereRe['relation_id'] = $v['relation_id'];
$recordData = Record::where($whereRe)->count();
if ($recordData >= 1) {
$relationId[] = $v['relation_id'];
}
}
$wheres['id'] = array('in', $relationId);
$staff = Staff::info();
$wheres['owner_staff_id'] = $staff->id;
break;
case 5:
$record = collection(Record::where(array('relation_type' => 1, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
$wheres['id'] = array('not in', $record);
$staff = Staff::info();
$wheres['owner_staff_id'] = $staff->id;
break;
default:
$wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
break;
}
$owner_staff_id = $wheres['owner_staff_id'];
unset($wheres['owner_staff_id']);
$list = $this->model->where($where)->with(['ownerStaff','customerOther'])
->where($wheres)
->where(function ($query) use ($staff_id, $owner_staff_id, $type) {
if ($type == 0) {//全部
$query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
->whereOr(['owner_staff_id' => $owner_staff_id]);
} else {
$query->where(['owner_staff_id' => $owner_staff_id]);
}
})
->where('owner_staff_id != 0 and owner_staff_id is not null')->order($sort, $order)->select();
$list = collection($list)->toArray();
if (!$list) {
$this->error('无导出数据');
}
$title = [
'序号',
'归属人',
'创建时间',
'下次联系时间',
'最后跟进时间',
];
$dataValue = Form::getDataValue(Form::CUSTOMER_TYPE);
foreach ($dataValue as $val) {
$title[] = $val['config']['label'];
}
$data=[];
foreach ($list as $k => $v) {
if($v['customer_other']){//其他客户
$other=$v['customer_other']['otherdata'];
$other=json_decode($other,true);
$v = array_merge($v, $other);
}
$field = array(
$v['id'],
$v['owner_staff']['name'],
$v['createtime'],
$v['next_time'],
$v['last_time'],
);
foreach ($dataValue as $val) {
if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
$field[] = $v[$val['id'] . '_str'] ?? '';
} else {
$field[] = ($v[$val['id']] ?? '');
}
}
$data[] = $field;
}
//halt($data);
$file = export_excel($title, $data, '客户');
if ($file['filePath']) {
$this->success('导出成功', '', $file);
}
$this->error('导出失败');
}
/**
* 导出word
*/
public function words($ids = null)
{
if ($this->request->isPost()) {
$file = input('file', '');
$is_template=input('is_template',0);
$template_name=input('template_name','');
if (empty($file)) {
$this->error('导出模板');
}
if($is_template == 1){
if(empty($template_name)){
$this->error('模板名称不能为空');
}
$create=[
'type'=>'customer',
'name'=>$template_name,
'url'=>$file
];
$wordTemplateModel = new WordTemplate();
$wordTemplateModel->save($create);
}
$tmp = new TemplateProcessor('.' . $file);
Settings::setCompatibility(true);
Settings::setOutputEscapingEnabled(true);
$row = $this->model::get($ids);
$row = $row->toArray();
$row = CustomerOther::getOther($row);
$form = Form::getDataValue(Form::CUSTOMER_TYPE);
$imgNames=[];
foreach($form as $k=>$v){
if($v['component'] == 'uploadImage'){
$imgNames[]=$v['id'];
}
}
foreach ($row as $key => $item) {
if(in_array($key,$imgNames) && $item ){
if(is_array($item)){
foreach ($item as $it){
$tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
}
}else{
$fileinfo = File::where(['id'=>['in',$item]])->field('id,name,file_path,save_name')->select();
foreach ($fileinfo as $it){
$tmp->setImageValue($key,ltrim(parse_url($it['file_path'])['path'],'/'));
}
}
}else{
if(is_array($item)){
$tmp->setValue($key , '');//
continue;
}
$tmp->setValue($key , $item);//
}
}
$contacts = Contacts::where(['customer_id' => $ids])->find();
if ($contacts) {
$contacts=$contacts->toArray();
$contacts = ContactsOther::getOther($contacts);
foreach ($contacts as $key => $item) {
if(is_array($item)){
continue;
}
if ($key == 'name') {
$key = 'con_name';
}
if ($key == 'subname') {
$key = 'con_subname';
}
$tmp->setValue($key, $item);//
}
}else{
$form = Form::getDataValue(Form::CONTACTS_TYPE);
foreach ($form as $f) {
if ($f['id'] == 'name') {
$f['id'] = 'con_name';
}
if ($f['id'] == 'subname') {
$f['id'] = 'con_subname';
}
$tmp->setValue($f['id'], '');//
}
}
//end 配置
$filename = $row['name'];
$filepath = $filename . '.docx';
$fileurl = './uploads/' . date('Ymd') . '/';
if (!file_exists($fileurl)) {
mkdir($fileurl);
}
$tmp->saveAs($fileurl . $filepath);//另存为
$model = new File();
$data = [
'types' => 'file',
'name' => $filepath,
'save_name' => $fileurl . $filepath,
'size' => filesize($fileurl . $filepath),
'file_path' => trim($fileurl, '.') . $filepath,
];
$model->save($data);
$lastid = $model->id;
$file = cdnurl($model::getUrl($lastid), true);
$this->success('成功', '', ['file' => $file, 'id' => $lastid, 'filename' => $filepath]);
}
$form = Form::getDataValue(Form::CUSTOMER_TYPE);
$column = array();
foreach ($form as $k => $v) {
if ($v['config']['label'] == '备注信息') {
$v['config']['label'] = '客户备注';
}
$column[] = array(
'key' => $v['id'],
'name' => $v['config']['label'],
);
}
$templates=WordTemplate::where(['type'=>'customer'])->select();
$contacts = Form::getDataValue(Form::CONTACTS_TYPE);
$columns = array();
foreach ($contacts as $k => $v) {
if ($v['id'] == 'name') {
$v['id'] = 'con_name';
}
if ($v['id'] == 'subname') {
$v['id'] = 'con_subname';
}
if ($v['config']['label'] == '备注信息') {
$v['config']['label'] = '联系人备注';
}
$columns[] = array(
'key' => $v['id'],
'name' => $v['config']['label'],
);
}
$column = array_merge($column, $columns);
$this->assign('column', $column);
$this->assign('templates', $templates);
$this->assign('ids', $ids);
return $this->view->fetch();
}
/**
* 保存客户报价单关联(用于关联用友集成的报价单)
* 如果客户下没有项目,会创建一个默认项目
* @return \think\response\Json
*/
public function save_customer_quotation_link()
{
// 处理 CORS 跨域请求
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
// 处理 OPTIONS 预检请求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
http_response_code(200);
exit;
}
$this->request->filter(['strip_tags', 'trim']);
$customer_id = input('customer_id');
$quotation_id = input('quotation_id');
$quotation_number = input('quotation_number', '');
$quotation_name = input('quotation_name', '');
if (empty($customer_id) || empty($quotation_id)) {
return json(['code' => 0, 'msg' => '参数不完整:customer_id 和 quotation_id 必填', 'data' => null]);
}
// 检查客户是否存在
$customer = $this->model->where('id', $customer_id)->find();
if (!$customer) {
return json(['code' => 0, 'msg' => '客户不存在', 'data' => null]);
}
try {
// 查找客户下的项目,如果没有则创建一个默认项目
$businessModel = new \addons\antis\model\Business();
$business = $businessModel->where('customer_id', $customer_id)->order('id desc')->find();
if (!$business) {
// 创建默认项目
$businessData = [
'customer_id' => $customer_id,
'name' => '默认项目',
'owner_staff_id' => $customer->owner_staff_id ?? 0,
'createtime' => time(),
'updatetime' => time()
];
$result = $businessModel->save($businessData);
if (!$result) {
return json(['code' => 0, 'msg' => '创建默认项目失败:' . ($businessModel->getError() ?: '未知错误'), 'data' => null]);
}
$business_id = $businessModel->id;
\think\Log::write('save_customer_quotation_link 创建默认项目成功: business_id=' . $business_id, 'info');
} else {
$business_id = $business->id;
}
// 在 Amodela 表中创建关联记录
$amodelaModel = new \addons\qingdong\model\Amodela();
// 检查是否已存在关联记录
$quotationMarker = '(quotation_' . $quotation_id . ')';
$existing = $amodelaModel->where('business_id', $business_id)
->where('name', 'like', '%' . $quotationMarker . '%')
->find();
// 构建报价单名称
if ($quotation_name) {
if (strpos($quotation_name, $quotationMarker) === false) {
$quotationName = $quotation_name . $quotationMarker;
} else {
$quotationName = $quotation_name;
}
} else {
$custName = is_object($customer) ? trim((string)($customer->name ?? '')) : trim((string)($customer['name'] ?? ''));
$bizName = '';
if ($business) {
$bizName = is_object($business) ? trim((string)($business->name ?? '')) : trim((string)($business['name'] ?? ''));
}
$dateStr = date('Ymd');
$segments = array_values(array_filter([$custName, $bizName, $dateStr], function ($v) {
return $v !== '';
}));
$baseName = implode('_', $segments);
$quotationName = $baseName !== '' ? ($baseName . $quotationMarker) : ('用友报价单-' . $quotation_number . $quotationMarker);
}
if ($existing) {
// 更新现有记录
$existing->name = $quotationName;
$result = $existing->save();
$amodelaModel = $existing;
} else {
// 创建新的关联记录
// 同 Business::save_quotation_link:补齐安全默认值,避免生产库 NOT NULL / 无默认值导致 500
$amodelaModel->business_id = $business_id;
$amodelaModel->bill_id = 0; // 用友集成报价单:不对应 PHP 流程单据
$amodelaModel->name = $quotationName;
$amodelaModel->status = '1';
$amodelaModel->amodel_id = 0;
$amodelaModel->type = 'goods';
$amodelaModel->goods_id = '';
$amodelaModel->json = json_encode([], JSON_UNESCAPED_UNICODE);
$amodelaModel->lr = 1;
$amodelaModel->file = '';
$amodelaModel->customer_id = intval($customer_id);
// 取客户/项目名称(如果字段存在)
$amodelaModel->customer_name = isset($customer['name']) ? $customer['name'] : '';
try {
$amodelaModel->business_name = \addons\antis\model\Business::where('id', $business_id)->value('name') ?: '默认项目';
} catch (\Exception $e) {
$amodelaModel->business_name = '默认项目';
}
\think\Log::write('save_customer_quotation_link 准备保存数据: customer_id=' . $customer_id . ', business_id=' . $business_id . ', name=' . $quotationName . ', bill_id=0, type=goods, status=1, amodel_id=0', 'info');
try {
$result = $amodelaModel->allowField(true)->save();
if ($result) {
$savedId = $amodelaModel->id;
\think\Log::write('save_customer_quotation_link 保存成功: id=' . $savedId, 'info');
// 验证保存是否成功
$verifyRecord = $amodelaModel->where('id', $savedId)->find();
if ($verifyRecord) {
\think\Log::write('save_customer_quotation_link 验证成功: id=' . $savedId . ', name=' . $verifyRecord['name'], 'info');
} else {
\think\Log::write('save_customer_quotation_link 警告: save()返回true但查询不到记录 id=' . $savedId, 'warning');
}
} else {
$errorMsg = $amodelaModel->getError() ?: '未知错误';
\think\Log::write('save_customer_quotation_link 保存失败: ' . $errorMsg, 'error');
\think\Log::write('save_customer_quotation_link 模型数据: ' . json_encode($amodelaModel->getData(), JSON_UNESCAPED_UNICODE), 'error');
}
} catch (\Exception $e) {
\think\Log::write('save_customer_quotation_link 保存异常: ' . $e->getMessage() . ' | 文件: ' . $e->getFile() . ' | 行号: ' . $e->getLine(), 'error');
throw $e;
}
}
if ($result && isset($amodelaModel->id) && $amodelaModel->id > 0) {
return json([
'code' => 1,
'msg' => '客户报价单关联成功',
'data' => [
'id' => $amodelaModel->id,
'name' => $amodelaModel->name,
'customer_id' => $customer_id,
'business_id' => $business_id,
'quotation_id' => $quotation_id
]
]);
} else {
$errorMsg = '客户报价单关联失败:保存返回false或未获取到ID';
if ($amodelaModel->getError()) {
$errorMsg .= ',错误:' . $amodelaModel->getError();
}
\think\Log::write('save_customer_quotation_link 保存失败详情: ' . $errorMsg, 'error');
return json(['code' => 0, 'msg' => $errorMsg, 'data' => null]);
}
} catch (\Exception $e) {
$errorMsg = '保存客户报价单关联关系失败:' . $e->getMessage();
$errorMsg .= ' | 文件:' . $e->getFile();
$errorMsg .= ' | 行号:' . $e->getLine();
\think\Log::write('save_customer_quotation_link 异常: ' . $errorMsg, 'error');
return json(['code' => 0, 'msg' => $errorMsg, 'data' => null]);
}
}
}