staffDailyReport.js
14.8 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
/**
* 驻店日报 API 门面 — Page/Loader 唯一入口
* @see packageDynamicForm/docs/PAGES.md#驻店日报-新staffdailyreport
* @see packageDynamicForm/docs/ARCHITECTURE.md
*
* 职责:fetchPageContext、fetchSchema、save/submit、normalizeUserInfo
* 实现:委托 staffDailyReportAdapters(mock/real);save 走 buildDailyReportSaveRequest
* templateType:1
*/
const { buildPageContext } = require('../fixtures/mock-meta.js')
const { dynamicDailyReportSave } = require('./dynamicDailyReport.js')
const {
DEFAULT_REPORT_TEMPLATE_ID: { staff: STAFF_DEFAULT_REPORT_TEMPLATE_ID }
} = require('../config/dailyReportConstants.js')
import { envIndex } from '~/config.js'
import {
parseJsonContentDetailValues,
mapBrandListToBrandIds,
mergeValuesIntoSchema
} from '../form-engine/submit-adapter.js'
import {
parseDetailEchoValues,
stripValuesFromSchemaRoot
} from '../form-engine/detail-echo.js'
import { mergeTemplateDefaultsIntoInitialValues } from '../form-engine/values.js'
import { enrichPageContextWithDetailEcho } from '../form-engine/app-subform-json.js'
const { buildDailyReportSaveRequest } = require('../form-engine/save-request.js')
import {
resolveBaseSceneCode
} from '../form-engine/page-context.js'
const {
fetchDetailAdapter,
fetchSchemaRootAdapter,
fetchSceneAdapter,
fetchBrandAdapter,
fetchWeeklyAdapter,
saveEchoAdapter
} = require('./staffDailyReportAdapters.js')
const { isStaffMockMode } = require('../config/apiSwitch.js')
const { fetchDailyReportCarBrandList: fetchCarBrandListImpl } = require('./dailyReportCarBrand.js')
const {
DAILY_REPORT_TEMPLATE_TYPE,
DAILY_REPORT_SOURCE
} = require('../config/dailyReportConstants.js')
const {
normalizeDailyReportUserInfo
} = require('../utils/user-merchant.js')
const {
unwrapApiResponse,
resolveDetailGetResponse,
isApiSuccess,
isEmptyDetailPayload
} = require('../utils/api-response.js')
const { normalizeReportStatus } = require('../utils/report-status.js')
const IS_PRODUCTION = envIndex === 3
/**
* 规范化用户信息,补齐 merchantId、staffUuid 等日报所需字段
* @param {Object} [userInfo={}] 原始用户信息
* @returns {Object} 规范化后的用户上下文
*/
function normalizeUserInfo(userInfo = {}) {
return normalizeDailyReportUserInfo(userInfo)
}
/**
* 从品牌、场景、详情等来源组装 pageContext
* @param {Object} [options={}]
* @param {Object} [options.userInfo] 用户信息
* @param {Array} [options.brandIds] 经营品牌 ID 列表
* @param {Object} [options.detail] 日报详情
* @param {string} [options.baseSceneCode] 门店场景编码
* @param {Array} [options.sceneList] 可选场景列表
* @returns {Object} pageContext 对象
*/
function buildPageContextFromSources({
userInfo = {},
brandIds = [],
merchantCarBrandList = [],
detail = {},
baseSceneCode,
sceneList,
carBrandList = []
} = {}) {
const normalized = normalizeUserInfo(userInfo)
const pageContext = buildPageContext(
{ baseSceneCode },
brandIds,
normalized,
sceneList || []
)
const enriched = enrichPageContextWithDetailEcho(pageContext, detail)
return {
...enriched,
sceneType: normalized.sceneType,
yqMerchantName: normalized.yqMerchantName,
merchantCarBrandList: Array.isArray(merchantCarBrandList) ? merchantCarBrandList : [],
carBrandList: Array.isArray(carBrandList) ? carBrandList : []
}
}
/** 统一 API 响应结构 { code, message, data } */
function unwrapResponse(result = {}) {
return unwrapApiResponse(result)
}
/** 场景列表兜底为数组 */
function normalizeSceneListData(data) {
return Array.isArray(data) ? data : []
}
/**
* 获取门店可选场景列表并解析 baseSceneCode
* @param {Object} [options={}]
* @param {string|number} [options.merchantId] 门店 ID
* @param {string} [options.detailBaseSceneCode] 详情中已有的场景编码
* @param {boolean} [options.hasRecord] 是否已有日报记录
* @returns {Promise<{code: number, message: string, baseSceneCode: string|null, sceneList: Array}>}
*/
async function fetchMerchantScene({
merchantId,
shopMerchantId,
staffUuid,
phone,
sceneType,
detailBaseSceneCode,
hasRecord
} = {}) {
if (!merchantId) {
return {
code: 0,
message: 'ok',
baseSceneCode: resolveBaseSceneCode([], detailBaseSceneCode, hasRecord),
sceneList: []
}
}
const result = await fetchSceneAdapter({
merchantId,
shopMerchantId,
staffUuid,
phone,
sceneType
})
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
return {
code: code ?? -1,
message,
baseSceneCode: resolveBaseSceneCode([], detailBaseSceneCode, hasRecord),
sceneList: []
}
}
const sceneList = normalizeSceneListData(data)
return {
code: 0,
message: 'ok',
baseSceneCode: resolveBaseSceneCode(sceneList, detailBaseSceneCode, hasRecord),
sceneList
}
}
/**
* 获取门店经营品牌 ID 列表
* @param {Object} [options={}]
* @param {string|number} [options.merchantId] 门店 ID
* @returns {Promise<{code: number, message: string, data: Array}>}
*/
async function fetchMerchantBrandIds({ merchantId } = {}) {
if (!merchantId) {
return { code: 0, message: 'ok', data: [] }
}
const result = await fetchBrandAdapter({ merchantId })
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
return { code: code ?? -1, message, data: [] }
}
const brandList = Array.isArray(data) ? data : []
return {
code: 0,
message: 'ok',
data: mapBrandListToBrandIds(brandList),
merchantCarBrandList: Array.isArray(result.merchantCarBrandList)
? result.merchantCarBrandList
: []
}
}
async function fetchDailyReportCarBrandList({ merchantId, sceneType } = {}) {
return fetchCarBrandListImpl({
merchantId,
sceneType,
useMock: isStaffMockMode('brand')
})
}
/**
* 组装表单 pageContext(品牌、场景、用户信息)
* @param {Object} [options={}]
* @param {Object} [options.userInfo] 用户信息
* @param {Array} [options.brandIds] 经营品牌 ID 列表
* @param {Object} [options.detail] 日报详情
* @param {Object} [options.merchantScene] fetchMerchantScene 返回值
* @param {Array} [options.carBrandList] 保存用车型列表
* @returns {Promise<{code: number, message: string, data: Object|null}>}
*/
async function fetchPageContext(options = {}) {
const {
userInfo = {},
brandIds = [],
merchantCarBrandList = [],
detail = {},
merchantScene = {},
carBrandList = []
} = options
const normalizedUser = normalizeUserInfo(userInfo)
const hasRecord = !!detail.dailyReportRecordId
let baseSceneCode = resolveBaseSceneCode(
merchantScene.sceneList || [],
detail.baseSceneCode,
hasRecord
)
if (baseSceneCode == null) {
baseSceneCode = merchantScene.baseSceneCode ?? normalizedUser.baseSceneCode ?? null
}
if (baseSceneCode == null) {
return {
code: -1,
message: '无法确定门店场景,请检查场景配置',
data: null
}
}
return {
code: 0,
message: 'ok',
data: buildPageContextFromSources({
userInfo,
brandIds,
merchantCarBrandList,
detail,
baseSceneCode,
sceneList: merchantScene.sceneList || [],
carBrandList
})
}
}
/** 无记录时的空 detail 占位 */
function buildEmptyDetail(reportTemplateId) {
return {
reportTemplateId: reportTemplateId || STAFF_DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: null,
reportStatus: '0',
values: {}
}
}
/**
* 按日期拉取驻店日报详情
* @param {Object} [options={}]
* @param {string|number} [options.merchantId] 门店 ID
* @param {string} [options.staffUuid] 员工 UUID
* @param {string} [options.reportDate] 报表日期 YYYY-MM-DD
* @param {number|string} [options.reportTemplateId] 模板 ID
* @returns {Promise<{code: number, message: string, data: Object|null}>}
*/
async function fetchReportDetail({
merchantId,
staffUuid,
reportDate,
reportTemplateId,
sceneType
} = {}) {
if (!merchantId || !staffUuid || !reportDate) {
return {
code: 0,
message: 'ok',
data: buildEmptyDetail(reportTemplateId)
}
}
const result = await fetchDetailAdapter({
merchantId,
staffUuid,
reportDate,
reportTemplateId,
sceneType
})
const resolved = resolveDetailGetResponse(result, buildEmptyDetail, reportTemplateId)
if (!isApiSuccess(resolved.code)) {
return resolved
}
if (isEmptyDetailPayload(result?.data)) {
return resolved
}
return normalizeDetailResponse(resolved.data, reportTemplateId)
}
/** 将 adapter 返回的 detail 规范化为 { reportTemplateId, dailyReportRecordId, baseSceneCode, values } */
function normalizeDetailResponse(detail = {}, reportTemplateId) {
const recordId = detail.dailyReportRecordId ?? detail.id ?? null
return {
code: 0,
message: 'ok',
data: {
reportTemplateId: detail.reportTemplateId || reportTemplateId || STAFF_DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: recordId,
baseSceneCode: detail.baseSceneCode,
reportStatus: normalizeReportStatus(detail.reportStatus),
values: parseJsonContentDetailValues(detail.jsonContent, []),
jsonContent: detail.jsonContent,
fieldDataList: detail.fieldDataList || [],
subformDataList: detail.subformDataList || []
}
}
}
/**
* 拉取表单 schema 并合并已有填报值
* @param {Object} [options={}]
* @param {number|string} [options.reportTemplateId] 模板 ID
* @param {string} [options.baseSceneCode] 门店场景编码
* @param {string|number} [options.merchantId] 门店 ID
* @param {Object} [options.detail] 完整详情(含 jsonContent / fieldDataList)
* @param {Object} [options.detailValues={}] 详情中的已有字段值(detail 缺省时 fallback)
* @returns {Promise<{code: number, message: string, data: Object|null}>}
*/
async function fetchSchema({
reportTemplateId,
baseSceneCode,
merchantId,
detail,
detailValues = {}
} = {}) {
const result = await fetchSchemaRootAdapter({
reportTemplateId,
baseSceneCode,
merchantId
})
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
if (isStaffMockMode('schema')) {
return { code: -1, message: message || '加载表单模板失败', data: null }
}
return { code: code ?? -1, message, data: null }
}
if (!data?.list) {
return { code: -1, message: '加载表单模板失败', data: null }
}
const initialValues = mergeTemplateDefaultsIntoInitialValues(
data.list,
parseDetailEchoValues(detail, data.list, detailValues)
)
const schema = stripValuesFromSchemaRoot(data)
return {
code: 0,
message: 'ok',
data: schema,
initialValues
}
}
function resolveSchemaDetailValues(detail, schemaList = [], fallbackValues = {}) {
if (!detail?.jsonContent || !schemaList.length) {
return fallbackValues
}
return parseJsonContentDetailValues(detail.jsonContent, schemaList)
}
/**
* 拉取周历提交标记列表(templateType=1)
* @param {Object} [options={}]
* @param {string|number} [options.merchantId] 门店 ID
* @param {string} [options.staffUuid] 员工 UUID
* @param {string} [options.reportStartDate] 周起始日期
* @param {string} [options.reportEndDate] 周结束日期
* @returns {Promise<{code: number, message: string, data: Array}>}
*/
async function fetchWeeklyList({
merchantId,
staffUuid,
reportStartDate,
reportEndDate,
sceneType
} = {}) {
if (!merchantId) {
return { code: 0, message: 'ok', data: [] }
}
const result = await fetchWeeklyAdapter({
merchantId,
staffUuid,
sceneType,
templateType: DAILY_REPORT_TEMPLATE_TYPE.staff,
reportStartDate,
reportEndDate
})
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
return { code: code ?? -1, message, data: [] }
}
return {
code: 0,
message: 'ok',
data: Array.isArray(data) ? data : []
}
}
/**
* 校验并提交驻店日报(dynamic.save + 可选 mock 回显)
* @param {Object} [payload={}]
* @param {Object} payload.engine formEngine 实例
* @param {number|string} payload.reportTemplateId 模板 ID
* @param {number|string|null} [payload.dailyReportRecordId] 已有记录 ID
* @param {string} payload.reportDate 报表日期
* @returns {Promise<{code: number, message: string, data: Object|null}>}
*/
async function submitForm(payload = {}) {
const { engine, reportTemplateId, dailyReportRecordId, reportDate } = payload
if (!engine) {
return { code: 10002, message: '表单未初始化', data: null }
}
if (!reportTemplateId) {
return { code: 10002, message: 'reportTemplateId 不能为空', data: null }
}
if (!reportDate) {
return { code: 10002, message: 'reportDate 不能为空', data: null }
}
const pageContext = engine.getPageContext() || {}
const userContext = normalizeUserInfo(wx.$util?.getUserInfo?.() || {})
const { request: saveRequest, fieldDataList, subformDataList } = buildDailyReportSaveRequest({
reportDate,
userContext,
pageContext,
engine,
reportTemplateId,
dailyReportRecordId,
templateType: DAILY_REPORT_TEMPLATE_TYPE.staff,
dailyReportSource: DAILY_REPORT_SOURCE.miniapp
})
if (!IS_PRODUCTION) {
console.log('[staffDailyReport] dynamic.save 提交数据结构', saveRequest)
console.log('[staffDailyReport] dynamic.save jsonContent', JSON.parse(saveRequest.jsonContent))
}
const result = await dynamicDailyReportSave(saveRequest)
const { code, message, data } = unwrapResponse(result)
if (code == 0) {
const savedRecord = saveEchoAdapter({
merchantId: saveRequest.merchantId,
staffUuid: userContext.staffUuid,
reportDate,
reportTemplateId,
dailyReportRecordId: data?.dailyReportRecordId || dailyReportRecordId,
fieldDataList,
subformDataList,
jsonContent: saveRequest.jsonContent
})
return {
code: 0,
message,
data: {
...(data || {}),
dailyReportRecordId: savedRecord?.dailyReportRecordId || data?.dailyReportRecordId || dailyReportRecordId
}
}
}
return {
code: code ?? -1,
message,
data
}
}
/**
* 首屏渲染后后台刷新 brand/scene/schema 进程内缓存(不更新当前页 UI)
* @param {Object} [options={}]
* @param {Object} [options.userContext] 用户上下文(merchantId、staffUuid 等)
* @param {string} [options.baseSceneCode] 门店场景编码
* @param {number|string} [options.reportTemplateId] 模板 ID
* @returns {Promise<void>}
*/
async function revalidateCachedMetadata({
userContext = {},
baseSceneCode,
reportTemplateId
} = {}) {
if (
isStaffMockMode('brand') &&
isStaffMockMode('scene') &&
isStaffMockMode('schema')
) {
return
}
const { merchantId, shopMerchantId, staffUuid, phone, sceneType } = userContext
if (!merchantId) {
return
}
const refreshOptions = { skipCacheRead: true }
await Promise.allSettled([
fetchBrandAdapter({ merchantId }, refreshOptions),
fetchSceneAdapter(
{ merchantId, shopMerchantId, staffUuid, phone, sceneType },
refreshOptions
),
fetchSchemaRootAdapter(
{ reportTemplateId, baseSceneCode, merchantId },
refreshOptions
)
])
}
module.exports = {
fetchMerchantBrandIds,
fetchMerchantScene,
fetchDailyReportCarBrandList,
fetchPageContext,
fetchReportDetail,
fetchSchema,
fetchWeeklyList,
submitForm,
buildPageContextFromSources,
normalizeUserInfo,
revalidateCachedMetadata
}