Contract.php
102 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
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
<?php
namespace app\admin\controller\antis\customer;
use addons\antis\model\BusinessProduct;
use addons\antis\model\ContactsOther;
use addons\antis\model\ContractProduct;
use addons\antis\model\CustomerOther;
use addons\antis\model\ExamineRecord;
use addons\antis\model\File;
use addons\antis\model\FormField;
use addons\antis\model\Invoice;
use addons\antis\model\ProductPart;
use addons\antis\model\Product;
use addons\antis\model\Ratio;
use addons\antis\model\Receivables;
use addons\antis\model\Staff;
use addons\antis\model\WordTemplate;
use addons\fastflow\model\Czgprz;
use addons\qingdong\model\Amodela;
use addons\qingdong\model\AmodelGoods;
use app\admin\controller\antis\Base;
use addons\antis\model\ContractOther;
use addons\antis\model\Form;
use addons\antis\model\Contacts;
use addons\antis\model\Customer;
use addons\antis\model\OperationLog;
use addons\antis\model\Record;
use addons\antis\model\ContractFile;
use addons\antis\model\Flow;
use addons\antis\model\Business;
use app\admin\controller\fastflow\flow\CustomMessage;
use app\admin\controller\fastflow\flow\Run;
use app\admin\model\fastflow\bill\Bywnpk;
use app\admin\model\kuerp\Customers;
use app\admin\model\kuerp\Goods;
use app\admin\model\kuerp\GoodsStock;
use app\admin\model\kuerp\Warehouse;
use fastflow\api;
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 app\admin\model\ats\qingdong\Mainbody;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
/**
* 合同管理
* 操作文档:https://doc.fastadmin.net/antis
* 软件介绍:https://www.fastadmin.net/store/antis.html
* 售后微信:qingdong_crm
*/
class Contract extends Base {
protected $relationSearch = true;
/**
* @var \addons\antis\model\Contract
*/
protected $model = null;
protected $noNeedLogin = ['getContractGoods','object_array','tmrxyo','Billselectpage','flow','get_contract_offer_id','get_quotation_id_from_offer','search_contracts','get_contract_detail','get_offer_business_hint'];
public function _initialize() {
// 如果是无需登录的方法,跳过父类初始化,避免可能的错误
try {
$action = strtolower($this->request->action());
$noNeedLoginActions = ['getcontractgoods', 'object_array', 'tmrxyo', 'billselectpage', 'flow', 'get_contract_offer_id', 'get_quotation_id_from_offer', 'search_contracts', 'get_contract_detail', 'get_offer_business_hint'];
if (in_array($action, $noNeedLoginActions)) {
// 只初始化模型,跳过可能导致错误的操作
$this->model = new \addons\qingdong\model\Contract;
return;
}
} catch (\Exception $e) {
// 如果获取 action 失败,继续执行
}
parent::_initialize();
$this->model = new \addons\qingdong\model\Contract;
}
/**
* 查看
*/
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();
switch($type){
case 1:
$staff = Staff::info();
$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'=>3,'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'=>3,'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'=>3,'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;
}
$ids=[];
$group_id=input('group_id');
$staff_id=input('staff_id');
if ($group_id) {//角色组
$ids = Staff::getGroupStaffIds($group_id);
}
if ($staff_id) {
$ids = $staff_id;
}
if ($group_id || $staff_id) {
$wheres['owner_staff_id'] = ['in', $ids];
}
////审批流完成将合同状态改为通过审核
// halt($where);
$list = $this->model
->where($where)
->where($wheres)
->with([
'customer',
'orderStaff',
'contacts'
])
->order('id desc')
->paginate($limit);
$aa_list = $this->model->where('check_status',0)->field('id,bill_id,name,check_status')->select();
foreach ($aa_list as $v){
$status = Db::name('bywnpk')->where('ats_bywnpk.id',$v['bill_id'])->value('status');
if($status == 2){
$this->model->where('id',$v['id'])->update(['check_status'=>2]);
}
}
$allmoney = $this->model->where($wheres)->where(array('check_status'=>2))->sum('money');
$repayment_money = Receivables::where($wheres)->where(array('check_status'=>2))->sum('money'); //已回款
$no_money = $allmoney - $repayment_money;
if($no_money <= 0){
$no_money = 0;
}
$result = array("total" => $list->total(), "rows" => $list->items(),'allmoney'=>$allmoney,'repayment_money'=>$repayment_money,'no_money'=>$no_money);
return json($result);
}
$field = FormField::getFields(FormField::CONTRACT_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')) {
return $this->selectpage2(1);
}
}
}
public function getContractGoods(){
$param = $this->request->param();
if(isset($param['ids']) && !empty($param['ids'])){
$find = (new \addons\antis\model\Contract())->where('id',$param['ids'])->find();
$data = (new Amodela())->where('id',$find['offer_id'])->find();
if($data){
$goodsModel = new Goods();
$json = json_decode($data['json']);
$json = $this->object_array($json);
if($json){
$this->success('','',$json);
}
}
}
$this->success('','','');
}
//合同出仓
public function tmrxyo($ids = null){
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
$row = $this->model->get($ids);
$stockModel = new GoodsStock();
//组合商品
if(!empty($params['goods_id'])){
$goods_array = [];
$goods_array2 = [];
for($i = 0 ; $i < count($params['goods_id']); $i++) {
//商品数量大于0才进行出仓
if($params['nums'][$i] > 0){
$find = $stockModel->where('goods_id',$params['goods_id'][$i])->where('stores_id','1')->sum('stock');
//分成都和深圳仓库
if($find > 0){
$goods_array[]=[
'goods_id'=>$params['goods_id'][$i],
'nums'=>$params['nums'][$i],
'unitPrice'=>$params['unitPrice'][$i],
];
}else{
$goods_array2[]=[
'goods_id'=>$params['goods_id'][$i],
'nums'=>$params['nums'][$i],
'unitPrice'=>$params['unitPrice'][$i],
];
}
}
}
}else{
$this->error('该合同没有商品!');
}
$goodsModel = new Goods();
Db::startTrans();
try {
if(!empty($goods_array)){
//添加出仓审批流程
$tmrxyo_data = [
'initiator_id'=>$this->auth->id,
'status'=>1,
'type'=>'1',
'contract_id'=>$row['id'],
];
$tmrxyoModel = new \app\admin\model\fastflow\bill\Tmrxyo();
$tmrxyoModel->save($tmrxyo_data);
$id = $tmrxyoModel->id;
$api = new api(new CustomMessage(), (new Run));
$data4 = [
'bill'=>'ats_tmrxyo',
'bill_id'=>$id,
'ebill_id'=>'',
'flow_id'=>35,
'checkcontent'=>'',
'file_name'=>'',
'file'=>'',
'carbon_scope'=>1,
'carbon_receiver'=>'',
'carbon_range'=>1,
];
$api->startFlow($data4);
//判断当前的出仓数量加上该合同之前的出仓数量是否大于合同的该商品数量
$amodelGoods = new AmodelGoods();
$offer_id= (new \app\admin\model\qingdong\Contract())->where('id',$row['id'])->value('offer_id');
//$price = [];
if($offer_id){
$data = (new Amodela())->where('id',$offer_id)->find();
$json = $this->object_array(json_decode($data['json']));
$inster_data = [];
foreach ($goods_array as $v){
$inster_data[]=[
'amodela_id'=>$offer_id,
'tmrxyo_id'=>$id,
'goods_id'=>$v['goods_id'],
'nums'=>$v['nums'],
'unitPrice'=>$v['unitPrice'],
'status'=>1,
'createtime'=>time()
];
$qty = $amodelGoods->where('goods_id',$v['goods_id'])->where('amodela_id',$offer_id)->where('unitPrice',$v['unitPrice'])->count('nums');
$qty = $v['nums'] + $qty;
foreach ($json as $item){
//$price[$item['productID']] = $item['unitPrice'];
if($item['productID'] == $v['goods_id'] && $item['unitPrice'] == $v['unitPrice']){
if($qty > $item['qty']){
$msg = $item['productName'].'已超出该报价单数量';
throw new Exception($msg);
}
}
}
}
}else{
throw new Exception('查询不到该合同');
}
//添加进销存客户数据
//进销存客户数据
$time = time();
$customer_data = (new Customer())->where('id',$row['customer_id'])->find();
$customer_res = (new Customers())->where('customer_id',$customer_data['id'])->find();
if(!$customer_res){
$codel = (new Customers())->order('id desc')->find();
$code = $this->incrementNumberInString($codel->customer_code);
$customers_data = [
'customertype_id'=>1,
'customerlevel_id'=>1,
'customer_code'=>$code,
'customer_name'=>$customer_data['name'],
'account_time'=>false,
'receive_account'=>'',
'opening_prepayment'=>'',
'identification'=>'',
'deposit_bank'=>'',
'bank_number'=>'',
'staff_member_id'=>'',
'note'=>'',
'need_receive_account'=>0,
'connet_name'=>$customer_data['name'],
'customer_mobile'=>$customer_data['mobile'],
'customer_phone'=>$customer_data['mobile'],
'qq_wx_email'=>'',
'getgoods_address'=>$customer_data['address']??'无',
'createtime'=>$time,
'updatetime'=>$time,
'customer_id'=> $row['customer_id'],
];
$receiving_address = $customer_data['address'];
$sid = Db::name('kuerp_customers')->insertGetId($customers_data);
Db::name('kuerp_sales_payment_log')->insert([
'customers_id' => $sid,
'business_type' => 5,
'bill_time' => $customers_data['account_time'],
'bill_code' => $customers_data['customer_code'],
'give_money' => $customers_data['need_receive_account'],
]);
$customers_user[] = [
'first_connect_name'=>$customer_data['name'],
'first_connect_mobile'=>$customer_data['mobile'],
'first_connect_phone'=>$customer_data['mobile'],
'qq_wx_email'=>'',
'connect_address'=>$customer_data['address']??'无',
'is_first'=>1,
'createtime'=>$time,
'updatetime'=>$time,
'customers_code'=>$code,
'sid'=>$sid,
];
Db::name('kuerp_customers_user')->insertAll($customers_user);
}else{
//$customer_res = (new Customers())->where('customer_id',$customer_data['id'])->find();
$sid = $customer_res['id'];
$receiving_address = $customer_res['getgoods_address'];
}
//销货单
$s_number = 0;
$all_money = 0;
$purchase_code = 'XHD1'.date('YmdHis');
foreach ($inster_data as $item){
$s_number += $item['nums'];
$all_money += $item['unitPrice'] * $item['nums'];
}
foreach ($inster_data as $item){
$goods_allmoney = $item['unitPrice'] * $item['nums'];
$rres = $goodsModel->where('id',$item['goods_id'])->find();
$sales_info_data[] = [
'purchase_code'=>$purchase_code,
'purchase_type'=>'1',
'purchase_time'=>$time,
'customers_id'=>$sid,
'sale_user'=>1,
'receiving_address'=>$receiving_address,
'goods_code'=>$rres['goods_code'],
'goods_note'=>$rres['goods_name'],
'goods_unit'=>$rres['unit_id'],
'stores_id'=>1,
'allow_stock'=>$rres['inventory'],
'order_info_id'=>0,
'number'=>$item['nums'],
'default_unit'=>$rres['unit_id'],
'basic_nmber'=> $item['nums'],
'unit_price'=>$item['unitPrice'],
'cost_price'=>0,
'dis_money'=>0,
'all_money'=>$goods_allmoney,
'remark'=>'',
'goods_attr'=>0,
'tax_included'=>$item['unitPrice'],
'tax_rate'=>0,
'tax_money'=>'',
'money_tax_price'=>$goods_allmoney,
'batch_id'=>'',
'batch_name'=>'',
'manufacture'=>false,
'guarantee'=>'0',
'validity'=>false,
'preferential_rate'=>0,
'preferential_money'=>0,
'real_money'=>$all_money,
'purchase_money'=>0,
'preparation_id'=>$this->auth->id,
'operation_id'=>$this->auth->id,
'pay_status'=>'0',
'pay_money'=>0,
'account'=>0,
'createtime'=>$time,
'updatetime'=>$time,
'purchase_order_id'=>'',
'period'=>null,
'serial_code'=>[],
'goods_batch_info'=>[],
'user_order_info_id'=>[],
];
}
$sales_data = [
'purchase_code'=>$purchase_code,
'purchase_type'=>'1',
'purchase_time'=>$time,
'customers_id'=>$sid,
'sale_user'=>1,
'receiving_address'=>$receiving_address,
'customers_money'=>0,
'number'=>$s_number,
'all_money'=>$all_money,
'tax_money'=>0,
'money_tax_price'=>$all_money,
'preferential_rate'=>0,
'preferential_money'=>0,
'real_money'=>$all_money,
'note'=>'',
'preparation_id'=>$this->auth->id,
'operation_id'=>$this->auth->id,
'arrears'=>$all_money,
'all_arrears'=>$all_money,
'purchase_order_id'=>'',
'pay_status'=>0,
'pay_money'=>0,
'account'=>0,
'cost_data'=>'',
'createtime'=>$time,
'updatetime'=>$time,
'tmrxyo_id'=>$id,
'see_stastus'=>0
];
$GoodsSalesMOdel = new \app\admin\model\kuerp\GoodsSales;
$goodsSales_id = $GoodsSalesMOdel->insertGetId($sales_data);
Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$sales_data['purchase_code']])->delete();
//销货单其他表
foreach ($sales_info_data as $data_k=>$data_v){
$goods_serial = $data_v['serial_code'];
unset($data_v['serial_code']);
$goods_batch_info = $data_v['goods_batch_info'];
unset($data_v['goods_batch_info']);
$user_order_info_id = $data_v['user_order_info_id'];unset($data_v['user_order_info_id']);
$purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v);
if(!empty($user_order_info_id) && !empty($params['order_id'])){
//订货单详情关联表
Db::name('kuerp_user_ordersaleinfo')->insert([
'sales_id' => $goodsSales_id,
'orderinfo_id' => $user_order_info_id,
'salesinfo_id' => $purchase_id,
]);
}
//批次
if($goods_batch_info){
//商品销售批次详情表
$goods_batch_info['purchase_info_id'] = $purchase_id;
Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info);
}
if(!empty($goods_serial)){
//商品序列号
Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
'status'=>'3',
'sale_id' => $purchase_id,
'sale_code' => $data_v['purchase_code']
]);
}
if(!empty($data_v['order_info_id'])){
//销售订单关联
Db::name('kuerp_goods_saleord_info')->insert([
'order_id'=>$data_v['order_info_id'],
'purchase_id'=>$purchase_id,
'number'=>$data_v['number'],
'money'=>$data_v['pay_money'],
'all_money'=>$data_v['all_money'],
'tax_rate'=>$data_v['tax_rate'],
'tax_money'=>$data_v['tax_money'],
'money_tax_price'=>$data_v['money_tax_price']
]);
}
}
foreach ($inster_data as &$item){
$item['sales_id'] = $goodsSales_id;
}
$amodelGoods->insertAll($inster_data);
}
if(!empty($goods_array2)){
//添加出仓审批流程
$tmrxyo_data = [
'initiator_id'=>$this->auth->id,
'status'=>1,
'type'=>'2',
'contract_id'=>$row['id'],
];
$tmrxyoModel = new \app\admin\model\fastflow\bill\Tmrxyo();
$tmrxyoModel->save($tmrxyo_data);
$id = $tmrxyoModel->id;
$api = new api(new CustomMessage(), (new Run));
$data4 = [
'bill'=>'ats_tmrxyo',
'bill_id'=>$id,
'ebill_id'=>'',
'flow_id'=>35,
'checkcontent'=>'',
'file_name'=>'',
'file'=>'',
'carbon_scope'=>1,
'carbon_receiver'=>'',
'carbon_range'=>1,
];
$api->startFlow($data4);
//判断当前的出仓数量加上该合同之前的出仓数量是否大于合同的该商品数量
$amodelGoods = new AmodelGoods();
$offer_id= (new \app\admin\model\qingdong\Contract())->where('id',$row['id'])->value('offer_id');
//$price = [];
if($offer_id){
$data = (new Amodela())->where('id',$offer_id)->find();
$json = $this->object_array(json_decode($data['json']));
$inster_data2 = [];
foreach ($goods_array2 as $v){
$inster_data2[]=[
'amodela_id'=>$offer_id,
'tmrxyo_id'=>$id,
'goods_id'=>$v['goods_id'],
'nums'=>$v['nums'],
'unitPrice'=>$v['unitPrice'],
'status'=>1,
'createtime'=>time()
];
$qty = $amodelGoods->where('goods_id',$v['goods_id'])->where('amodela_id',$offer_id)->where('unitPrice',$v['unitPrice'])->count('nums');
$qty = $v['nums'] + $qty;
foreach ($json as $item){
if($item['productID'] == $v['goods_id'] && $item['unitPrice'] == $v['unitPrice']){
if($qty > $item['qty']){
$msg = $item['productName'].'已超出该报价单数量';
throw new Exception($msg);
}
}
}
}
}else{
throw new Exception('查询不到该合同');
}
//添加进销存客户数据
//进销存客户数据
$time = time();
$customer_data = (new Customer())->where('id',$row['customer_id'])->find();
$customer_res = (new Customers())->where('customer_id',$customer_data['id'])->find();
if(!$customer_res){
$codel = (new Customers())->order('id desc')->find();
$code = $this->incrementNumberInString($codel->customer_code);
$customers_data = [
'customertype_id'=>1,
'customerlevel_id'=>1,
'customer_code'=>$code,
'customer_name'=>$customer_data['name'],
'account_time'=>false,
'receive_account'=>'',
'opening_prepayment'=>'',
'identification'=>'',
'deposit_bank'=>'',
'bank_number'=>'',
'staff_member_id'=>'',
'note'=>'',
'need_receive_account'=>0,
'connet_name'=>$customer_data['name'],
'customer_mobile'=>$customer_data['mobile'],
'customer_phone'=>$customer_data['mobile'],
'qq_wx_email'=>'',
'getgoods_address'=>$customer_data['address']??'无',
'createtime'=>$time,
'updatetime'=>$time,
'customer_id'=> $row['customer_id'],
];
$receiving_address = $customer_data['address'];
$sid = Db::name('kuerp_customers')->insertGetId($customers_data);
Db::name('kuerp_sales_payment_log')->insert([
'customers_id' => $sid,
'business_type' => 5,
'bill_time' => $customers_data['account_time'],
'bill_code' => $customers_data['customer_code'],
'give_money' => $customers_data['need_receive_account'],
]);
$customers_user[] = [
'first_connect_name'=>$customer_data['name'],
'first_connect_mobile'=>$customer_data['mobile'],
'first_connect_phone'=>$customer_data['mobile'],
'qq_wx_email'=>'',
'connect_address'=>$customer_data['address']??'无',
'is_first'=>1,
'createtime'=>$time,
'updatetime'=>$time,
'customers_code'=>$code,
'sid'=>$sid,
];
Db::name('kuerp_customers_user')->insertAll($customers_user);
}else{
$sid = $customer_res['id'];
$receiving_address = $customer_res['getgoods_address'];
}
//销货单
$s_number = 0;
$all_money = 0;
$purchase_code = 'XHD2'.date('YmdHis');
foreach ($inster_data2 as $item){
$s_number += $item['nums'];
$all_money += $item['unitPrice'] * $item['nums'];
}
foreach ($inster_data2 as $item){
$goods_allmoney = $item['unitPrice'] * $item['nums'];
$rres = $goodsModel->where('id',$item['goods_id'])->find();
$sales_info_data2[] = [
'purchase_code'=>$purchase_code,
'purchase_type'=>'1',
'purchase_time'=>$time,
'customers_id'=>$sid,
'sale_user'=>1,
'receiving_address'=>$receiving_address,
'goods_code'=>$rres['goods_code'],
'goods_note'=>$rres['goods_name'],
'goods_unit'=>$rres['unit_id'],
'stores_id'=>1,
'allow_stock'=>$rres['inventory'],
'order_info_id'=>0,
'number'=>$item['nums'],
'default_unit'=>$rres['unit_id'],
'basic_nmber'=> $item['nums'],
'unit_price'=>$item['unitPrice'],
'cost_price'=>0,
'dis_money'=>0,
'all_money'=>$goods_allmoney,
'remark'=>'',
'goods_attr'=>0,
'tax_included'=>$item['unitPrice'],
'tax_rate'=>0,
'tax_money'=>'',
'money_tax_price'=>$goods_allmoney,
'batch_id'=>'',
'batch_name'=>'',
'manufacture'=>false,
'guarantee'=>'0',
'validity'=>false,
'preferential_rate'=>0,
'preferential_money'=>0,
'real_money'=>$all_money,
'purchase_money'=>0,
'preparation_id'=>$this->auth->id,
'operation_id'=>$this->auth->id,
'pay_status'=>'0',
'pay_money'=>0,
'account'=>0,
'createtime'=>$time,
'updatetime'=>$time,
'purchase_order_id'=>'',
'period'=>null,
'serial_code'=>[],
'goods_batch_info'=>[],
'user_order_info_id'=>[],
];
}
$sales_data = [
'purchase_code'=>$purchase_code,
'purchase_type'=>'1',
'purchase_time'=>$time,
'customers_id'=>$sid,
'sale_user'=>1,
'receiving_address'=>$receiving_address,
'customers_money'=>0,
'number'=>$s_number,
'all_money'=>$all_money,
'tax_money'=>0,
'money_tax_price'=>$all_money,
'preferential_rate'=>0,
'preferential_money'=>0,
'real_money'=>$all_money,
'note'=>'',
'preparation_id'=>$this->auth->id,
'operation_id'=>$this->auth->id,
'arrears'=>$all_money,
'all_arrears'=>$all_money,
'purchase_order_id'=>'',
'pay_status'=>0,
'pay_money'=>0,
'account'=>0,
'cost_data'=>'',
'createtime'=>$time,
'updatetime'=>$time,
'tmrxyo_id'=>$id,
'see_stastus'=>0
];
$GoodsSalesMOdel = new \app\admin\model\kuerp\GoodsSales;
$goodsSales_id = $GoodsSalesMOdel->insertGetId($sales_data);
Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$sales_data['purchase_code']])->delete();
//销货单其他表
foreach ($sales_info_data2 as $data_k=>$data_v){
$goods_serial = $data_v['serial_code'];
unset($data_v['serial_code']);
$goods_batch_info = $data_v['goods_batch_info'];
unset($data_v['goods_batch_info']);
$user_order_info_id = $data_v['user_order_info_id'];unset($data_v['user_order_info_id']);
$purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v);
if(!empty($user_order_info_id) && !empty($params['order_id'])){
//订货单详情关联表
Db::name('kuerp_user_ordersaleinfo')->insert([
'sales_id' => $goodsSales_id,
'orderinfo_id' => $user_order_info_id,
'salesinfo_id' => $purchase_id,
]);
}
//批次
if($goods_batch_info){
//商品销售批次详情表
$goods_batch_info['purchase_info_id'] = $purchase_id;
Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info);
}
if(!empty($goods_serial)){
//商品序列号
Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
'status'=>'3',
'sale_id' => $purchase_id,
'sale_code' => $data_v['purchase_code']
]);
}
if(!empty($data_v['order_info_id'])){
//销售订单关联
Db::name('kuerp_goods_saleord_info')->insert([
'order_id'=>$data_v['order_info_id'],
'purchase_id'=>$purchase_id,
'number'=>$data_v['number'],
'money'=>$data_v['pay_money'],
'all_money'=>$data_v['all_money'],
'tax_rate'=>$data_v['tax_rate'],
'tax_money'=>$data_v['tax_money'],
'money_tax_price'=>$data_v['money_tax_price']
]);
}
}
foreach ($inster_data2 as &$item){
$item['sales_id'] = $goodsSales_id;
}
$amodelGoods->insertAll($inster_data2);
}
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success();
}
$find = (new \addons\antis\model\Contract())->where('id',$ids)->find();
$data = (new Amodela())->where('id',$find['offer_id'])->find();
if($data){
$json = json_decode($data['json']);
$json = $this->object_array($json);
}
$amodelGoods = new AmodelGoods();
foreach ($json as &$item){
$count = $amodelGoods->where('amodela_id',$find['offer_id'])->where('goods_id',$item['productID'])->count('nums')??0;
$item['surplus'] = $item['qty'] - $count;
}
//halt($json);
$this->assign('row', $json);
return $this->view->fetch('tmrxyo');
}
public function incrementNumberInString($input) {
// 使用正则表达式匹配前面是大写英文,后面是数字的部分
preg_match('/([A-Z]+)(\d+)/', $input, $matches);
$letters = $matches[1];
$number = (int)$matches[2];
// 将数字加1
$newNumber = $number + 1;
$result = str_pad($newNumber, 3, '0', STR_PAD_LEFT);
// 重新组合
return $letters . $result;
}
/**
* 添加
*/
public function add()
{
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$result = FormField::checkFields(FormField::CONTRACT_TYPE, $params);
if ($result !== true) {
$this->error($result);
}
$result = false;
Db::startTrans();
try {
//halt($params);
$params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);
//halt($params);
$result = $this->model::createContract($params);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
//$this->success('','admin\fastflow/flow/run/start?bill=ats_xtuqll&bill_id='.$result);
//$this->redirect('admin\fastflow/flow/run/start?bill=ats_xtuqll&bill_id='.$result);
//
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$flow= Flow::getsteplist(Flow::CONTRACT_STATUS);
//if (empty($flow)) {
// $this->error('无可用审批流,请联系管理员','antis/work/flow');
//}
$customer_id = input('customer_id');
if($customer_id){
$business = Business::where(array('customer_id'=>$customer_id))->select();
}else{
$business = Business::getList();
}
$bus_ids = (new \app\admin\model\qingdong\Business())->where('create_staff_id',$this->auth->id)->column('id');
$bill_ids = (new Czgprz())->where('status',2)->column('id');
$bill = (new Amodela())->where('business_id','in',$bus_ids)->where('bill_id','in',$bill_ids)->field('id,name')->select();
$staff = Staff::info();
//halt($customer_id);
$mainbody = (new Mainbody())->select();
$this->assign('mainbody',$mainbody);
$this->assign('flow',$flow);
$this->assign('bill', $bill);
$this->assign('staff', Staff::getStaff());
$this->assign('customers', Customer::getList());
$this->assign('business', $business);
$this->assign('businesss', Business::get(input('business_id')));
$this->assign('customer', Customer::get($customer_id));
$this->assign('customer_id', $customer_id);
$this->assign('business_id', input('business_id'));
$this->assign('staffs', Staff::allList());
$this->assign('order_staff_id',$staff->id);
$this->assign('form_data', Form::getDataValue('contract'));
$this->assign('ratio',Ratio::where(['status'=>1])->select());
$this->assign('contractNum', 'C'.date('Ymd').rand(10000,99999));
return $this->view->fetch();
}
public function Billselectpage(){
$param = $this->request->param();
// ids = 项目 business_id;未选项目时可传 customer_id,列出该客户下所有项目的报价单(含用友关联的 amodel_a)
$businessIds = [];
if (!empty($param['ids'])) {
$businessIds = [intval($param['ids'])];
} elseif (!empty($param['customer_id'])) {
$businessIds = Business::where('customer_id', intval($param['customer_id']))->column('id');
}
if (empty($businessIds)) {
return json(array("total" => 0, "rows" => []));
}
$amodel = (new Amodela())->field('id,bill_id,name')->select();
$arr = [];
foreach ($amodel as $v){
// 判断是否是用友集成的报价单(通过 name 字段中包含 quotation_ 标记)
$isYongyouQuotation = false;
if (isset($v['name']) && strpos($v['name'], '(quotation_') !== false) {
$isYongyouQuotation = true;
}
if($isYongyouQuotation){
// 用友集成的报价单,直接包含(bill_id 可能为 0 或 null)
$arr[] = $v['id'];
} elseif($v['bill_id'] != '0' && $v['bill_id'] != null){
// PHP项目的报价单,需要检查状态
$status = (new Czgprz())->where('id' ,$v['bill_id'] )->where('status',2)->value('status');
if($status == 2){
$arr[] = $v['id'];
}
}else{
// bill_id 为 0 或 null 但不是用友集成的,可能是其他类型,也包含
$arr[] = $v['id'];
}
}
// 根据 business_id 筛选,只返回与当前项目关联的报价单
// 支持模糊搜索(通过 name 字段)
$searchName = $param['name'] ?? '';
$pageNumber = isset($param['pageNumber']) ? intval($param['pageNumber']) : 1;
$pageSize = isset($param['pageSize']) ? intval($param['pageSize']) : 10;
// 确保至少显示10条
if ($pageNumber == 1 && $pageSize < 10) {
$pageSize = 10;
}
$model = (new Amodela())
->where('business_id', 'in', $businessIds)
->where('id', 'in', $arr);
if (!empty($searchName)) {
$model->where('name', 'LIKE', '%' . $searchName . '%');
}
$count = $model->count();
$list = (new Amodela())
->where('business_id', 'in', $businessIds)
->where('id', 'in', $arr);
if (!empty($searchName)) {
$list->where('name', 'LIKE', '%' . $searchName . '%');
}
$list = $list->order('createtime', 'desc') // 按创建时间倒序排列
->page($pageNumber, $pageSize)
->select();
$result = array("total" => $count, "rows" => $list);
return json($result);
}
/**
* 获取报价单金额(通过调用用友集成API)
*/
public function getQuotationAmount() {
$this->applyCrmJsonCorsHeaders();
$amodel_a_id = input('amodel_a_id/d', 0);
if (!$amodel_a_id) {
return json(['code' => 0, 'msg' => '参数错误', 'data' => null]);
}
$amodel = (new \addons\qingdong\model\Amodela())->where('id', $amodel_a_id)->find();
if (!$amodel) {
return json(['code' => 0, 'msg' => '报价单记录不存在', 'data' => null]);
}
// 从 name 中解析 quotation_id
$name = $amodel['name'] ?? '';
if (!preg_match('/\(quotation_(\d+)\)/', $name, $matches)) {
return json(['code' => 0, 'msg' => '未找到用友报价单ID', 'data' => null]);
}
$quotation_id = $matches[1];
// 调用用友集成API获取报价单详情
$apiUrl = 'http://localhost:5002/api/Yongyou/Actions/GetQuotation/' . $quotation_id;
$response = @file_get_contents($apiUrl);
if ($response === false) {
return json(['code' => 0, 'msg' => '获取报价单信息失败', 'data' => null]);
}
$data = json_decode($response, true);
if (!$data || !isset($data['data'])) {
return json(['code' => 0, 'msg' => '解析报价单数据失败', 'data' => null]);
}
$quotationData = $data['data'];
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'totalAmount' => $quotationData['totalAmount'] ?? 0,
'totalAmountInWords' => $quotationData['totalAmountInWords'] ?? ''
]
]);
}
/**
* Vue 开发 (:5001) 直连 CRM PHP (:8000) 时的 CORS 与 OPTIONS。
*/
protected function applyCrmJsonCorsHeaders()
{
header('Content-Type: application/json; charset=utf-8');
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');
}
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
}
/**
* 获取合同的报价单ID(offer_id)
*/
public function get_contract_offer_id() {
$this->applyCrmJsonCorsHeaders();
$ids = input('ids');
if (empty($ids)) {
return json(['code' => 0, 'msg' => '合同ID不能为空', 'data' => null]);
}
$contract = $this->model->where('id', $ids)->find();
if (!$contract) {
return json(['code' => 0, 'msg' => '合同不存在', 'data' => null]);
}
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'offer_id' => $contract->offer_id
]
]);
}
/**
* 获取合同详情(包括合同编号)
*/
public function get_contract_detail() {
$this->applyCrmJsonCorsHeaders();
$ids = input('ids');
if (empty($ids)) {
return json(['code' => 0, 'msg' => '合同ID不能为空', 'data' => null]);
}
$contract = $this->model->where('id', $ids)->with(['business'])->find();
if (!$contract) {
return json(['code' => 0, 'msg' => '合同不存在', 'data' => null]);
}
$businessName = $this->resolveContractBusinessDisplayName($contract);
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'id' => $contract->id,
'num' => $contract->num,
'name' => $contract->name,
'offer_id' => $contract->offer_id,
'business_id' => $contract->business_id,
'business_name' => $businessName
]
]);
}
/**
* 解析合同对应的「项目名称」:优先 CRM 商机名称;合同未绑商机时从关联报价单 amodel_a.business_name 读取(与 save_quotation_link 写入一致)。
* @param \addons\qingdong\model\Contract $contract
*/
protected function resolveContractBusinessDisplayName($contract)
{
try {
if ($contract->business && !empty($contract->business->name)) {
return trim((string)$contract->business->name);
}
$bid = isset($contract->business_id) ? $contract->business_id : null;
if (!empty($bid)) {
$n = \addons\qingdong\model\Business::where('id', $bid)->value('name');
if ($n !== null && $n !== '') {
return trim((string)$n);
}
}
$oid = isset($contract->offer_id) ? $contract->offer_id : null;
if (!empty($oid)) {
$amodelRow = (new Amodela())->where('id', $oid)->find();
$hint = $this->resolveBusinessHintFromAmodelRow($amodelRow);
if (($hint['business_name'] ?? '') !== '') {
return $hint['business_name'];
}
}
} catch (\Throwable $e) {
\think\Log::write('resolveContractBusinessDisplayName: ' . $e->getMessage(), 'warning');
}
return '';
}
/**
* amodel_a 一行上的商机显示名(business_name 或关联 qingdong_business.name)。
*
* @param object|null $amodelRow
* @return array{business_name: string, business_id: mixed|null}
*/
protected function resolveBusinessHintFromAmodelRow($amodelRow)
{
if (!$amodelRow) {
return ['business_name' => '', 'business_id' => null];
}
try {
$bizName = trim((string)($amodelRow->business_name ?? ''));
$abid = isset($amodelRow->business_id) ? $amodelRow->business_id : null;
if ($bizName === '' && !empty($abid)) {
$n = \addons\qingdong\model\Business::where('id', $abid)->value('name');
if ($n !== null && $n !== '') {
$bizName = trim((string)$n);
}
}
return ['business_name' => $bizName, 'business_id' => $abid];
} catch (\Throwable $e) {
\think\Log::write('resolveBusinessHintFromAmodelRow: ' . $e->getMessage(), 'warning');
}
return ['business_name' => '', 'business_id' => null];
}
/**
* 关联报价单行(amodel_a)上的商机摘要:销售订单表头「项目名称」兜底;
* 兼容 get_contract_detail 仅返回旧字段(仅有 offer_id)时仍能带出商机名称。
*/
public function get_offer_business_hint()
{
$this->applyCrmJsonCorsHeaders();
$offer_id = input('offer_id');
if ($offer_id === null || $offer_id === '') {
return json(['code' => 0, 'msg' => '报价单关联ID(offer_id)不能为空', 'data' => null]);
}
try {
$amodelRow = (new Amodela())->where('id', $offer_id)->find();
if (!$amodelRow) {
return json(['code' => 0, 'msg' => '报价单行不存在', 'data' => null]);
}
$hint = $this->resolveBusinessHintFromAmodelRow($amodelRow);
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'business_name' => $hint['business_name'],
'business_id' => $hint['business_id'],
],
]);
} catch (\Throwable $e) {
\think\Log::write('get_offer_business_hint: ' . $e->getMessage(), 'error');
return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null]);
}
}
/**
* 从 offer_id(amodel_a表的ID)获取用友集成的报价单ID
* 如果报价单是用友集成的,name字段包含 (quotation_数字),提取其中的 quotation_id
* 同时返回 amodel_a 上的商机摘要(业务上作为销售订单「项目名称」),无需单独调 get_offer_business_hint(线上已存在本接口)。
*/
public function get_quotation_id_from_offer() {
$this->applyCrmJsonCorsHeaders();
$offer_id = input('offer_id');
if (empty($offer_id)) {
return json(['code' => 0, 'msg' => '报价单ID不能为空', 'data' => null]);
}
$amodela = (new Amodela())->where('id', $offer_id)->find();
if (!$amodela) {
return json(['code' => 0, 'msg' => '报价单不存在', 'data' => null]);
}
$offerBizHint = $this->resolveBusinessHintFromAmodelRow($amodela);
$quotationId = null;
// 判断是否是用友集成的报价单(通过 name 字段中包含 quotation_ 标记)
if (isset($amodela->name) && strpos($amodela->name, '(quotation_') !== false) {
// 提取 quotation_id
if (preg_match('/\(quotation_(\d+)\)/', $amodela->name, $matches)) {
$quotationId = $matches[1];
}
}
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'quotation_id' => $quotationId,
'is_yongyou' => !empty($quotationId),
'offer_id' => $offer_id,
'business_name' => $offerBizHint['business_name'],
'business_id' => $offerBizHint['business_id'],
]
]);
}
/**
* 搜索合同列表(用于下拉框选择,无需认证)
*/
public function search_contracts() {
// 立即设置响应头为 JSON,避免 ThinkPHP 输出 HTML 错误页面
header('Content-Type: application/json; charset=utf-8');
// 处理 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;
}
// 使用 ob_start 捕获所有输出,确保只返回 JSON
ob_start();
try {
// 确保模型已初始化
if (!$this->model) {
$this->model = new \addons\qingdong\model\Contract;
}
$name = input('name', '');
$num = input('num', ''); // 支持按合同编号搜索
$pageNumber = input('pageNumber', 1);
$pageSize = input('pageSize', 20);
$where = [];
if (!empty($name)) {
$where['name'] = ['like', '%' . $name . '%'];
}
// 如果提供了合同编号,优先按合同编号精确匹配
if (!empty($num)) {
$where['num'] = $num;
}
// 查询所有状态的合同(包括待审核、已审核通过等),以便在销售订单中可以选择
// 不再限制 check_status,让用户可以选择任意状态的合同
$list = $this->model
->where($where)
->with(['customer', 'business'])
->order('id desc')
->page($pageNumber, $pageSize)
->select();
$count = $this->model->where($where)->count();
// 格式化返回数据
$rows = [];
foreach ($list as $contract) {
$bizDisplay = $this->resolveContractBusinessDisplayName($contract);
$bid = isset($contract->business_id) ? $contract->business_id : null;
$rows[] = [
'id' => $contract->id,
'name' => $contract->name,
'num' => $contract->num,
'customer' => $contract->customer ? [
'id' => $contract->customer->id,
'name' => $contract->customer->name
] : null,
'business' => ($bizDisplay !== '') ? [
'id' => $bid,
'name' => $bizDisplay
] : null,
'business_name' => $bizDisplay,
'offer_id' => $contract->offer_id,
'money' => $contract->money
];
}
ob_clean();
echo json_encode([
'total' => $count,
'rows' => $rows
], JSON_UNESCAPED_UNICODE);
exit;
} catch (\Exception $e) {
\think\Log::write('search_contracts 异常: ' . $e->getMessage() . ' | 文件: ' . $e->getFile() . ' | 行号: ' . $e->getLine(), 'error');
ob_clean();
header('Content-Type: application/json; charset=utf-8');
http_response_code(200);
echo json_encode([
'total' => 0,
'rows' => [],
'error' => '查询合同失败:' . $e->getMessage()
], JSON_UNESCAPED_UNICODE);
exit;
} catch (\Throwable $e) {
\think\Log::write('search_contracts 致命错误: ' . $e->getMessage() . ' | 文件: ' . $e->getFile() . ' | 行号: ' . $e->getLine(), 'error');
ob_clean();
header('Content-Type: application/json; charset=utf-8');
http_response_code(200);
echo json_encode([
'total' => 0,
'rows' => [],
'error' => '查询合同失败:' . $e->getMessage()
], JSON_UNESCAPED_UNICODE);
exit;
} finally {
// 清理输出缓冲区
if (ob_get_level() > 0) {
ob_end_flush();
}
}
}
/**
* 修改合同
*/
public function edit($ids = null) {
$map['id'] = $ids;
if ($this->request->isAjax()) {
$params = $this->request->post('row/a');
$params = $this->preExcludeFields($params);
$row = $this->model::where(['id' => $ids, 'check_status' => ['in', [3, 4]]])->find();
if (empty($row)) {
$this->error('合同审核中或已审核通过无法修改');
}
// 表单验证
if (($result = $this->qingdongValidate($params, 'Contract', 'create')) !== true) {
$this->error($result);
}
$result = FormField::checkFields(FormField::CONTRACT_TYPE, $params,$ids);
if ($result !== true) {
$this->error($result);
}
Db::startTrans();
try {
$params = Form::updateFormParams(Form::CONTRACT_TYPE, $params);
$params['id']=$ids;
$params['owner_staff_id'] = $row['owner_staff_id'];
if($params['product']){
$params['product']=json_decode($params['product'],true);
}
$result = $this->model::updateContract($params);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success('修改成功');
}
$row = $this->model->where($map)->with(['customer','contacts','business'])->find();
if(empty($row)){
$this->error('信息不存在');
}
$row = $row->toArray();
$row = ContractOther::getOther($row);
$product=ContractProduct::where(['contract_id'=>$ids])->with(['productinfo'])->select();
foreach ($product as $k=>$v){
if($v['productinfo']){
$v['product_name']=$v['productinfo']['name'];
$v['cost_price']=$v['productinfo']['cost_price'];
$v['type']=$v['productinfo']['type'];
if($v['productinfo']['goods']){
$v['goods_name']=$v['productinfo']['goods']['name'];
}
}
$product[$k]=$v;
}
$row['product']=json_encode($product);
$row['ratios']=json_decode($row['ratios'],true);
$flow= Flow::getsteplist(Flow::CONTRACT_STATUS);
//if (empty($flow)) {
// $this->error('无可用审批流,请联系管理员','antis/work/flow');
//}
$this->assign('flow',$flow);
$this->view->assign("row", $row);
$this->assign('customers', Customer::getList());
$this->assign('business', Business::getList());
$this->assign('staffs', Staff::getList());
$this->assign('staff', Staff::getStaff());
$this->assign('ratio',Ratio::where(['status'=>1])->select());
$this->assign('form_data', Form::getDataValue('contract',$row));
$this->assign('contacts', Contacts::where(['customer_id'=>$row['customer_id']])->field('id,name')->select());
return $this->view->fetch();
}
///**
// * 获取附件记录
// */
//public function get_file($ids = null) {
// list($where, $sort, $order, $offset, $limit) = $this->buildparams();
// $list = ContractFile::where(['contract_id' => $ids])->with(['file'])->field('file_id')->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 = Invoice::where(['contract_id' => $ids])->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 合同详情
*/
public function detail($ids = null) {
$row = $this->model->where(['id' => $ids])->with([
'customer',
'contacts',
'orderStaff',
'ownerStaff',
'business'
])->find();
if (empty($row)) {
$this->error(__('No Results were found'));
}
$row=$row->toArray();
$row=ContractOther::getOther($row);
$row['ratios'] = json_decode($row['ratios'], true);
if ($row['ratios']) {
foreach ($row['ratios'] as $k => $v) {
$v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
$v['money'] = $row['money'] * ($v['ratio'] / 100);
$row['ratios'][$k] = $v;
}
}
$row['repayment_money'] = Receivables::where(['contract_id'=>$ids])->sum('money'); //已回款
$row['no_money'] = $row['money'] -$row['repayment_money'];
if($row['no_money'] <= 0){
$row['no_money'] = 0;
}
// 关联报价单(amodel_a.offer_id):用于详情页展示,逻辑与 get_quotation_id_from_offer / get_business_bill 一致
$quotation_info = [
'has_offer' => false,
'offer_id' => null,
'offer_name' => '',
'offer_name_display' => '',
'is_yongyou' => false,
'quotation_id' => null,
'view_url' => '',
];
if (!empty($row['offer_id'])) {
$amodela = (new Amodela())->where('id', $row['offer_id'])->find();
if ($amodela) {
$amodelaArr = $amodela->toArray();
$name = isset($amodelaArr['name']) ? (string)$amodelaArr['name'] : '';
$quotation_info['has_offer'] = true;
$quotation_info['offer_id'] = $amodelaArr['id'];
$quotation_info['offer_name'] = $name;
$display = preg_replace('/\s*\(quotation_\d+\)\s*$/u', '', $name);
$quotation_info['offer_name_display'] = trim($display) !== '' ? trim($display) : $name;
if ($name !== '' && strpos($name, '(quotation_') !== false && preg_match('/\(quotation_(\d+)\)/', $name, $matches)) {
$quotation_info['is_yongyou'] = true;
$quotation_info['quotation_id'] = $matches[1];
$quotation_info['view_url'] = get_yongyou_integration_full_url('quotation', ['id' => $matches[1], 'mode' => 'view']);
}
}
}
$this->assign('quotation_info', $quotation_info);
$this->assign('examine_record',ExamineRecord::getList(ExamineRecord::CONTRACT_TYPE,$ids));
$this->assign('flow',Flow::getstepdetail(Flow::CONTRACT_STATUS, $ids));
//跟进记录
$this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
//操作记录
$log=OperationLog::getList(OperationLog::CONTRACT_TYPE, $ids);
$this->assign('operation_log',$log);
$this->assign('row', $row);
$this->assign('ids', $ids);
$this->assign('form_data', Form::getDataValue('contract',$row));
$this->assignconfig("idinfo", ['id' => $ids]);
return $this->view->fetch();
}
/**
* 获取联系人select
*/
public function get_contacts_list(){
$pageSize = input('pageSize');
$pageNumber = input('pageNumber');
$where = [];
if ($keyValue = $this->request->request("keyValue")) {
$where['id'] = ['in',$keyValue];
}
$ids=input('ids');
$name = input('name');
if(!empty($name)){
$where['name'] = ['like','%'.$name.'%'];
}
$staff = Contacts::where($where)->where(['customer_id'=>$ids])
->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
return json(['list' => $staff->items(), 'total' => $staff->total()]);
}
/**
* 获取产品明细
*/
public function get_contract_product(){
$contract_id=input('contract_id',0,'intval');
if(empty($contract_id)){
$this->error('参数不能为空');
}
$products=ContractProduct::where(['contract_id'=>$contract_id])
->with(['productinfo'])->select();
foreach($products as $k=>$v){
if(!$v['productinfo']['id']){
unset($products[$k]);
}
}
return json(['rows' =>$products, 'total' => count($products)]);
}
/**
* 获取回款计划
*/
public function get_receivables_plan($ids = null) {
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = \addons\antis\model\ReceivablesPlan::where([
'contract_id' => $ids
])->with(['customer'])->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 = \addons\antis\model\Receivables::where([
'contract_id' => $ids
])->with(['customer','ownerStaff'])->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
/**
* 获取商机关联产品
*/
public function get_business_product(){
$business_id=input('business_id');
if(empty($business_id)){
$this->error('参数不能为空');
}
$business=BusinessProduct::where(['business_id'=>$business_id])->with(['productinfo'])->select();
$this->success('请求成功','',$business);
}
/**
* 获取产品
*/
public function get_product()
{
$where = [];
if ($keyValue = $this->request->request("keyValue")) {
$where['id'] = $keyValue;
}
$name = input('name');
if(!empty($name)){
$where['name'] = ['like','%'.$name.'%'];
}
$countrys = Product::where($where)->field('id,name')->order('id desc')->select();
return json(['list' => $countrys, 'total' => count($countrys)]);
}
/**
* 获取产品配置
*/
public function get_product_part()
{
$where = [];
if ($keyValue = $this->request->request("keyValue")) {
$where['id'] = $keyValue;
}
$name = input('name');
if(!empty($name)){
$where['name'] = ['like','%'.$name.'%'];
}
$countrys = ProductPart::where($where)->field('id,name')->order('id desc')->select();
return json(['list' => $countrys, 'total' => count($countrys)]);
}
/**
* 获取产品价格
*/
public function get_product_price()
{
$id = input('id', 0);
$price = Product::where(['id' => $id])->value('price') ?? 0;
$this->success('请求成功', '', ['price' => $price]);
}
/**
* 获取审批人列表
*/
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)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
return json(['list' => $staff->items(), 'total' => $staff->total()]);
}
/**
* 删除
*/
public function del($ids = "") {
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$map['id'] = array('in', $ids);
$result = $this->model->destroy($map);
if (!$result) {
$this->error('删除失败');
}
$this->success('删除成功');
}
/**
* 导入合同
* @return string|void
*/
public function import()
{
set_time_limit(0);
if ($this->request->isPost()) {
$file = $this->request->request('file');
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) ? NULL : trim($val);
}
}
if (!isset($fields[1])) {
$this->error('导入文件第一行没有数据');
}
$lastid = $this->model->withTrashed()->order('id desc')->value('id');
$lastid = $lastid + 5;//防止重复
$contractRow = [];
$errorInfo = [];
$fieldnames = FormField::where(['types' => FormField::CONTRACT_TYPE])->column('field', 'name');
if(!$fieldnames){
$this->error('请在系统管理->字段管理中保存合同管理表单生成合同导入字段');
}
$customerNames=Customer::where([])->column('id,owner_staff_id','name');
$contacts = Contacts::where([])->field('id,name,customer_id')->select();
$contacts = collection($contacts)->toArray();
$contactsNames = [];
foreach ($contacts as $v) {
$contactsNames[$v['customer_id']][$v['name']] = $v;
}
$businessNames=Business::where([])->column('id','name');
$staffNames=Staff::where([])->column('id','name');
$fn = [];
$nums=$this->model->where([])->column('num');
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++;
$addContract = ['id' => $lastid];
$customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0;
if(empty($customer)){
$errorInfo[] = "第{$currentRow}行,客户名称不存在;";
continue;
}
$addContract['customer_id']=$customer['id'];
$addContract['owner_staff_id']=$customer['owner_staff_id'];
$addContract['create_staff_id']=$customer['owner_staff_id'];
$contacts = isset($contactsNames[$addContract['customer_id']])?(isset($contactsNames[$addContract['customer_id']][$values[1]]) ? $contactsNames[$addContract['customer_id']][$values[1]] : []):[];
if (!empty($values[1]) && empty($contacts)) {
$errorInfo[] = "第{$currentRow}行,客户签约人名称不存在;";
continue;
}
$addContract['contacts_id']=$contacts['id']??0;
$business=isset($businessNames[$values[2]])?$businessNames[$values[2]]:[];
if (!empty($values[2]) && empty($business)) {
$errorInfo[] = "第{$currentRow}行,商机名称不存在;";
continue;
}
$addContract['business_id']=$business['id']??0;
$orderstaff=isset($staffNames[$values[3]])?$staffNames[$values[3]]:[];
if (!empty($values[3]) && empty($orderstaff)) {
$errorInfo[] = "第{$currentRow}行,商机名称不存在;";
continue;
}
$addContract['order_staff_id']=$orderstaff['id']??0;
foreach ($values as $kv => $value) {
if (!isset($fn[$kv]) || empty($fn[$kv])) {
continue;
}
$addContract[$fn[$kv]] = $value;
}
if (empty($addContract['num'])) {
$errorInfo[] = "第{$currentRow}行,合同编号不能为空;";
continue;
}
if (in_array($addContract['num'], $nums)) {
$errorInfo[] = "第{$currentRow}行,合同编号`{$addContract['num']}`已存在;";
continue;
}
if (empty($addContract['name'])) {
$errorInfo[] = "第{$currentRow}行,合同名称不能为空;";
continue;
}
$contractRow[] = $addContract;
}
if (!empty($errorInfo)) {
$this->error(implode(',', $errorInfo));
}
Db::startTrans();
try {
$this->model::importContract($contractRow);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success('导入成功');
}
$this->assign('staffs', Staff::getList());
return $this->view->fetch();
}
/**
* 模板
*/
public function template()
{
$title = [
'客户名称',
'客户签约人',
'商机名称',
'公司签约人',
];
$contractData = Form::getDataValue(Form::CONTRACT_TYPE);
foreach ($contractData 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);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
switch($type){
case 1:
$staff = Staff::info();
$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'=>3,'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'=>3,'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'=>3,'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;
}
$list = $this->model->with([
'customer',
'orderStaff',
'contacts',
'ownerStaff','contractOther',
])->where($where)->where($wheres)->order($sort, $order)->select();
$list = collection($list)->toArray();
if (!$list) {
$this->error('无导出数据');
}
$title = [
'序号',
'客户名称',
'客户签约人',
'公司签约人',
'归属人',
'创建时间',
];
$dataValue = Form::getDataValue(Form::CONTRACT_TYPE);
foreach ($dataValue as $val) {
$title[] = $val['config']['label'];
}
foreach ($list as $k => $v) {
if($v['contract_other']){//其他客户
$other=$v['contract_other']['otherdata'];
$other=json_decode($other,true);
$v = array_merge($v, $other);
}
$field = array(
$v['id'],
$v['customer']['name'],
$v['contacts']['name']??'',
$v['order_staff']['name']??'',
$v['owner_staff']['name']??'',
$v['createtime'],
);
foreach ($dataValue as $val) {
if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
$field[] = $v[$val['id'] . '_str'] ?? '';
} else {
$field[] = ($v[$val['id']] ?? '');
}
}
$data[] = $field;
}
$file = export_excel($title, $data, '合同');
if ($file['filePath']) {
$this->success('导出成功', '', $file);
}
$this->error('导出失败');
}
/**
* 导入产品明细
* @return string|void
*/
public function import_product()
{
set_time_limit(0);
if ($this->request->isPost()) {
$file = $this->request->request('file');
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 = ContractProduct::order('id desc')->value('id');
$lastid = $lastid + 5;//防止重复
$contractProductRow = [];
$errorInfo = [];
$contractNum=$this->model::where([])->column('id,name','num');
$productName=Product::where([])->column('id,price','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;
}
}
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++;
$addContractProduct = ['id' => $lastid];
$contract = isset($contractNum[$values[0]]) ? $contractNum[$values[0]] : 0;
if (empty($contract)) {
$errorInfo[] = "第{$currentRow}行,合同编号不存在;";
continue;
}
$product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0;
if (empty($product)) {
$errorInfo[] = "第{$currentRow}行,产品名称不存在;";
continue;
}
if (empty($values[2])) {
$errorInfo[] = "第{$currentRow}行,产品数量不能为空;";
continue;
}
if (empty($values[3])) {
$errorInfo[] = "第{$currentRow}行,产品售价不能为空;";
continue;
}
$addContractProduct['contract_id'] = $contract['id'];
$addContractProduct['product_id'] = $product['id'];
$addContractProduct['number'] = $values[2];
$addContractProduct['price'] = $values[3];
$contractProductRow[]=$addContractProduct;
}
if (!empty($errorInfo)) {
$this->error(implode(',', $errorInfo));
}
Db::startTrans();
try {
ContractProduct::importProduct($contractProductRow);
Db::commit();
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
$this->success('导入成功');
}
$this->assign('staffs', Staff::getList());
return $this->view->fetch();
}
/**
* 模板
*/
public function template_product()
{
$title = [
'合同编号',
'商品名称',
'数量',
'售价',
];
$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_product()
{
$ids = input('ids');
$type = input('type');
$wheres = array();
//导出其中几条
if (isset($ids)) {
$wheres['contract_id'] = array('in', $ids);
}
//导出全部
if (isset($type)) {
if ($type == 3) {
unset($wheres['contract_id']);
}
}
$list=ContractProduct::where($wheres)->with(['contract','productinfo'])->select();
$list = collection($list)->toArray();
if (!$list) {
$this->error('无导出数据');
}
$title = [
'序号',
'合同编号',
'合同名称',
'商品名称',
'售价',
'批发价',
'产品',
'规格',
'数量',
];
$data=[];
foreach ($list as $k => $v) {
$field = array(
$v['id'],
$v['contract']['num'],
$v['contract']['name'],
$v['productinfo']['name']??'',
$v['price']??'',
$v['productinfo']['cost_price']??'',
$v['productinfo']['goods']['name']??'',
$v['productinfo']['unit']??'',
$v['number']??'',
);
$data[] = $field;
}
$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'=>'contract',
'name'=>$template_name,
'url'=>$file
];
$wordTemplateModel = new WordTemplate();
$wordTemplateModel->save($create);
}
$tmp = new TemplateProcessor('.' . $file);
Settings::setCompatibility(true);
Settings::setOutputEscapingEnabled(true);
$row = $this->model->where(['id'=>$ids])->with(['customer','contacts','business','orderStaff'])->find();
$row = $row->toArray();
$row = ContractOther::getOther($row);
$form = Form::getDataValue(Form::CONTRACT_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);//
}
}
$contractProduct=ContractProduct::where(['contract_id'=>$ids])
->with(['productinfo'])->select();
$contractProduct=collection($contractProduct)->toArray();
$c = count($contractProduct);//总行数
// $tmp->cloneRow('product_name', $c);//复制行
// for ($i = 0; $i < $c; $i++) {
// $p=$contractProduct[$i];
// $tmp->setValue("product_name#" . ($i + 1), $p['productinfo']['name'] ?? '');//名称
// $tmp->setValue("product_unit#" . ($i + 1), $p['productinfo']['unit'] ?? '');//单位
// $tmp->setValue("product_num#" . ($i + 1), $p['productinfo']['num'] ?? '');//编码
// $tmp->setValue("product_type#" . ($i + 1), $p['productinfo']['type'] ?? '');//规格
// $tmp->setValue("product_number#" . ($i + 1), $p['number']);//数量
// $tmp->setValue("product_price#" . ($i + 1), $p['price']);//总价格
// $tmp->setValue("product_total#" . ($i + 1), $p['price'] * $p['number']);//总价格
// }
$tmp->setValue('money_big', convertAmountToCn($row['money']));
$tmp->setValue('customer_name', $row['customer']['name'] ?? '');
$tmp->setValue('contacts_name', $row['contacts']['name'] ?? '');
$tmp->setValue('business_name', $row['business']['name'] ?? '');
$tmp->setValue('order_staff_name', $row['order_staff']['name'] ?? '');
//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]);
}
$templates=WordTemplate::where(['type'=>'contract'])->select();
$contract = Form::getDataValue(Form::CONTRACT_TYPE);
$columns = array();
$columns[] = ['key' => 'customer_name', 'name' => '客户名称'];
$columns[] = ['key' => 'contacts_name', 'name' => '联系人名称'];
$columns[] = ['key' => 'business_name', 'name' => '商机名称'];
$columns[] = ['key' => 'order_staff_name', 'name' => '公司签约人名称'];
$columns[] = ['key' => 'money_big', 'name' => '合同金额人民币大写'];
foreach ($contract as $k => $v) {
$columns[] = array(
'key' => $v['id'],
'name' => $v['config']['label'],
);
}
$columns[] = ['key' => 'product_name', 'name' => '产品名称'];
$columns[] = ['key' => 'product_unit', 'name' => '产品单位'];
$columns[] = ['key' => 'product_num', 'name' => '产品编码'];
$columns[] = ['key' => 'product_type', 'name' => '产品规格'];
$columns[] = ['key' => 'product_number', 'name' => '产品数量'];
$columns[] = ['key' => 'product_price', 'name' => '产品单价'];
$columns[] = ['key' => 'product_total', 'name' => '产品合计'];
$this->assign('column', $columns);
$this->assign('templates', $templates);
$this->assign('ids', $ids);
return $this->view->fetch();
}
public function flow(){
$params = $this->request->param();
$url = request()->domain() . '/addons/qingdong/bill/detail';
$headers = [
'Content-Type' => 'application/json'
];
$bodys = json_encode([
"bill"=>"ats_bywnpk",
"bill_id"=>$params['bill_id'],
]);
$client = new Client();
$request = new Request('POST', $url, $headers, $bodys);
$res = $client->sendAsync($request)->wait();
$file = $res->getBody()->getContents();
$data = json_decode($file)->data;
$lclist = [];
$c1 = [];
$nodes_data2 = $this->object_array($data->nodes_data2);
if (empty($nodes_data2)) {
}else{
$logs = array_reverse($this->object_array($data->logs));
if (end($logs)['step_name'] == '结束') {
$lclist = $logs;
} else {
if (count($logs) <= count($nodes_data2)) {
$c1[] = $logs[0];
foreach ($nodes_data2 as $n => $node) {
$cq = null;
$nodes_data2[$n]['type'] = '2';
foreach ($logs as $i => $log) {
if ($node['name'] == $log['step_name']) {
$cq = $i;
break;
}
}
if (!is_null($cq)) {
$c1[] = $logs[$cq];
} else {
$c1[] = $nodes_data2[$n];
}
}
} else {
$c1 = $logs;
}
$lclist = $c1;
}
}
// halt($lclist);
$lclist = $this->object_array($lclist);
$this->assign('row', $lclist);
return $this->view->fetch('flow');
}
}