createOrder.js
61.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
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
/**
* @file 精品下单页编排。
* 页面负责生命周期、组件协调和 API 时序;提交、选品池和金额规则位于本页 services。
*/
import { getSystemInfoSync } from '~/utils/systemInfo'
import { checkDailyReport, checkStudyTask } from '~/store/ModalToQueueControl'
import api from '../../api'
import {
getProductStrategy,
DISCOUNT_TYPE,
ORDER_TYPE
} from './productStrategy'
import { SubmitContext } from './submitStrategy'
import { RouteContext } from './routeStrategy'
import {
clearOrderCouponFields,
resetCouponComponent
} from './services/orderCouponEffects'
import {
STAFF_MODE,
buildOrderPatch,
resolveDefaultSelection
} from './services/merchantStaffSelection'
import {
closePagePopupPatch,
computePagePopupVisible,
shouldSyncPagePopup,
mergeSetDataForPopupLock
} from './services/pagePopupLock'
import {
resolveCustomerId,
shouldFetchCustomerProfile,
parseCustomerProfileResponse,
buildCustomerProfileEchoPatch
} from './services/customerProfileEffects'
import {
PAY_TYPE,
PAY_TYPE_MAP,
GENDER_TYPE,
PAYEE_TYPE,
SALES_TYPE,
IMAGES
} from './constants'
import { getYQorderInfo, getPositionList, setConfigInfo } from '~/store/index'
import {
normalizeMarketingMetaOnItem,
applyMarketingFlagMapToSelectOrderList
} from '~/utils/marketingFlag'
import {
resolveCreateAllGoodsFlag,
buildOrderTypePickerList,
isAllowedLimitedOrderType
} from './services/orderMerchantConfig'
import {
normalizeSceneColumns,
resolveAutoScene,
toSceneFields
} from '../../services/sceneAutoSelection.helpers'
import { POSITION_BUCKET_DATA_KEYS } from './services/selectOrderCatalogClassification'
import {
buildCreateOrderCatalogViewModel,
createCatalogRequestCoordinator
} from './services/createOrderCatalog.workflow.js'
import {
compareBoutiqueMoney,
divideBoutiqueMoneyByQuantity,
isMarketingGoodsPriceLocked,
multiplyBoutiqueMoney
} from './services/goodsPriceEdit.helpers.js'
import { buildBoutiqueSubOrderList } from './services/submitGoodsSnapshot.js'
import timeUtil from '~/utils/timeFormat/time-utils.js'
import {
resolveConfiguredPhone,
validateBoutiqueRequiredFields
} from './services/orderValidation.helpers.js'
import { buildBoutiquePaymentSelectionPatch } from './services/paymentSelection.helpers.js'
import { buildBoutiqueOrderHydration } from './services/orderHydration.helpers.js'
import { buildBoutiqueChooseList } from './services/goodsChooseEcho.workflow.js'
import {
coordinateBoutiqueCustomerDailyFieldsEcho,
formatCustomerTags,
getBoutiqueCustomerTagOptions,
isBoutiqueActualDeliveryDateVisible,
isBoutiqueCustomerTagsVisible,
parseCustomerTags,
reconcileBoutiqueCustomerDailyFields,
serializeCustomerTags
} from './services/customerDailyFields.helpers.js'
import NP from 'number-precision'
const app = getApp()
let toastList = {
userId: '销售顾问不能为空',
baseSceneCode: '场景名称不能为空',
subShopMerchantId: '二级流量方不能为空',
deliveryUserId: '交付专员不能为空',
customerName: '车主姓名不能为空',
salesType: '客户来源不能为空',
customerPhone: '手机号不能为空',
sellerUserId: '转化人员不能为空',
customerCouponCode: '精品礼券不能为空',
carBrand: '车型不能为空',
standNo: '车架号( VIN码 )不能为空',
plateNumber: '车牌不能为空',
actualDeliveryDate: '实际交付日期不能为空',
payeeType: '收款方不能为空',
selectPayType: '支付方式不能为空'
}
import { validateVin, formatVinInput } from '~/utils/vinVaildate'
// orderSource 订单来源(1后台录入,2移动端预录客户,3移动端升级下单,4再次下单)
Page({
/**
* 页面的初始数据
*/
data: {
payType: PAY_TYPE_MAP,
paymentMethod: null,
skylight: IMAGES.SKYLIGHT,
tricorn: IMAGES.TRICORN,
windshield: IMAGES.WINDSHIELD,
sideIcorn: IMAGES.SIDE_ICON,
afterIcorn: IMAGES.AFTER_ICON,
scanIcon: IMAGES.SCAN_ICON,
selectIcon: IMAGES.SELECT_ICON,
recordIcon: IMAGES.RECORD_ICON,
tipsIcon: IMAGES.TIPS_ICON,
name: 'createdOrder',
outTradeNo: '',
totalFee: '',
accountDate: '',
switchVlaue: '',
orderCreateType: 'createdOrder', // additionRecordOrder(补录订单) createdOrder(新增) errorOrder(错误订单) alreadyExistOrder(扫码/预约订单)
showOrderpop: false,
pagePopupVisible: false,
phoneShow: false,
customerInfoBox: false,
payTypeList: [
{
name: '门店收款',
value: PAY_TYPE.SHOP
},
{
name: 'POS机',
value: PAY_TYPE.POS
},
{
name: '嘀加收款',
value: PAY_TYPE.DJ_COLLECTION
},
{
name: '微信支付',
value: PAY_TYPE.WECHAT,
imgurl: '../../images/wxPayIcon.png'
}
],
showPayList: [],
payeeList: [
{
name: '嘀加收款',
value: PAYEE_TYPE.DJ
},
{
name: '4S店收款',
value: PAYEE_TYPE.SHOP
}
],
orderObj: {
customer: {
customerName: '',
customerPhone: '',
standNo: '',
plateNumber: '',
customerSex: GENDER_TYPE.MALE,
experienceFlag: 'Y',
salesType: SALES_TYPE.PRE_SALES,
customerTags: '',
actualDeliveryDate: ''
},
deliveryUserId: '',
deliveryEmployeeName: '',
baseSceneCode: '',
baseSceneName: '',
// selectPayType: 0,
selectPayType: PAY_TYPE.SHOP, // 支付方式:默认门店收款
payeeType: PAYEE_TYPE.SHOP, // 收款方:默认4s店收款
djOrderType: ORDER_TYPE.NORMAL, // 订单类型:默认普通订单
discountType: DISCOUNT_TYPE.NONE, // 优惠类型:默认无优惠
remark: '',
customerCouponId: '',
subOrderList: []
},
goodsList: [],
goodsData: [],
userInfo: {},
requiredList: [],
isErrorOrder: false,
isAlreadyExistOrder: false,
showTips: false,
associateOrderType: false,
tipsProps: {
tipsText: '该门店产生异常订单,请点击补录!',
showTips: true,
type: 2,
typeText: '补录订单'
},
positionTypeList: [],
currentWordNumber: 0, // 订单备注字数
copyGoodsData: [],
marketingFlagMap: {},
activityIdMap: {},
isShowSubShopMerchant: false,
frontGearArr: [], // 前挡
sideRearGearArr: [], // 侧后挡
skylightArr: [], // 天窗
sideBeforeRearGearArr: [], // 前侧窗玻璃
sideAfterRearGearArr: [], // 后档
otherProduct: [], //其他精品
packageList: [],
baseConfigData: {},
showSource: false,
customerSourcePickerIndex: 0,
customerTagOptions: getBoutiqueCustomerTagOptions(),
customerDailyFieldMerchantBrands: [],
customerDailyFieldBrandMerchantId: '',
customerTagDraftOptions: [],
customerTagsPopup: false,
customerTagsText: '',
showCustomerTags: true,
showActualDeliveryDate: false,
actualDeliveryDateMax: timeUtil.getTodayDateStr(),
Sourcecolumns: [
{
type: SALES_TYPE.PRE_SALES,
name: '销售端引流-售前'
},
{
type: SALES_TYPE.PRE_SALES_DELIVERY,
name: '交付端引流-售前'
},
{
type: SALES_TYPE.AFTER_SALES,
name: '门店引流-售后'
},
{
type: SALES_TYPE.NATURAL_TO_STORE,
name: '自然到店'
}
],
orderTypeList: [
{ text: '正常订单', value: ORDER_TYPE.NORMAL },
{ text: '打折策略', value: ORDER_TYPE.DISCOUNT },
{ text: '买赠策略', value: ORDER_TYPE.GIFT },
{ text: '冲量活动', value: ORDER_TYPE.IMPULSE },
{ text: '组合付款', value: ORDER_TYPE.COMBINATION },
{ text: '内部结算', value: ORDER_TYPE.INTERNAL_SETTLEMENT }
],
orderTypeName: '正常订单',
orderTypePickerList: [],
sceneColumns: [],
packageBox: false,
skuGoodsBox: false,
djPayList: [], // 嘀加收款方对应支付方式
merchantPayList: [], // 门店收款方对应支付方式
configPayTypeList: [], // 园区店配置支持的支付方式
recordOrderFlag: true, // 补录订单入口标识
returnFun: false,
skuGoodsData: {}, //多规格商品数据
vinValid: true,
createAllGoodsFlag: 1, // 当前门店是否能创建全部类型订单 0-否 1-是
staffPickerBox: false,
staffPickerMode: '',
subShopMerchantBox: false
},
onCloseOrderType() {
this.setData({ orderTypeBox: false })
},
onConfirmOrderType(e) {
const { value } = e.detail
const { orderObj, goodsList } = this.data
// 如果订单类型改变,重置所有商品的折扣信息
if (orderObj.djOrderType !== value.value) {
goodsList.forEach(item => {
const strategy = getProductStrategy(item)
if (strategy) {
// 重置为无折扣
strategy.resetDiscount()
}
})
this.setGoodsTotal(goodsList)
}
this.setData({
'orderObj.djOrderType': value.value,
orderTypeName: value.text,
orderTypeBox: false,
goodsList
})
},
changeProductDiscountType(e) {
const { index, gindex } = e.detail // gindex for package sub-items
const { type } = e.detail
const { goodsList } = this.data
const discountType = parseInt(type)
const item = goodsList[index]
const strategy = getProductStrategy(item)
if (strategy) {
// 如果是套餐子商品
if (gindex !== undefined && strategy.updateSubItemDiscount) {
strategy.updateSubItemDiscount(gindex, discountType, '') // Reset to empty string
} else {
strategy.setDiscount(discountType, '') // Reset value when type changes
}
this.setGoodsTotal(goodsList)
}
},
inputDiscountValue(e) {
const { index, gindex } = e.detail
let { value } = e.detail
const { goodsList, orderObj } = this.data
const item = goodsList[index]
const strategy = getProductStrategy(item)
if (strategy) {
// 获取当前的 discountType
let currentType
let basePrice
if (gindex !== undefined && strategy.getSubItemData) {
currentType = strategy.getSubItemData(gindex).discountType
basePrice = strategy.getSubItemBasePrice(gindex)
} else {
currentType = strategy.getData().discountType
basePrice = strategy.getBasePrice()
}
// 1:默认值为空不是为0
if (value === '') {
// Allow empty value
} else {
// Remove non-digit and non-dot characters
value = value.replace(/[^\d.]/g, '')
if (value.length > 1 && value.startsWith('0') && value[1] !== '.') {
value = value.replace(/^0+/, '')
if (value === '') {
value = '0'
} else if (value.startsWith('.')) {
value = '0' + value
}
}
// Ensure only one dot
const parts = value.split('.')
if (parts.length > 2) {
value = parts[0] + '.' + parts.slice(1).join('')
}
if (currentType == DISCOUNT_TYPE.RATIO) {
// 折扣比例
// 2:是折扣比例的话,最多只能输入1位整数和1个小数
// 允许输入 10 (无折扣)
if (value === '10') {
// Allow '10'
} else if (value.startsWith('10') && value !== '10') {
// If starts with 10 but has more chars (e.g. 10.1), restrict to 10
value = '10'
} else {
const dotIndex = value.indexOf('.')
if (dotIndex !== -1) {
let integerPart = value.substring(0, dotIndex)
let decimalPart = value.substring(dotIndex + 1)
if (integerPart.length > 1) {
integerPart = integerPart.slice(0, 1)
}
if (decimalPart.length > 1) {
decimalPart = decimalPart.slice(0, 1)
}
value = integerPart + '.' + decimalPart
} else {
if (value.length > 1) {
value = value.slice(0, 1)
}
}
}
} else if (currentType == DISCOUNT_TYPE.AMOUNT) {
// 折扣金额
// 3:是折扣金额的话,最大值不能超过 item.goods.sellPrice 的值,超过取 item.goods.sellPrice,输入最多不超过两个小数
const dotIndex = value.indexOf('.')
if (dotIndex !== -1) {
let integerPart = value.substring(0, dotIndex)
let decimalPart = value.substring(dotIndex + 1)
if (decimalPart.length > 2) {
decimalPart = decimalPart.slice(0, 2)
}
value = integerPart + '.' + decimalPart
}
const compared = compareBoutiqueMoney(value, basePrice)
if (compared.ok && compared.value > 0) {
value = basePrice.toString()
}
}
}
if (gindex !== undefined && strategy.updateSubItemDiscount) {
strategy.updateSubItemDiscount(gindex, currentType, value)
} else {
strategy.setDiscount(currentType, value)
}
if (this.debouncedSetGoodsTotal) {
this.debouncedSetGoodsTotal(goodsList)
} else {
// onLoad 尚未完成时直接同步总价,保证早到事件仍可落盘。
this.setGoodsTotal(goodsList)
}
return value
}
},
toggleGift(e) {
const { index, gindex } = e.detail
const { value } = e.detail // "4" for Yes, "5" for No
const { goodsList } = this.data
const type = parseInt(value)
const item = goodsList[index]
const strategy = getProductStrategy(item)
if (strategy) {
if (gindex !== undefined && strategy.updateSubItemDiscount) {
// const type = isGift ? DISCOUNT_TYPE.GIFT : DISCOUNT_TYPE.NON_GIFT
strategy.updateSubItemDiscount(gindex, type, 0)
} else {
// const type = isGift ? DISCOUNT_TYPE.GIFT : DISCOUNT_TYPE.NON_GIFT
strategy.setDiscount(type, 0)
}
this.setGoodsTotal(goodsList)
}
},
closeTips() {
this.setData({
showTips: false
})
},
/**
* 补录订单导航回调:路由到补录流程后清空销售顾问与礼券。
* @see clearOrderCouponFields
*/
async navigator(e) {
let { selectOutTradeNoArr } = e.detail
let { paymentMethod, isErrorOrder, orderCreateType } = this.data
this.closeSwitchPopup()
selectOutTradeNoArr?.length &&
this.onRoute({
selectOutTradeNoArr,
orderCreateType: isErrorOrder ? orderCreateType : 'additionRecordOrder',
paymentMethod,
djOrderType: this.data.orderObj.djOrderType
})
if (isErrorOrder) return
let { orderObj } = this.data
// 补录导航后:清空销售顾问与礼券,避免沿用上一笔无效数据
;['employeeName', 'userId', 'orderSource'].forEach(item => {
if (orderObj[item]) delete orderObj[item]
})
clearOrderCouponFields(orderObj)
let goodsList = []
this.setData({
orderObj,
goodsList
})
this.setGoodsTotal(goodsList)
this.refreshSelectOrderGoodsIfReady()
},
/**
* 门店+场景就绪时刷新选品列表(补录进入后弹层需带活动标)
*/
refreshSelectOrderGoodsIfReady() {
const { orderObj, orderCreateType } = this.data
if (!orderObj?.merchantId || !orderObj?.baseSceneCode) return
const hasSceneType =
orderObj.sceneType !== undefined &&
orderObj.sceneType !== null &&
orderObj.sceneType !== ''
if (!hasSceneType) return
// 补录会先清空 userId,不能依赖销售顾问才拉选品
if (!orderObj.userId && orderCreateType !== 'additionRecordOrder') return
this.getSelectOrderGoodsList(orderObj.merchantId, orderObj.sceneType)
},
tipsEvent() {
this.setData({
showOrderpop: true
})
},
closeSwitchPopup() {
this.setData({
showOrderpop: false
})
},
remarkInput(e) {
this.setData({
currentWordNumber: e.detail.cursor,
'orderObj.remark': e.detail.value
})
},
showCustomPop() {
this.setData({
customerInfoBox: true
})
},
/**
* 客户档案确认:合并档案数据后,备注/车架号/车型任一项为空则按客户 id 补拉 customerProfileInfo 回显
* @param {WechatMiniprogram.CustomEvent} e
*/
async chooseCustomerInfo(e) {
let { detail } = e
let {
outTradeNo,
showPayList,
orderObj: {
associateOrderType,
associateOrderCode,
selectPayType,
payeeType
}
} = this.data
detail.outTradeNo = outTradeNo
// 解决补录订单 这两个参数丢失问题
if (associateOrderType || associateOrderCode) {
detail.associateOrderType = associateOrderType
detail.associateOrderCode = associateOrderCode
}
detail.selectPayType = selectPayType
detail.payeeType = payeeType
// detail.selectPayType = 3
await this.onRoute(detail)
// 判断一下档案支付方式现在是否还在,在就替换,没有就去掉这个参数
this.settingPayType(detail)
this.setData(closePagePopupPatch('customerInfoBox'))
},
/**
* 订单回显后备注/车架号/车型任一项为空时调用 customerProfileInfo 补全(编辑进入、客户档案选中等)
* @param {Object} [detail] 路由入参或 setOrderObj 的 options,用于解析 customerId
*/
async echoCustomerProfileIfNeeded(detail) {
const { orderObj } = this.data
if (!shouldFetchCustomerProfile(orderObj)) return
const customerId =
resolveCustomerId(orderObj?.customer) ||
resolveCustomerId(detail?.customer) ||
detail?.id
if (!customerId) return
try {
const res = await api.getCustomerProfileInfo({ id: customerId })
const profile = parseCustomerProfileResponse(res)
if (!profile) return
const { patch, echoedStandNo } = buildCustomerProfileEchoPatch(
orderObj,
profile
)
if (!Object.keys(patch).length) return
this.setData(patch, () => {
if (echoedStandNo.length === 17) {
this.handleVinInput(echoedStandNo, true)
}
})
} catch (err) {
// 接口失败不打断选档流程
}
},
/** 客户档案弹框取消:重置 flag,解除 page-meta 锁页 */
onCustomerInfoCancel() {
this.setData(closePagePopupPatch('customerInfoBox'))
},
/** 通用弹框取消:由 wxml data-popup-key 指定要关闭的字段 */
onPagePopupCancel(e) {
const popupKey = e.currentTarget.dataset.popupKey
this.setData(closePagePopupPatch(popupKey))
},
/** 二级流量方确认:组件已写入 orderObj,此处仅关弹框解锁 */
onSubShopMerchantConfirm() {
this.setData(closePagePopupPatch('subShopMerchantBox'))
},
/**
* 多规格商品确认:页面消费组件 payload,统一更新商品合计并关闭弹层。
* @param {{detail:Array<object>}} e 多规格商品确认事件
* @returns {void}
*/
onSkuGoodsConfirm(e) {
const goodsList = Array.isArray(e.detail) ? e.detail : []
this.setData(closePagePopupPatch('skuGoodsBox'))
this.setGoodsTotal(goodsList)
},
reWrite(type, data) {
let { orderObj } = this.data
// 车架号字段特殊处理
if (type === 'standNo') {
this.handleVinInput(data, true, type) // 扫描时立即校验
} else {
orderObj.customer[type] = data
this.setData({
orderObj
})
}
},
navOcr(e) {
let { type } = e.currentTarget.dataset
wx.$router.go(`ocr?type=${type}`)
},
async prefillRecentScene() {
const freshUserInfo = wx.$util.getUserInfo() || {}
const userInfo =
(this.data.userInfo && Object.keys(this.data.userInfo).length
? this.data.userInfo
: freshUserInfo) || {}
const currentCode = this.data.orderObj?.baseSceneCode || ''
if (currentCode) return
try {
const res = await api.getRecentUserScene({
sceneType: String(userInfo.sceneType || ''),
phone: userInfo.phone
})
const recent = res?.code == 0 ? res?.data : null
const baseSceneCode = recent?.baseSceneCode || ''
if (!baseSceneCode) return
this.setData(
{
userInfo,
'orderObj.baseSceneCode': baseSceneCode,
'orderObj.sceneType': recent?.sceneType
},
() => this.applyBoutiqueCustomerDailyFields()
)
} catch (e) {
// 最近场景仅用于预填,读取失败时保留用户手动选择能力。
}
},
showPopup(e) {
let {
copyGoodsData,
packageList,
orderObj: { selectPayType },
baseConfigData,
createAllGoodsFlag
} = this.data
let { showName, staffMode, positionnnum: positionNum } =
e.currentTarget.dataset || e.detail
if (staffMode) {
return this.setData({
staffPickerBox: true,
staffPickerMode: staffMode
})
}
if (showName == 'orderTypeBox' && !this.data.orderTypePickerList?.length) return
let obj = POSITION_BUCKET_DATA_KEYS
let arr = []
if (showName == 'goodsBox') {
// type 产品类型 1前挡 2侧后挡 3天窗 4其它精品
let keyName = obj[positionNum]
arr = keyName ? this.data[keyName] : []
if (arr?.length < 1) {
return this.showToast(`门店无配置其它精品商品`)
}
}
if (showName == 'packageBox') {
arr = packageList
}
applyMarketingFlagMapToSelectOrderList(
arr,
this.data.marketingFlagMap || {},
this.data.activityIdMap || {}
)
arr.forEach((item) => normalizeMarketingMetaOnItem(item))
this.setData({
[showName]: true,
goodsData: arr
})
},
/**
* 拉取场景列表并自动选中:优先匹配已有 baseSceneCode(含 recent 预填),否则取第一项
*/
async getUserSceneList() {
const freshUserInfo = wx.$util.getUserInfo() || {}
const userInfo =
(this.data.userInfo && Object.keys(this.data.userInfo).length
? this.data.userInfo
: freshUserInfo) || {}
try {
const { orderObj } = this.data
const merchantId =
orderObj?.merchantId || userInfo?.shopMerchantId || ''
const res = await api.getUserScene({
sceneType: String(userInfo.sceneType || ''),
phone: userInfo.phone,
merchantId
})
const list =
res?.code == 0 && res?.data?.length ? res.data : []
const sceneColumns = normalizeSceneColumns(list)
const currentCode = orderObj?.baseSceneCode || ''
const { scene: currentScene } = resolveAutoScene(currentCode, sceneColumns)
const sceneFields = toSceneFields(currentScene)
const patch = {
userInfo,
sceneColumns
}
if (currentScene) {
patch['orderObj.baseSceneCode'] = sceneFields.baseSceneCode
patch['orderObj.baseSceneName'] = sceneFields.baseSceneName
patch['orderObj.sceneType'] = sceneFields.sceneType
}
this.setData(patch, () => {
const { orderObj: nextOrderObj } = this.data
this.applyBoutiqueCustomerDailyFields(nextOrderObj?.customer)
if (
currentScene &&
nextOrderObj?.merchantId &&
nextOrderObj?.baseSceneCode &&
(nextOrderObj?.userId ||
this.data.orderCreateType === 'additionRecordOrder')
) {
this.getSelectOrderGoodsList(
nextOrderObj.merchantId,
currentScene.sceneType
)
}
})
} catch (e) {
this.setData({
sceneColumns: []
})
}
},
/** 关闭员工选择弹窗 */
onStaffPickerCancel() {
this.setData({ staffPickerBox: false })
},
/**
* 确认员工选择:写入 orderObj;sales 模式清空礼券与商品并重载列表
* @param {WechatMiniprogram.CustomEvent} e
*/
onStaffPickerConfirm(e) {
const { merchant, staff, mode } = e.detail
const { orderObj, goodsList } = this.data
const patch = buildOrderPatch(mode, merchant, staff)
const nextOrderObj = { ...orderObj, ...patch }
let nextGoodsList = goodsList
if (mode === STAFF_MODE.SALES) {
clearOrderCouponFields(nextOrderObj)
nextGoodsList = []
const hasSceneSelected =
nextOrderObj.baseSceneCode !== undefined &&
nextOrderObj.baseSceneCode !== null &&
nextOrderObj.baseSceneCode !== ''
const hasSceneType =
nextOrderObj.sceneType !== undefined &&
nextOrderObj.sceneType !== null &&
nextOrderObj.sceneType !== ''
if (hasSceneSelected && hasSceneType) {
this.getSelectOrderGoodsList(
nextOrderObj.merchantId,
nextOrderObj.sceneType
)
}
}
this.setData(
{
orderObj: nextOrderObj,
goodsList: nextGoodsList,
staffPickerBox: false
},
() => {
if (mode === STAFF_MODE.SALES) {
resetCouponComponent(this)
this.loadBoutiqueCustomerTagOptions(nextOrderObj.merchantId)
}
}
)
},
/**
* onLoad 预填销售顾问:上一单同店或单门店「系统」兜底
* @see resolveDefaultSelection
*/
async prefillLastSeller() {
const { orderObj, userInfo, orderCreateType } = this.data
try {
const patch = await resolveDefaultSelection({
orderObj,
userInfo,
orderCreateType
})
if (!patch) return
this.setData(
{
orderObj: { ...orderObj, ...patch }
},
() => {
const nextOrderObj = this.data.orderObj || {}
this.loadBoutiqueCustomerTagOptions(nextOrderObj.merchantId)
if (nextOrderObj?.merchantId && nextOrderObj?.baseSceneCode) {
if (
nextOrderObj.sceneType !== undefined &&
nextOrderObj.sceneType !== null &&
nextOrderObj.sceneType !== ''
) {
this.getSelectOrderGoodsList(
nextOrderObj.merchantId,
nextOrderObj.sceneType
)
} else {
this.getUserSceneList()
}
}
}
)
} catch (e) {
// 最近一次销售仅用于预填,失败不阻断手动选择与开单。
}
},
/**
* 表单输入;手机号变为合法号码时清空礼券/商品并重置 Coupon 组件。
* @see clearOrderCouponFields @see resetCouponComponent
*/
input(e) {
let { orderObj, userInfo, goodsList } = this.data
let { value } = e.detail
let { name } = e.currentTarget.dataset
let prop = `orderObj.${name}`
if (name == 'customer.customerPhone' && phoneRex.test(value)) {
// 手机号变更:礼券与商品可能失效,清空并同步 Coupon 组件 UI
if (orderObj.orderSource) delete orderObj.orderSource
clearOrderCouponFields(orderObj)
delete orderObj.isPhoneQuery
if (orderObj.selectPayType != 0) {
goodsList = []
}
this.setData({
orderObj,
goodsList,
returnFun: false
})
resetCouponComponent(this)
this.setGoodsTotal(goodsList)
}
// 车架号字段特殊处理
if (name === 'customer.standNo') {
this.handleVinInput(value) // 手动输入时需达到17位才校验
return
}
this.setData({
[`orderObj.${name}`]: value.trim()
})
},
/**
* 手机号失焦:通知 #coupon 组件按当前手机号刷新礼券列表
*/
phoneBlur() {
this.selectComponent('#coupon')?.customerPhoneBlur &&
this.selectComponent('#coupon')?.customerPhoneBlur()
},
changeGender(e) {
let { gender } = e.currentTarget.dataset
wx.vibrateShort()
this.setData({
['orderObj.customer.customerSex']: gender
})
},
changeExperience(e) {
let { experience } = e.currentTarget.dataset
wx.vibrateShort()
this.setData({
['orderObj.customer.experienceFlag']: experience
})
},
changeSelectPayType(e) {
let { experience } = e.currentTarget.dataset
wx.vibrateShort()
this.setData({
['orderObj.selectPayType']: experience,
['orderObj.subOrderList']: [],
goodsList: []
})
// 解决没选门店就切换查询商品的的问题
this.data.orderObj.merchantId &&
this.getSelectOrderGoodsList(this.data.orderObj.merchantId)
},
// 切换收款方
changePayee(e) {
let {
item: { value }
} = e.currentTarget.dataset
let { isErrorOrder, switchVlaue, merchantPayList, djPayList } = this.data
if (isErrorOrder || switchVlaue) return
this.setData({
['orderObj.payeeType']: value
})
if (value == 1) {
// 收款方:4S店收款 支付方式默认选中门店收款
this.setData({
showPayList: merchantPayList,
['orderObj.selectPayType']: 2
})
} else {
// 收款方:嘀加收款 (1:微信支付)(3:pos机支付)(4:支付宝支付)支付方式有选中微信支付,没有选中,支付方式获取园区店配置,微信支付和pos机支付必须选中一项
this.setData({
showPayList: djPayList,
['orderObj.selectPayType']: djPayList?.some(v => v.value == 1)
? 1
: djPayList?.some(v => v.value == 3)
? 3
: 4
})
}
},
// 切换支付方式
changePayType(e) {
let {
item: { value }
} = e.currentTarget.dataset
let { goodsList } = this.data
if (value == 0 && goodsList && goodsList.length > 0) return
wx.vibrateShort()
this.setData({
['orderObj.selectPayType']: value
})
},
chooseCar(e) {
let { carBrand, carType } = e.detail
this.setData({
car: `${carBrand}|${carType}`,
...closePagePopupPatch('carBrandBox')
})
},
/**
* Coupon 组件确认回调(弹窗内选礼券后的展示名)
* @see tabWorkOrder/components/Coupon/Coupon.js
*/
chooseCoupon(e) {
let { name } = e.detail
this.setData({
couponName: name,
...closePagePopupPatch('couponBox')
})
},
/** 商品/套餐弹框确认后关闭,Goods/SetMeal 已通过 getPageInstance 写入 goodsList */
chooseGoods() {
const patch = {}
if (this.data.goodsBox) Object.assign(patch, closePagePopupPatch('goodsBox'))
if (this.data.packageBox) Object.assign(patch, closePagePopupPatch('packageBox'))
if (Object.keys(patch).length) this.setData(patch)
},
//修改套餐价格
changeMealPrice(e) {
let { goodsList } = this.data
let { value, index, gindex } = e.detail
if (
isMarketingGoodsPriceLocked({
goods: goodsList[index]?.packageGoods?.goodsList?.[gindex],
marketingFlag: goodsList[index]?.packageGoods?.goodsList?.[gindex]?.marketingFlag,
activityId: goodsList[index]?.packageGoods?.goodsList?.[gindex]?.activityId
})
) {
return
}
if (value.length > 1 && value.startsWith('0') && value[1] !== '.') {
value = value.replace(/^0+/, '')
if (value === '') {
value = '0'
} else if (value.startsWith('.')) {
value = '0' + value
}
}
let number = wx.$util.removeLeadingZerosAndEnsureNonNegative(value)
const strategy = getProductStrategy(goodsList[index])
// 策略模式应用:
// 获取对应的策略实例(此处预期为 PackageProductStrategy)。
// 利用策略类封装的 updateSubItemPrice 方法更新子商品价格,
// 以及 validateSubItemPrice 方法进行价格合规性校验(如最低限价检查)。
// 这样做避免了在业务层直接操作复杂的嵌套数据结构,提高了代码的可读性和可维护性。
if (strategy && strategy.updateSubItemPrice) {
// 移除输入时的校验,改为失焦校验
// const validation = strategy.validateSubItemPrice(item, number)
// if (!validation.valid) {
// wx.$util.showToast(validation.message)
// // 强制赋值最低价格
// number = item.minSellPrice
// }
strategy.clearError()
// 如果价格有变化,清空折扣输入框 (仅针对折扣单和组合单)
if (
this.data.orderObj.djOrderType == ORDER_TYPE.DISCOUNT ||
this.data.orderObj.djOrderType == ORDER_TYPE.COMBINATION
) {
const currentBasePrice = strategy.getSubItemBasePrice(gindex)
const compared = compareBoutiqueMoney(currentBasePrice, number)
if (!compared.ok || compared.value !== 0) {
const subItemData = strategy.getSubItemData(gindex)
if (
subItemData.discountType == DISCOUNT_TYPE.RATIO ||
subItemData.discountType == DISCOUNT_TYPE.AMOUNT
) {
strategy.updateSubItemDiscount(gindex, subItemData.discountType, '')
}
}
}
strategy.updateSubItemPrice(gindex, number)
this.setGoodsTotal(goodsList)
}
return number
},
changePrice(e) {
let { index } = e.detail
let { value } = e.detail
let { goodsList } = this.data
const lineItem = goodsList[index]
const strategy = getProductStrategy(lineItem)
if (
isMarketingGoodsPriceLocked({
goods: strategy?.getData?.() || lineItem?.goods,
marketingFlag: lineItem?.marketingFlag,
activityId: lineItem?.activityId
})
) {
return
}
let number = wx.$util.removeLeadingZerosAndEnsureNonNegative(value)
if (strategy) {
const data = strategy.getData()
// 再次编辑:输入框展示总价,改价需换算为单价
if (data?.resetOrder) {
const count = strategy.getCount()
data.totalPrice = number
const unit = divideBoutiqueMoneyByQuantity(number, count)
number = unit.ok ? unit.value : ''
}
strategy.clearError()
if (
this.data.orderObj.djOrderType == ORDER_TYPE.DISCOUNT ||
this.data.orderObj.djOrderType == ORDER_TYPE.COMBINATION
) {
const currentBasePrice = strategy.getBasePrice()
const compared = compareBoutiqueMoney(currentBasePrice, number)
if (!compared.ok || compared.value !== 0) {
const discountData = strategy.getData()
if (
discountData.discountType == DISCOUNT_TYPE.RATIO ||
discountData.discountType == DISCOUNT_TYPE.AMOUNT
) {
strategy.setDiscount(discountData.discountType, '')
}
}
strategy.setBasePrice(number)
} else {
strategy.setBasePrice(number)
}
this.setGoodsTotal(goodsList)
}
return number
},
priceBlur(e) {
const { index, gindex } = e.detail
const { goodsList } = this.data
const strategy = getProductStrategy(goodsList[index])
if (!strategy) return
let validation = { valid: true }
if (
gindex !== undefined &&
gindex !== null &&
strategy.getSubItemData &&
strategy.validateSubItemPrice
) {
const subItem = strategy.getSubItemData(gindex)
let checkPrice =
subItem.basePrice !== undefined
? subItem.basePrice
: subItem.sellPrice !== undefined
? subItem.sellPrice
: subItem.price
if (
!checkPrice &&
checkPrice !== 0 &&
subItem.validMinSellPrice === 'Y'
) {
strategy.updateSubItemPrice(gindex, subItem.minSellPrice)
checkPrice = subItem.minSellPrice
}
validation = strategy.validateSubItemPrice(subItem, checkPrice)
subItem.errorTarget = !validation.valid
subItem.checkError = !validation.valid
} else {
const data = strategy.getData()
let checkPrice = strategy.getBasePrice()
if (
!checkPrice &&
checkPrice !== 0 &&
data.validMinSellPrice === 'Y'
) {
const minPrice = strategy.getMinPrice()
strategy.setPrice(minPrice)
checkPrice = minPrice
}
validation = strategy.performValidation()
}
this.setGoodsTotal(goodsList)
},
setGoodsTotal(goodsList) {
let total = 0
goodsList.forEach(item => {
normalizeMarketingMetaOnItem(item)
const strategy = getProductStrategy(item)
if (strategy) {
const data = strategy.getData()
if (data && item.count != null) {
data.number = item.count
if (data.resetOrder) {
const unit = data.basePrice ?? data.sellPrice ?? data.price
if (unit != null && unit !== '') {
const lineTotal = multiplyBoutiqueMoney(unit, item.count)
if (lineTotal.ok) data.totalPrice = lineTotal.value
}
}
}
total = NP.plus(total, strategy.calculateSubtotal())
}
})
this.setData({
goodsList,
total: wx.$util.decimal(total, 2)
})
},
delGoodsList(e) {
let index
if (e.detail && e.detail.index !== undefined) {
index = e.detail.index
} else {
index = e.currentTarget.dataset.index
}
let { goodsList } = this.data
goodsList.splice(index, 1)
this.setData({
goodsList
})
this.setGoodsTotal(goodsList)
},
/**
* 精品下单唯一页面入口;提交锁、校验和 API 编排由 SubmitContext 负责。
* @param {WechatMiniprogram.BaseEvent} i
* @returns {Promise<void>}
*/
async submit(i) {
const context = new SubmitContext(this)
await context.execute(i)
},
handleRequiredError(key) {
if (toastList[key]) {
this.showToast(toastList[key])
wx.pageScrollTo({
selector: `.${key}`
})
}
},
/**
* 校验商品并生成精品 API 子单;不再接收无效的临时数组和价格开关参数。
* @param {boolean} save 是否仅建档
* @param {Array<object>} goodsList 页面商品
* @param {object} orderObj 待提交订单
* @returns {false|string}
*/
checkGoods(save, goodsList, orderObj) {
if (save) return false
const mapped = buildBoutiqueSubOrderList(goodsList, orderObj)
if (!mapped.ok) return '商品金额或数量格式不正确'
orderObj.subOrderList = mapped.subOrderList
if (orderObj.subOrderList?.length == 0) {
return '商品不能为空'
}
// 校验折扣值不能为空 (允许0)
const hasEmptyDiscountValue = orderObj.subOrderList.some(
item =>
(item.discountType == DISCOUNT_TYPE.RATIO ||
item.discountType == DISCOUNT_TYPE.AMOUNT) &&
(item.discountValue === '' ||
item.discountValue === null ||
item.discountValue === undefined)
)
if (hasEmptyDiscountValue) {
return '商品折扣值不能为空'
}
if (orderObj.djOrderType == 3) {
const totalCount = orderObj.subOrderList.reduce(
(sum, item) => sum + (parseInt(item.number, 10) || 0),
0
)
if (totalCount < 2) {
return '买赠策略至少需要选择两个商品'
}
const hasGift = orderObj.subOrderList.some(item => item.discountType == 4)
if (!hasGift) {
return '买赠策略需要至少有一个商品是赠品'
}
}
if (orderObj.djOrderType == 2) {
const hasDiscount = orderObj.subOrderList.some(
item => item.discountType && item.discountType != DISCOUNT_TYPE.NONE
)
if (!hasDiscount) {
return '打折策略需要至少有一个商品选择折扣'
}
}
if (orderObj.djOrderType == 5) {
const hasDiscount = orderObj.subOrderList.some(
item => item.discountType && item.discountType != DISCOUNT_TYPE.NONE
)
if (!hasDiscount) {
return '组合付款需要至少有一个商品选择折扣'
}
}
if (mapped.errorTargetCount) {
return '商品不能低于最低价格'
}
},
/**
* 将页面校验上下文交给纯 helper,保留既有公开方法名供提交策略调用。
* @param {boolean} save 是否保存为客户档案
* @param {object} obj 当前订单
* @returns {{ok:true}|{ok:false,errorKey?:string,message?:string,presentation?:'toast'}}
*/
checkRequired(save, obj) {
return validateBoutiqueRequiredFields({
save,
orderObj: obj,
requiredList: this.data.requiredList,
showActualDeliveryDate: this.data.showActualDeliveryDate
})
},
/**
* 订单尚无手机号时回填门店配置默认值,不修改配置列表。
* @returns {void}
*/
checkPhoneUseConfig() {
const { phoneShow, orderObj } = this.data
if (
phoneShow &&
phoneShow.length &&
orderObj.merchantName &&
orderObj.employeeName &&
!orderObj.customer.customerPhone
) {
const phoneNumber = resolveConfiguredPhone(phoneShow, orderObj.merchantId)
if (phoneNumber !== undefined) {
this.setData({
'orderObj.customer.customerPhone': phoneNumber
})
}
}
},
/**
* 路由/接口回显写入 orderObj(编辑、再次下单、扫码礼券等)。
* 含礼券字段从 customerCoupon 回显的逻辑。
* 同门店客户档案回填时复用已加载的经营品牌立即同步日报字段显隐;
* 跨门店仍等待新经营品牌结果,避免沿用旧门店规则。
* @param {Object} options 订单详情或路由入参
* @returns {void}
*/
setOrderObj(options) {
this._setOrderObjInvoked = true
const {
scene,
userInfo,
isErrorOrder,
associateOrderType,
paymentMethod,
orderTypeList
} = this.data
wx.$util.showLoading('加载中...')
const previousOrderObj = this.data.orderObj || {}
const candidateMerchantId =
options?.merchantId || options?.merchantCoupon?.merchantId
const canReuseMerchantBrandContext =
candidateMerchantId !== undefined &&
candidateMerchantId !== null &&
candidateMerchantId !== '' &&
String(candidateMerchantId) ===
String(previousOrderObj.merchantId || '') &&
String(candidateMerchantId) ===
String(this.data.customerDailyFieldBrandMerchantId || '')
const { orderObj, patch, effects } = buildBoutiqueOrderHydration({
options,
previousOrderObj,
orderTypeList,
scene,
userInfo,
isErrorOrder,
associateOrderType,
merchantBrands: canReuseMerchantBrandContext
? this.data.customerDailyFieldMerchantBrands || []
: []
})
effects.forEach(effect => {
if (effect.type === 'setNavigationBarTitle') {
wx.setNavigationBarTitle({ title: effect.title })
}
if (
effect.type === 'enableAlertBeforeUnload' &&
wx.enableAlertBeforeUnload
) {
wx.enableAlertBeforeUnload({
title: effect.title,
message: effect.message
})
}
})
this._boutiqueCustomerDailyFieldsEchoPending = true
this._boutiqueCustomerDailyRequestId =
(this._boutiqueCustomerDailyRequestId || 0) + 1
this.setData(
{
orderObj,
...patch
},
() => {
this.loadBoutiqueCustomerTagOptions(orderObj.merchantId)
this.echoCustomerProfileIfNeeded(options)
this._setOrderObjInvoked = false
}
)
if (paymentMethod && scene) {
if (paymentMethod == 1 && options.yqMerchantId) {
let oParams = {}
oParams.yqMerchantId = options.yqMerchantId
api.getYqStoreConfig(oParams).then(res => {
let obj = res.data || {}
let m = obj.supportPayTypes || []
let n = this.data.payTypeList
let list = n.filter(k => {
let idx = m.find(j => j == k.value)
return idx >= 0
})
this.setData({
['orderObj.selectPayType']: list[0]?.value, // 默认线上支付,微信或pos机或支付宝
['orderObj.payeeType']: 0
})
})
}
if (paymentMethod != 1 && paymentMethod != 5) {
this.setData({
['orderObj.selectPayType']:
paymentMethod == 3
? PAY_TYPE.SHOP
: paymentMethod == 4
? PAY_TYPE.TRANSFER
: PAY_TYPE.OTHER,
['orderObj.payeeType']:
paymentMethod == 3 ? PAYEE_TYPE.SHOP : PAYEE_TYPE.DJ
})
}
}
this.getSelectOrderGoodsList(orderObj.merchantId)
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: async function (options) {
const originSetData = this.setData.bind(this)
this.setData = (updates, callback) => {
if (updates && typeof updates === 'object' && shouldSyncPagePopup(updates)) {
const merged = mergeSetDataForPopupLock(this.data, updates)
updates = {
...updates,
pagePopupVisible: computePagePopupVisible(merged)
}
}
return originSetData(updates, callback)
}
this.debouncedSetGoodsTotal = wx.$util.debounce(this.setGoodsTotal, 500)
/*获取屏幕高度*/
this.setData({
windowHeight: getSystemInfoSync().windowHeight
})
const userInfo = wx.$util.getUserInfo() || {}
const initialCreateAllGoodsFlag = resolveCreateAllGoodsFlag(
undefined,
userInfo.sceneType
)
this.setData({
userInfo
})
this.applyOrderTypeConfig(initialCreateAllGoodsFlag, {
preserveOrderType: true
})
if (options.scene) {
this.setData({
...options,
returnFun: true
})
}
if (options.orderCode) {
await this.onRoute(options)
}
await this.prefillRecentScene()
this.getUserSceneList()
this.prefillLastSeller()
// 添加埋点
wx.$track.setTrackData(0, 'submit_order', {}, '', 1)
},
/**
* 扫码 / scene 礼券入参:解析 scene 并拉取礼券详情写入订单。
* 须在路由策略 setData 写入 scene 之后调用(见 onRoute / onShow)。
* @param {Object} userInfo
* @param {string} sceneRaw 编码后的 scene 参数字符串
*/
applyCouponFromScene(userInfo, sceneRaw) {
if (!sceneRaw) return
let scene = decodeURIComponent(sceneRaw)
if (userInfo.userType == 2) {
let id = scene.split('=')[1]
api
.getCouponDeatil({
id
})
.then(info => {
let { code, data, message } = info
if (code == 0) {
if (data.usedFlag == 'Y') {
wx.showModal({
content: '该礼券已被使用',
confirmText: '知道了',
confirmColor: '#347BFF',
showCancel: false,
success(res) {
if (res.confirm) wx.$router.back()
}
})
return
}
this.setOrderObj(data)
api
.getOrderByCustomerCouponId({
customerCouponId: id
})
.then(res => {
let { code, data, message } = res
if (code == 0) {
this.setData({
['orderObj.orderCode']: data.orderCode
})
} else {
this.showToast(message)
}
})
} else {
this.showToast(message)
}
})
} else {
wx.showModal({
title: '温馨提示',
content: '您的账号无法完成此操作',
confirmText: '知道了',
confirmColor: '#347BFF',
showCancel: false,
success(res) {
if (res.confirm) {
wx.$util.refreshPageData()
wx.$router.go('index')
}
}
})
}
},
init(userInfo) {
let { scene, orderObj } = this.data
if (!orderObj.sellerMerchantName) {
orderObj.sellerMerchantName = userInfo.merchantName
orderObj.sellerName = userInfo.name
orderObj.sellerMerchantId = userInfo.merchantId
orderObj.sellerUserId = userInfo.uuid
this.setData({
orderObj
})
}
if (scene) {
this.applyCouponFromScene(userInfo, scene)
}
},
/**
* 拉取一次精品选品池,同时生成分类列表和活动元数据。
* 同参数并发请求会共享 Promise;请求代次保证门店/场景切换后旧响应不会覆盖新状态。
* 仅 first 为 true 时回显已选商品,后续刷新不会覆盖 goodsList。
* 部位分桶仅适用于 goodsFlag==1 单商品(有 1–7 部位即入桶,不限太阳膜品类);
* 多规格 → otherProduct;套餐 → packageList(见 selectOrderCatalogClassification)。
* @param {string|number} merchantId 当前销售门店
* @param {string|number} sceneType 场景类型,合法的 0 必须保留
* @returns {Promise<void>}
*/
async getSelectOrderGoodsList(merchantId, sceneType = this.data.orderObj.sceneType) {
if (!merchantId) return
const request = {
merchantId,
sceneType: sceneType ?? 1,
baseSceneCode: this.data.orderObj?.baseSceneCode || ''
}
const requestGeneration = (this._catalogRequestGeneration || 0) + 1
this._catalogRequestGeneration = requestGeneration
if (!this._catalogRequestCoordinator) {
this._catalogRequestCoordinator = createCatalogRequestCoordinator(params =>
api.getSelectOrderGoodsList(params)
)
}
try {
const [positionTypeList = [], baseConfigData, result] = await Promise.all([
getPositionList(),
setConfigInfo(app.globalData),
this._catalogRequestCoordinator.run(request)
])
if (requestGeneration !== this._catalogRequestGeneration) return
if (result.code != 0) {
wx.$util.showToast(result.message)
return
}
const { first, orderObj } = this.data
const viewModel = buildCreateOrderCatalogViewModel(result.data, {
subOrderList: orderObj?.subOrderList
})
const { subOrderList, ...catalogPatch } = viewModel
const patch = { positionTypeList, baseConfigData, ...catalogPatch }
// 编辑/再次下单仅首次由详情回显商品,主动刷新只更新可选目录。
if (first && subOrderList.length) {
patch.goodsList = subOrderList
patch['orderObj.subOrderList'] = subOrderList
}
await new Promise(resolve => this.setData(patch, resolve))
if (first) this.getChooseList()
} catch (error) {
console.warn('精品选品池加载失败', error)
} finally {
wx.hideLoading()
}
},
remarkConfirm(e) {
let value = e.detail
this.setData({
['orderObj.remark']: value,
...closePagePopupPatch('showRemark')
})
},
/**
* 从订单快照和当前目录重建商品选择列表,保留既有公开方法名。
* @returns {void}
*/
getChooseList() {
const { goodsList } = buildBoutiqueChooseList({
orderObj: this.data.orderObj,
goodsData: this.data.goodsData,
copyGoodsData: this.data.copyGoodsData,
packageList: this.data.packageList,
otherProduct: this.data.otherProduct,
marketingFlagMap: this.data.marketingFlagMap,
activityIdMap: this.data.activityIdMap
})
this.setData({
goodsList,
first: false
})
this.setGoodsTotal(goodsList)
},
handleVinInput(value, autoValidate = false, type = 'standNo') {
let { orderObj } = this.data
const formattedValue = formatVinInput(value || '')
orderObj.customer[type] = formattedValue
this.setData({
orderObj
})
// 扫描时立即校验,手动输入时需达到17位才校验
if (formattedValue && (autoValidate || formattedValue.length === 17)) {
validateVin(formattedValue)
.then(result => {
let { valid } = result.data.data
// 校验成功,所有提示已在公共方法中处理
this.setData({
vinValid: valid
})
})
.catch(() => {
// 公共校验方法已展示失败提示,保留当前输入供用户修正。
})
}
},
getSetting() {
// 动态获取 车型 车架 车牌 是否必填
let { dynamicSetting, requiredList } = this.data
// app .
getYQorderInfo()
.then(merchantSettingInfo => {
let dictionaryObj = {
carTypeRequiredFlag: 'carBrand',
standNoRequiredFlag: 'standNo',
plateNumRequiredFlag: 'plateNumber'
}
for (const key in dictionaryObj) {
if (merchantSettingInfo[key] == 'Y') {
requiredList.push(dictionaryObj[key])
}
}
this.setData({
requiredList: [...new Set(requiredList)],
phoneShow: wx.$util.deepClone(merchantSettingInfo.yqPhoneConfig)
})
})
.catch(() => {
// 门店设置加载失败时沿用页面默认必填与支付配置。
})
},
// 获取园区店支付配置
getConfig() {
let orderObj = wx.$util.deepClone(this.data.orderObj)
let o = this.data.orderObj
let oParams = {}
oParams.yqMerchantId = o.sellerMerchantId
api.getYqStoreConfig(oParams).then(res => {
let obj = res.data || {}
let m = obj.supportPayTypes || []
let n = this.data.payTypeList
let list = n.filter(k => {
let idx = m.find(j => j == k.value)
return idx >= 0
})
this.setData({
configPayTypeList: list
})
this.settingPayType(orderObj)
})
},
/**
* 一次性应用收款方、支付方式与可选列表决策,保留既有公开方法名。
* @param {object} orderObj 当前订单快照
* @returns {void}
*/
settingPayType(orderObj) {
this.setData(
buildBoutiquePaymentSelectionPatch({
configPayTypeList: this.data.configPayTypeList,
isErrorOrder: this.data.isErrorOrder,
switchVlaue: this.data.switchVlaue,
selectOutTradeNoArr: this.data.selectOutTradeNoArr,
paymentMethod: this.data.paymentMethod,
isAppointment: this.data.isAppointment,
orderObj: orderObj || this.data.orderObj
})
)
},
/**
* 按门店配置与业务场景同步订单类型 picker(限制场景:正常订单 + 内部结算)
* @param {0|1} createAllGoodsFlag
* @param {{ preserveOrderType?: boolean }} [options]
*/
applyOrderTypeConfig(createAllGoodsFlag, options = {}) {
const { orderTypeList, orderObj } = this.data
const orderTypePickerList = buildOrderTypePickerList(
orderTypeList,
createAllGoodsFlag
)
const patch = { createAllGoodsFlag, orderTypePickerList }
const isExistingOrder = orderObj && !!orderObj.id
const isDisallowedType =
orderObj &&
orderObj.djOrderType &&
!isAllowedLimitedOrderType(orderObj.djOrderType)
if (
createAllGoodsFlag === 0 &&
!options.preserveOrderType &&
!(isExistingOrder && isDisallowedType) &&
!isAllowedLimitedOrderType(orderObj?.djOrderType)
) {
patch.orderTypeName = '正常订单'
patch['orderObj.djOrderType'] = ORDER_TYPE.NORMAL
}
this.setData(patch)
},
getShopMerchantPointConfig() {
const { userInfo } = this.data
const shopMerchantId = userInfo?.shopMerchantId
if (!shopMerchantId) return
api.getShopMerchantPointConfig({ merchantId: shopMerchantId }).then(res => {
if (res?.code != 0 || !res?.data) return
const { pointsMultiRole, createAllGoodsFlag: rawFlag } = res.data
const createAllGoodsFlag = resolveCreateAllGoodsFlag(
rawFlag,
userInfo?.sceneType
)
if (pointsMultiRole == 'Y') {
toastList.userId = '销售顾问/录单员不能为空'
}
this.applyOrderTypeConfig(createAllGoodsFlag)
this.setData({ pointsMultiRole })
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.getConfig()
this.getShopMerchantPointConfig()
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
wx.disableAlertBeforeUnload && wx.disableAlertBeforeUnload() //关闭小程序页面返回询问对话框
},
async onRoute(res) {
this._setOrderObjInvoked = false
try {
const routeContext = new RouteContext(this)
await routeContext.execute(res)
if (res && res.scene) {
const userInfo = this.data.userInfo || wx.$util.getUserInfo()
if (userInfo) this.applyCouponFromScene(userInfo, res.scene)
}
// 未走 setOrderObj 的策略(如补录)在 onRoute 末尾补全客户档案
if (!this._setOrderObjInvoked) {
await this.echoCustomerProfileIfNeeded(res)
}
} catch (error) {
console.error('onRoute execution failed:', error)
// Fallback: 至少保证页面不白屏
wx.$util.hideLoading()
this.setData({ flag: true })
}
},
getLatestAccountDate(list) {
if (!list || list.length === 0) return null // 处理空数组
// 获取最大的时间戳
const latestTimestamp = list.reduce((max, item) => {
return Math.max(max, item.accountDateValue)
}, -Infinity)
return new Date(latestTimestamp).format('yyyy-MM-dd hh:mm:ss')
},
applyBoutiqueCustomerDailyFields(
customer = this.data.orderObj?.customer || {},
tagOptions = this.data.customerTagOptions || []
) {
if (this._boutiqueCustomerDailyFieldsEchoPending) {
const pendingCustomer = coordinateBoutiqueCustomerDailyFieldsEcho({
phase: 'pending',
customer
})
this.setData({ 'orderObj.customer': pendingCustomer })
return
}
const visibilityContext = {
baseSceneName: this.data.orderObj?.baseSceneName,
baseSceneCode: this.data.orderObj?.baseSceneCode,
merchantBrands: this.data.customerDailyFieldMerchantBrands || []
}
const nextCustomer = reconcileBoutiqueCustomerDailyFields(
customer,
tagOptions,
visibilityContext
)
this.setData({
'orderObj.customer': nextCustomer,
customerTagsText: formatCustomerTags(nextCustomer.customerTags),
showCustomerTags: isBoutiqueCustomerTagsVisible(nextCustomer.salesType),
showActualDeliveryDate: isBoutiqueActualDeliveryDateVisible({
...visibilityContext,
salesType: nextCustomer.salesType
})
})
},
async loadBoutiqueCustomerTagOptions(merchantId) {
const requestMerchantId = merchantId || ''
const requestId = (this._boutiqueCustomerDailyRequestId || 0) + 1
this._boutiqueCustomerDailyRequestId = requestId
let customerTagOptions = getBoutiqueCustomerTagOptions()
let merchantBrands = []
if (requestMerchantId) {
try {
const res = await api.getMerchantCarBrandList([requestMerchantId])
merchantBrands =
res?.code == 0 ? res?.data?.data?.[0]?.carBrandList || [] : []
customerTagOptions = getBoutiqueCustomerTagOptions(merchantBrands)
} catch (error) {
// 品牌标签配置是展示增强项,失败时回退到通用标签配置。
}
}
const currentMerchantId = this.data.orderObj?.merchantId || ''
const currentRequestId = this._boutiqueCustomerDailyRequestId
const nextCustomer = coordinateBoutiqueCustomerDailyFieldsEcho({
phase: 'resolved',
customer: this.data.orderObj?.customer,
tagOptions: customerTagOptions,
context: {
baseSceneName: this.data.orderObj?.baseSceneName,
baseSceneCode: this.data.orderObj?.baseSceneCode,
merchantBrands
},
requestMerchantId,
currentMerchantId,
requestId,
currentRequestId
})
if (!nextCustomer) return
this.setData(
{
customerTagOptions,
customerDailyFieldMerchantBrands: merchantBrands,
customerDailyFieldBrandMerchantId: requestMerchantId
},
() => {
const resolvedCustomer = coordinateBoutiqueCustomerDailyFieldsEcho({
phase: 'resolved',
customer: this.data.orderObj?.customer,
tagOptions: customerTagOptions,
context: {
baseSceneName: this.data.orderObj?.baseSceneName,
baseSceneCode: this.data.orderObj?.baseSceneCode,
merchantBrands
},
requestMerchantId,
currentMerchantId: this.data.orderObj?.merchantId || '',
requestId,
currentRequestId: this._boutiqueCustomerDailyRequestId
})
if (!resolvedCustomer) return
this._boutiqueCustomerDailyFieldsEchoPending = false
this.applyBoutiqueCustomerDailyFields(
resolvedCustomer,
customerTagOptions
)
}
)
},
openCustomerTagsPopup() {
if (!this.data.showCustomerTags) return
const selected = new Set(
parseCustomerTags(this.data.orderObj?.customer?.customerTags)
)
this.setData({
customerTagsPopup: true,
customerTagDraftOptions: (this.data.customerTagOptions || []).map(item => ({
...item,
checked: selected.has(item.value)
}))
})
},
onToggleCustomerTag(e) {
const index = Number(e.currentTarget.dataset.index)
const customerTagDraftOptions = (this.data.customerTagDraftOptions || []).map(
(item, itemIndex) =>
itemIndex === index ? { ...item, checked: !item.checked } : item
)
this.setData({ customerTagDraftOptions })
},
onCancelCustomerTags() {
this.setData({ customerTagsPopup: false })
},
onConfirmCustomerTags() {
const selected = (this.data.customerTagDraftOptions || [])
.filter(item => item.checked)
.map(item => item.value)
const customerTags = serializeCustomerTags(selected)
this.setData(
{
customerTagsPopup: false,
'orderObj.customer.customerTags': customerTags
},
() => this.applyBoutiqueCustomerDailyFields()
)
},
onCustomerDeliveryDateChange(e) {
this.setData({
'orderObj.customer.actualDeliveryDate': e.detail.value || ''
})
},
/**
* 打开客户来源选择器,并按当前业务值定位选项。
* 客户档案可能直接回填 salesType,不能沿用 Picker 上一次保留的内部索引。
* @returns {void}
*/
toSelectCustomerSource() {
const salesType = this.data.orderObj?.customer?.salesType
const selectedIndex = (this.data.Sourcecolumns || []).findIndex(
item => String(item.type) === String(salesType)
)
this.setData({
customerSourcePickerIndex: selectedIndex >= 0 ? selectedIndex : 0,
showSource: true
})
},
onChangeSource(e) {
const { type } = e.detail.value
const customer = {
...(this.data.orderObj?.customer || {}),
salesType: type
}
this.setData({ showSource: false }, () => {
this.applyBoutiqueCustomerDailyFields(customer)
})
},
onCloseSource() {
this.setData({
showSource: false
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {}
})