submitStrategy.js
11.4 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
import {
checkDailyReport,
checkStudyTask,
checkOrderLockGate
} from '~/store/ModalToQueueControl'
import { buildAdditionRecordLockBypassContext } from '~/utils/abnormalFlowLock.helpers.js'
import api from '../../api'
import { prepareSubmitPayload } from './services/submitPayload.helpers.js'
import {
isBoutiqueErrorOrderBalanced,
isBoutiqueTotalAtLeastOneCent
} from './services/goodsPriceEdit.helpers.js'
import {
buildSubmitUiResult,
resolveBoutiqueSubmitAction,
runValidationPipeline,
runWithSubmitLock,
submitBoutiqueOrder
} from './services/submitWorkflow.js'
// ----------------------------------------------------------------------
// 辅助构造函数:校验结果
// ----------------------------------------------------------------------
function ValidationResult(isValid, message, errorKey, presentation) {
this.isValid = isValid
this.message = message || null
this.errorKey = errorKey || null
this.presentation = presentation || null
}
ValidationResult.success = function () {
return new ValidationResult(true)
}
ValidationResult.failure = function (message) {
return new ValidationResult(false, message)
}
// ----------------------------------------------------------------------
// 策略基类 (模拟)
// ----------------------------------------------------------------------
// 实际上不需要复杂的继承结构,只需确保每个策略对象都有 validate 方法即可。
// 这里使用工厂函数模式来创建策略对象。
// 1. 异步前置校验 (日报、学习任务、配置)
function AsyncPreCheckStrategy(page, context) {
this.page = page
this.context = context
}
AsyncPreCheckStrategy.prototype.validate = async function () {
// 校验是否填写昨日日报
let staffCheck = await checkDailyReport()
if (staffCheck) return ValidationResult.failure(null) // checkDailyReport 自带提示或跳转
// 校验学习中心开单限制
let staffStudyTask = await checkStudyTask()
if (staffStudyTask) return ValidationResult.failure(null)
let lockCheck = await checkOrderLockGate(
buildAdditionRecordLockBypassContext(this.page.data)
)
if (lockCheck) return ValidationResult.failure(null)
// 判断手机号是否用配置的默认值
this.page.checkPhoneUseConfig()
return ValidationResult.success()
}
// 2. 状态与权限校验
function StatePermissionStrategy(page, context) {
this.page = page
this.context = context
}
StatePermissionStrategy.prototype.validate = async function () {
const save = this.context.save
const data = this.page.data
const isErrorOrder = data.isErrorOrder
const isAlreadyExistOrder = data.isAlreadyExistOrder
const orderCreateType = data.orderCreateType
// 如果是错单补录 禁用掉保存功能 或待跟进订单/预约订单 或补录工单 禁用建档
if (
(isErrorOrder && save) ||
(isAlreadyExistOrder && save) ||
(orderCreateType == 'additionRecordOrder' && save)
) {
return ValidationResult.failure(null)
}
return ValidationResult.success()
}
// 3. 必填项校验
function RequiredFieldStrategy(page, context) {
this.page = page
this.context = context
}
RequiredFieldStrategy.prototype.validate = async function () {
const save = this.context.save
const orderObj = this.page.data.orderObj
const result = this.page.checkRequired(save, orderObj)
if (!result.ok) {
return new ValidationResult(
false,
result.message,
result.errorKey,
result.presentation
)
}
return ValidationResult.success()
}
// 4. VIN码校验
function VinValidationStrategy(page, context) {
this.page = page
this.context = context
}
VinValidationStrategy.prototype.validate = async function () {
const data = this.page.data
const orderObj = data.orderObj
const vinValid = data.vinValid
const carVin = orderObj.customer.standNo
if (carVin) {
if (carVin.length !== 17) {
return ValidationResult.failure(
'请输入 17 位有效字符(支持大写 A-H/J-N/P-Z、0-9)'
)
}
if (!vinValid) {
return ValidationResult.failure('车架号校验不匹配,请核对后重新输入')
}
}
return ValidationResult.success()
}
// 5. 商品校验
function GoodsValidationStrategy(page, context) {
this.page = page
this.context = context
}
GoodsValidationStrategy.prototype.validate = async function () {
const save = this.context.save
const data = this.page.data
const goodsList = data.goodsList
const orderObj = data.orderObj
// 调用页面的 checkGoods 方法
let goodsKey = this.page.checkGoods(save, goodsList, orderObj)
if (goodsKey) {
return ValidationResult.failure(goodsKey)
}
return ValidationResult.success()
}
// 6. 错单金额校验
function ErrorOrderPriceStrategy(page, context) {
this.page = page
this.context = context
}
ErrorOrderPriceStrategy.prototype.validate = async function () {
const data = this.page.data
const isErrorOrder = data.isErrorOrder
const totalFee = data.totalFee
const total = data.total
const orderObj = data.orderObj
if (isErrorOrder) {
const balance = isBoutiqueErrorOrderBalanced({
originalPrice: orderObj.finalPrice,
associatedFeeCents: totalFee,
currentTotal: total
})
if (!balance.ok) {
return ValidationResult.failure('订单金额格式不正确')
}
if (!balance.value) {
return ValidationResult.failure(
'原错误订单总价+关联交易流水必须等于商品总价'
)
}
}
return ValidationResult.success()
}
// 7. 总价校验
function TotalPriceStrategy(page, context) {
this.page = page
this.context = context
}
TotalPriceStrategy.prototype.validate = async function () {
const save = this.context.save
const data = this.page.data
const orderObj = data.orderObj
// 建档或战败单不校验
if (save || orderObj.selectPayType == 0) {
return ValidationResult.success()
}
const total = isBoutiqueTotalAtLeastOneCent(data.total)
if (!total.ok) {
return ValidationResult.failure('订单金额格式不正确')
}
if (!total.value) {
return ValidationResult.failure('订单总价不能小于0.01元')
}
return ValidationResult.success()
}
// ----------------------------------------------------------------------
// 提交上下文 (Main Entry)
// ----------------------------------------------------------------------
function SubmitContext(page) {
this.page = page
}
/**
* 从页面事件进入精品提交,并在校验、组装、请求和异常提示期间持有提交锁。
* @param {WechatMiniprogram.BaseEvent} event
* @returns {Promise<{status:string,value?:*}>}
*/
SubmitContext.prototype.execute = async function (event) {
const dataset = event.currentTarget.dataset
const save = dataset.save
const context = { save: save }
return runWithSubmitLock(
{
isLocked: () => Boolean(this.page.data.submitStatus),
setLocked: locked => this.page.setData({ submitStatus: locked })
},
async () => {
try {
return await this.executeUnlocked(context)
} catch (error) {
console.warn('精品开单提交失败', error)
wx.showModal({
title: '温馨提示',
content: error?.message || '提交失败,请稍后重试',
showCancel: false,
confirmText: '知道了',
confirmColor: '#347BFF'
})
} finally {
setTimeout(function () {
wx.hideLoading()
}, 2000)
}
}
)
}
/**
* 执行锁内的精品校验、payload 构建与提交。
* @param {{save:boolean}} context
* @returns {Promise<*>}
*/
SubmitContext.prototype.executeUnlocked = async function (context) {
const save = context.save
// 1. 构建校验链
const strategies = [
new AsyncPreCheckStrategy(this.page, context),
new StatePermissionStrategy(this.page, context),
new GoodsValidationStrategy(this.page, context),
new RequiredFieldStrategy(this.page, context),
new VinValidationStrategy(this.page, context),
new ErrorOrderPriceStrategy(this.page, context),
new TotalPriceStrategy(this.page, context)
]
// 2. 执行校验
const validation = await runValidationPipeline(strategies)
if (!validation.ok) {
if (validation.message) {
if (validation.presentation === 'toast') {
this.page.showToast(validation.message)
} else {
wx.showModal({
title: '温馨提示',
content: validation.message,
showCancel: false,
confirmText: '知道了',
confirmColor: '#347BFF'
})
}
}
if (validation.errorKey) {
this.page.handleRequiredError(validation.errorKey)
}
return
}
// 3. 准备并提交
await this.finishSubmit(save)
}
/**
* 构建提交参数并二次核对业务模式与 API 选择,防止重构后静默串接口。
* @param {boolean} save 是否建档
* @returns {Promise<void>}
*/
SubmitContext.prototype.finishSubmit = async function (save) {
const preparedData = this.prepareSubmitData(save)
const submitObj = preparedData.submitObj
const action = resolveBoutiqueSubmitAction({
save,
isErrorOrder: this.page.data.isErrorOrder,
isAlreadyExistOrder: this.page.data.isAlreadyExistOrder,
orderCreateType: this.page.data.orderCreateType,
selectPayType: submitObj.selectPayType
})
if (action.method !== preparedData.apiName) {
throw new Error('精品提交接口选择不一致')
}
await this.doSubmit(submitObj, action)
}
/**
* 从页面订单态生成精品 API payload,保留原契约字段和值。
* @param {boolean} save 是否建档
* @returns {{submitObj:object,apiName:string}}
*/
SubmitContext.prototype.prepareSubmitData = function (save) {
const data = this.page.data
return prepareSubmitPayload(data.orderObj, {
save,
isErrorOrder: data.isErrorOrder,
orderCreateType: data.orderCreateType,
scene: data.scene,
merchantBrands: data.customerDailyFieldMerchantBrands
})
}
/**
* 执行已选定的精品 API,并只在页面层处理提示、刷新和语义路由。
* @param {object} submitObj API payload
* @param {{method:string,mode:string}} action 提交动作
* @returns {Promise<void>}
*/
SubmitContext.prototype.doSubmit = async function (submitObj, action) {
const page = this.page
const outcome = await submitBoutiqueOrder(
{ method: action.method, payload: submitObj },
api
)
const res = outcome.response
const uiResult = buildSubmitUiResult({
mode: action.mode,
response: res,
pageContext: page.data
})
if (outcome.status === 'success') {
wx.disableAlertBeforeUnload && wx.disableAlertBeforeUnload() // 关闭页面返回询问对话框
if (action.mode === 'prerecorded') {
wx.showModal({
title: '温馨提示',
content: '保存成功',
showCancel: false,
confirmText: '知道了',
confirmColor: '#347BFF',
success: function (_res_) {
if (_res_.confirm) {
// 预录建档跳转到预约列表
wx.$util.refreshPageData()
wx.$router.go(uiResult.navigation.alias)
wx.$util.pointRecord(30)
}
}
})
} else {
// 状态更新需刷新工单列表和预约管理列表
wx.$util.refreshPageData()
wx.$router.redirectTo(
uiResult.navigation.alias,
uiResult.navigation.params
)
}
} else {
wx.showModal({
title: '温馨提示',
content: uiResult.message,
showCancel: false,
confirmText: '知道了',
confirmColor: '#347BFF'
})
}
}
export { SubmitContext }