Commit ba33dc25 by 张立顺

feat 动态表单功能开发

1 parent 72a2dd35
Showing 162 changed files with 4173 additions and 171 deletions
No preview for this file type
...@@ -279,7 +279,9 @@ ...@@ -279,7 +279,9 @@
"pages": [ "pages": [
"pages/negotiationDetail/negotiationDetail", "pages/negotiationDetail/negotiationDetail",
"pages/storeDailyReport/storeDailyReport", "pages/storeDailyReport/storeDailyReport",
"pages/staffDailyReport/staffDailyReport" "pages/staffDailyReport/staffDailyReport",
"pages/carBrandPick/carBrandPick",
"pages/carBrandSeries/carBrandSeries"
] ]
} }
], ],
......
# DEVLOG — packageDynamicForm # DEVLOG — packageDynamicForm
## 2026-05-26 — 配置中心 Schema + 精品首页入口
- **Schema**:`fetchSchemaRootAdapter` 在 `apiSwitch.schema = 'real'` 时改为 `fetchConfigCenterTemplate`(`staff-daily-template` / `store-daily-template` / `negotiation-details-template`),不再调用 `dynamicDailyReportSchema`。
- **菜单**:精品首页(`sceneType === 1`)经 `appendDynamicFormTabIndexMenus` 写入 `menu` 与 `newMenu`;「驻店日报-新」与旧驻店日报权限对齐。权益首页仅 `sceneType === 0` 注入。
- **单测**:`tests/configCenterTemplate.test.mjs`、`tests/dynamicFormMenus.test.mjs`、adapter 用例已覆盖配置中心 URL 与缓存。
## [2026-05-27] staffDailyReport UI 对齐 Figma 225-8129 ## [2026-05-27] staffDailyReport UI 对齐 Figma 225-8129
**需求摘要**:日历以下改为 Figma 纵向排版,去掉 TabBar / upgradeStaffDaily 旧样式。 **需求摘要**:日历以下改为 Figma 纵向排版,去掉 TabBar / upgradeStaffDaily 旧样式。
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
| 页面 | navigateToUrl | 说明 | | 页面 | navigateToUrl | 说明 |
|------|----------|------| |------|----------|------|
| 洽谈明细 | `/packageDynamicForm/pages/negotiationDetail/negotiationDetail` | 占位页,后续接 schema | | 洽谈明细 | `/packageDynamicForm/pages/negotiationDetail/negotiationDetail` | F3-1~F3-4 schema + form-engine + inline group-repeater |
| 门店日报 | `/packageDynamicForm/pages/storeDailyReport/storeDailyReport` | 对应 Figma node 359:3122 | | 门店日报 | `/packageDynamicForm/pages/storeDailyReport/storeDailyReport` | 对应 Figma node 359:3122 |
| 驻店日报-新 | `/packageDynamicForm/pages/staffDailyReport/staffDailyReport` | Schema v2 员工日报(旧「驻店日报」入口保留) | | 驻店日报-新 | `/packageDynamicForm/pages/staffDailyReport/staffDailyReport` | Schema v2 员工日报(旧「驻店日报」入口保留) |
...@@ -14,6 +14,8 @@ ...@@ -14,6 +14,8 @@
- [动态表单 Schema 设计](../../动态表单Schema设计.md) - [动态表单 Schema 设计](../../动态表单Schema设计.md)
- [动态表单 API 接口契约](../../动态表单API接口契约.md) - [动态表单 API 接口契约](../../动态表单API接口契约.md)
- [multipleSelect 字段选项接口](./field-options-api.md)
- [group 子表单多行增删](./group-repeater.md)
- [Figma 门店日报](https://www.figma.com/design/sobhs03NFz61DbuixLVCZ2/202605-%E6%97%A5%E6%8A%A5?node-id=359-3122&m=dev) - [Figma 门店日报](https://www.figma.com/design/sobhs03NFz61DbuixLVCZ2/202605-%E6%97%A5%E6%8A%A5?node-id=359-3122&m=dev)
## 代码入口 ## 代码入口
......
# 四级车型选择(carBrandSelect)
## 流程
1. `form-field-carBrand` 点击 → 洽谈页 `openCarBrandForField`
2. [`carBrandPickerBridge`](../../../packageDynamicForm/services/carBrandPickerBridge.js) → [`carBrandPick`](../../../packageDynamicForm/pages/carBrandPick/carBrandPick)
3. 选品牌 → [`carBrandSeries`](../../../packageDynamicForm/pages/carBrandSeries/carBrandSeries)(子品牌 / 车系 / 款型)
4. `completeCarPick` 回写 `engine.setGroupFieldValue`
## API(对齐 App 动态表单 `CarModelList`)
| 步骤 | 接口 | 说明 |
|------|------|------|
| **L1+L2 品牌/子品牌** | `merchants.api.open.merchant.info`(`brandFlag: true`) | `getMerchantCarBrandList([merchantId])` → `data[0].carBrandList`,**非**全国 `getOnlyCarBrandList` |
| L3 车系 | `scrm.api.carlife.common.getCarSeriesList` | 点击子品牌后按需加载 |
| L4 款型 | `scrm.api.carlife.common.getCarTypeList` | 点击车系后底部弹层 |
洽谈页经桥接传入 `merchantId`(对应 App `shopMerchantId`)。`brandIds`(`staffDailyReportMerchantCarBand`)仅用于 schema 显隐,不用于选择列表。
Mock:`apiSwitch.brand === 'mock'` 时使用 [`car-brand-merchant-mock.js`](../../../packageDynamicForm/fixtures/car-brand-merchant-mock.js) 主营树。
## 行内值结构
```js
{
vehicleBrandId, vehicleBrandName,
vehicleSubBrandId, vehicleSubBrandName,
vehicleSeriesId, vehicleSeriesName,
vehicleShapeId, vehicleShapeName,
displayText // 岚图/岚图汽车/FREE/2024款
}
```
展示顺序与 [`GLForm`](../../../packageEquity/components/GLForm/GLForm.wxml) 一致。
## 提交(待 App 联调)
[`car-brand-value.js`](../../../packageDynamicForm/form-engine/car-brand-value.js) 中 `CAR_BRAND_SUBMIT_KEY_MAP` 预留 schema childKey → 后端 fieldKey。未配置时 `fieldDataList` 对子字段提交 `JSON.stringify` 整对象,`jsonContent` 行内仍为对象。
## 校验
- `carBrandSelect` 必填:`vehicleShapeId` 必须有值(四级选满)
## 手工用例
1. 洽谈明细 F3 新增行 → 点「车型配置」→ 走完四级选择 → 展示四级名称拼接。
2. 未选款型提交 → 提示「车型配置不能为空」。
3. 返回洽谈页后切换「是否成交」,已填车型与其它字段仍在。
## 与旧能力区别
| 能力 | 级数 |
|------|------|
| `components/CarBrands` 弹窗 | 3 级(工单) |
| `packageDynamicForm` 本流程 | **4 级** |
# multipleSelect 字段选项接口
## 行为约定
| 字段类型 | `optionsKey` | 选项来源 |
|----------|--------------|----------|
| `select` | 可有 | schema 归一化时从 `SCHEMA_OPTIONS_MAP` 预填;组件**不**调接口 |
| `multipleSelect` | 有 | 组件打开弹框前调用 `fetchFieldOptions` |
| `multipleSelect` | 无 | 使用 schema 内静态 `options` |
## 请求
- 服务:`packageDynamicForm/api/fieldOptionsService.js`
- Mock 开关:`apiSwitch.fieldOptions`(`store` / `staff` 各一套)
- Body 字段:`optionsKey`, `merchantId`, `staffUuid`, `reportDate`, `reportType`
真实接口占位:`dj.api.smartcarlife.dailyReport.field.options`
## 响应
```json
{ "code": 0, "data": [{ "label": "张三", "value": "staff-001" }] }
```
## optionsKey 注册(mock)
| optionsKey | 说明 |
|------------|------|
| `storeStaffList` | 门店驻店人员 |
| `4sStaffList` | 4S 店人员 |
Mock 数据:`packageDynamicForm/fixtures/mock-field-options.js`
## 页面透传
`dynamic-form` 接收 `requestContext`,仅绑定到 `form-field-multipleSelect`。门店/员工日报页在 `applyEngineView` 时写入 `merchantId`、`staffUuid`、`reportDate`、`reportType`。
# subform 子表单(多行增删)
## 适用节点
- `type: 'subform'` 且含 `children[0]` 行模板(字段数组)
- 洽谈明细 `F3-1`~`F3-4`、门店日报 `F2-9`~`F2-28` 等
- 兼容:旧模版若仍为 `type: 'group'` 且 `children` 为 `[[...]]`,`schema-normalizer` 会提升为 `subform`
## 静态 group(非本组件)
- `type: 'group'` + 扁平 `children: [{...}, ...]`:驻店日报品牌区块(`F1-5`~`F1-11`)
- 由 [`dynamic-form`](../../../packageDynamicForm/components/dynamic-form/) 的 `sectionGroups` 渲染(白卡片 + 标题,无增删翻页)
- 值形态:扁平 `values['F1-5-1']`,非 `values['F1-5']` 数组
## UI(Figma 229-8646)
- **外层白卡片**(`border-radius: 32rpx`):整块 group 区块
- **标题行**:左标题 32rpx/600 + 右「+」图标胶囊按钮(浅蓝底 `#2c66f71a`)
- **翻页**:`当前行/总行`,左右箭头
- **浅蓝内容区**(`rgba(148,194,255,0.2)`,`border-radius: 24rpx`):「第 N 行」+ 删除(浅蓝圆底)
- **字段**:每个子字段独立 **白色圆角块**,块间距 16rpx(非整表连续分割线)
- 组件样式:`form-group-repeater.wxss` + `styleIsolation: apply-shared` 覆盖子字段行样式
组件:[`form-group-repeater`](../../../packageDynamicForm/components/form-group-repeater/)
## 与 gl_tape NegotiationDetail 数据对照
参考:`gl_tape/pages/common/dailyNewspaper/NegotiationDetail/edit.vue` + `EditForm.vue`
| gl_tape | 本仓库 |
|---------|--------|
| `list[i].children` = 多行 `FormField[]` | 引擎 `groupRowsCache[groupKey]` |
| `push(template.children[0])` | `cloneRowTemplate(group)` |
| `confirm` 深拷贝整行 | `setGroupFieldValue` / `replaceGroupRow` 同步 cache |
| `children.splice` 删行 | `removeGroupRow` |
| `childrenShowRules` 行内显隐 | `group-visibility.js` → `group-show-rule-eval.js`(小程序 **fallback**;Node 可选用 eval5) |
| UI 当前行字段 | 页面 `applyEngineView` → [`merge-form-group-view.js`](../../../packageDynamicForm/utils/merge-form-group-view.js) 生成 `groupRowVisibleMap` / `groupRowTotalMap`(深拷贝 + 行内显隐 + `_wxRowKey`) |
| `childrenRules` | schema-normalizer 合并到子字段 `rules` |
## 双写数据形态
**运行时 cache(对齐 gl_tape,供 UI):**
```js
groupRowsCache['F2-9'] = [
[ { key: 'F2-9-1', type: 'select', label: '...', value: '4s-001' }, ... ],
[ { key: 'F2-9-1', value: '4s-002' }, ... ]
]
```
**提交 values(扁平 map 数组):**
```js
values['F2-9'] = [
{ 'F2-9-1': '4s-001', 'F2-9-2': 1 },
{ 'F2-9-1': '4s-002', 'F2-9-2': 2 }
]
```
- 旧版扁平子 key(`F2-9-1` 等)在 `init` 时由 `migrateFlatGroupValues` 合并
- 校验错误 key:`F2-9__0__F2-9-1`
## 引擎 API
| 方法 | 说明 |
|------|------|
| `addGroupRow(group)` | `cloneRowTemplate` 新增行 |
| `removeGroupRow(groupKey, rowIndex)` | 删除行 |
| `setGroupFieldValue(...)` | 更新 cache 中字段 `value` 并同步 values |
| `replaceGroupRow(...)` | 整行 FormField[] 回写(对齐 confirm) |
| `getGroupRowsCache()` | 读取 gl_tape 形态行数据 |
## childrenShowRules 求值(小程序)
- Schema:`{ keys: ['F3-1-10', ...], result: "val1 == '是' && val2 != null" }`,`valN` 与 `keys` 下标一一对应。
- 小程序环境 **仅走内置 fallback**(覆盖洽谈 F3 常见句式),避免 eval5 未构建导致 `t.apply is not a function` 等 setData 异常。
- Node 单测/非小程序场景仍可选用 [**eval5**](https://www.npmjs.com/package/eval5)。
- 求值失败时 **隐藏** 该子字段(`return false`)。
## 多行输入隔离(避免多框联动)
- 页面 [`applyEngineView`](../../../packageDynamicForm/pages/negotiationDetail/negotiationDetail.js) 调用 [`merge-form-group-view.js`](../../../packageDynamicForm/utils/merge-form-group-view.js):首屏/结构变更时全量 `mergeGroupRowMapsIntoData`;**输入、新增、删行、翻页** 时仅用 [`patchGroupRowMapForKey`](../../../packageDynamicForm/utils/merge-form-group-view.js) 更新当前 `groupKey` 的 `groupRowVisibleMap`,避免刷新其它 F3 区块导致输入框错绑。
- [`dynamic-form`](../../../packageDynamicForm/components/dynamic-form/) / [`form-group-repeater`](../../../packageDynamicForm/components/form-group-repeater/) **不**用 observers 监听 cache,只展示页面传入的 `groupRowVisibleMap`。
- `setGroupFieldValue` 仅更新 cache 当前行,**不**每次全量 `rebuildGroupRowsCache`。
- repeater 子字段使用全局唯一 `_wxRowKey`(`groupKey_rowIndex_childKey`),`block wx:key` + 组件 `id`,`change` 事件透传 `rowIndex`。
### 组件 observer 约定(避免 `t.apply is not a function`)
- **properties** 上的 `observer: 'methodName'` 可使用字符串,指向 `methods` 中的方法(如 [`form-field-phone`](../../../packageDynamicForm/components/form-field-phone/form-field-phone.js) 的 `value.observer`)。
- **Component.observers** 数据监听器**必须**写 `function () { ... }`,**禁止**写字符串方法名(曾导致 `form-field-phone` 在「新增」挂载时报错)。
- group 行 UI 不依赖 repeater / dynamic-form 的 observers;字段变更后由页面 `applyEngineView` 重算 `groupRowVisibleMap`(含 `childrenShowRules`)。
## 校验
- **0 行**(未点「新增」或 `values[groupKey]` 为 `[]`):不校验该 group,可提交。
- **≥1 行**:对每行可见子字段执行 `required` 与 `rules`(错误 key:`groupKey__rowIndex__childKey`)。
- 显式 `rules.minRows` 仅在已有行且行数不足时提示;`group.required` 不再默认「至少 1 行」。
## 提交
- `jsonContent`:group 节点 `value` 为 **FormField[][]**(gl_tape 形态)
- `fieldDataList`:展开为 `groupKey` + `rowIndex` + `fieldKey` + `fieldValue`
- `parseDetailValues` / `extractValuesFromFormList` 支持两种 jsonContent 格式互转
## 页面
- `dynamic-form` 透传 `group-rows-cache`、`group-active-index`
- `storeDailyReport` / `staffDailyReport` 处理 group 增删改事件
## 四级车型选择(carBrandSelect)
- 组件:[`form-field-carBrand`](../../../packageDynamicForm/components/form-field-carBrand/)
- 页面:[`carBrandPick`](../../../packageDynamicForm/pages/carBrandPick/) + [`carBrandSeries`](../../../packageDynamicForm/pages/carBrandSeries/)
- 桥接:[`carBrandPickerBridge`](../../../packageDynamicForm/services/carBrandPickerBridge.js)
- 详见 [car-brand-select.md](./car-brand-select.md)
## 车架号 OCR(洽谈等)
schema 子字段 `type: input` + `prefixComponent: 'scan'` 时,`form-field-input` 显示「识别」按钮(非 `wx.scanCode`)。
| 环节 | 实现 |
|------|------|
| 跳转 | [`vinOcrBridge.openVinOcr`](../../../packageDynamicForm/services/vinOcrBridge.js) → `wx.$router.go('tabWorkOrder.ocr?type=standNo')` |
| 识别页 | [`tabWorkOrder/pages/ocr/ocr`](../../../tabWorkOrder/pages/ocr/ocr.js)(不修改) |
| 回写 | 上一页 `reWrite` → `applyVinOcrResult` → `engine.setGroupFieldValue`(与车型选择同路径);`wx.nextTick` + `onShow` 延迟刷视图 |
| 上下文 | [`resolveVinFieldContext`](../../../packageDynamicForm/services/vin-ocr-context.js) 推断 `groupKey`(如 `F3-1-7`→`F3-1`)、补全 `rowIndex`(含第 0 行);模块 `pending` + page `_vinOcrCtx` |
| 校验 | `validateVin` / `dj.pad.api.vin.validate` **仅校验与 toast,不写表单**;回显必须在 OCR 回写阶段完成 |
洽谈页:[`negotiationDetail.js`](../../../packageDynamicForm/pages/negotiationDetail/negotiationDetail.js) 提供 `openVinOcrForField` / `reWrite`。
### 手工用例
1. 洽谈明细 → 某 group 点「新增」→ 车架号点「识别」→ 进入 OCR 页拍照/选图识别成功。
2. 返回后 VIN 填入当前行,其它行、周历日期、未提交草稿仍在。
3. 从非洽谈页进入 OCR 时不应误写 pending(无 `openVinOcrForField` 时不应点识别)。
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
| ID | 类型 | 前置 | 步骤 | 预期 | 状态 | | ID | 类型 | 前置 | 步骤 | 预期 | 状态 |
|----|------|------|------|------|------| |----|------|------|------|------|------|
| IT-ROUTE-001 | E2E | 精品首页 | 点击「门店日报」 | 进入 storeDailyReport,标题「门店日报」 | 待测 | | IT-ROUTE-001 | E2E | 精品首页 | 点击「门店日报」 | 进入 storeDailyReport,URL 含 sceneType,动态表单渲染 | 待测 |
| IT-ROUTE-002 | E2E | 精品首页 | 点击「驻店日报-新」 | 进入 staffDailyReport,URL 含 `sceneType`,标题「驻店日报-新」 | 待测 | | IT-ROUTE-002 | E2E | 精品首页 | 点击「驻店日报-新」 | 进入 staffDailyReport,URL 含 `sceneType`,标题「驻店日报-新」 | 待测 |
| IT-ROUTE-003 | E2E | 权益首页 | 点击「洽谈明细」 | 进入 negotiationDetail | 待测 | | IT-ROUTE-003 | E2E | 权益首页 | 点击「洽谈明细」 | 进入 negotiationDetail | 待测 |
| IT-MENU-001 | E2E | 精品员工 | 打开首页 | menu 可见 3 个新入口图标 | 待测 | | IT-MENU-001 | E2E | 精品员工 | 打开首页 | menu 可见 3 个新入口图标 | 待测 |
...@@ -13,6 +13,9 @@ ...@@ -13,6 +13,9 @@
| IT-PAGE-002 | E2E | staffDailyReport | 选中**当天**(含已提交回显) | 可编辑 +「提交」,样式与新增一致 | 待测 | | IT-PAGE-002 | E2E | staffDailyReport | 选中**当天**(含已提交回显) | 可编辑 +「提交」,样式与新增一致 | 待测 |
| IT-PAGE-005 | E2E | staffDailyReport | 选中**非当天** | 只读变灰 + 无底部按钮 | 待测 | | IT-PAGE-005 | E2E | staffDailyReport | 选中**非当天** | 只读变灰 + 无底部按钮 | 待测 |
| IT-PAGE-007 | E2E | staffDailyReport | 精品入口(sceneType=1)vs 权益入口(sceneType=0) | 同一门店下字段显隐与 sceneType/baseSceneCode 一致 | 待测 | | IT-PAGE-007 | E2E | staffDailyReport | 精品入口(sceneType=1)vs 权益入口(sceneType=0) | 同一门店下字段显隐与 sceneType/baseSceneCode 一致 | 待测 |
| IT-PAGE-008 | E2E | staffDailyReport | 模拟加载失败 | 展示空态 +「重新加载」,点击后重新请求 | 待测 |
| IT-API-SWITCH-001 | E2E | apiSwitch.detail=real | 进入/刷新页面 | 网络面板可见 `dynamic.detail` | 待测 |
| IT-API-SWITCH-002 | E2E | apiSwitch.schema=real | 进入/刷新页面 | 网络面板可见 `dynamic.schema` | 待测 |
## 单元测试(Node) ## 单元测试(Node)
...@@ -21,6 +24,11 @@ ...@@ -21,6 +24,11 @@
| IT-UNIT-001 | dynamicFormMenus | `npm test` | 3 项菜单、去重、navigateToUrl 正确 | | IT-UNIT-001 | dynamicFormMenus | `npm test` | 3 项菜单、去重、navigateToUrl 正确 |
| IT-ENG-001 | form-engine visibility | `npm test` | 出勤/brandId/filterBrandId 显隐 | | IT-ENG-001 | form-engine visibility | `npm test` | 出勤/brandId/filterBrandId 显隐 |
| IT-ENG-002 | form-engine validator | `npm test` | 可见必填校验 | | IT-ENG-002 | form-engine validator | `npm test` | 可见必填校验 |
| IT-API-SWITCH-001 ~ 002 | staffDailyReportAdapters | `npm test` | apiSwitch mock/real 与 schema/scene 缓存 |
| IT-LOADER-001 ~ 002 | staffDailyFormLoader | `npm test` | 并行加载与 PageContext 顺序 |
| IT-STORE-LOADER-001 ~ 002 | storeDailyFormLoader | `npm test` | 门店日报 loader 顺序 |
| IT-STORE-API-SWITCH-001 ~ 002 | storeDailyReportAdapters | `npm test` | 门店 mock/real 与 schema 缓存 |
| IT-STORE-ENG-001 ~ 003 | form-engine store schema | `npm test` | 无出勤 gate / divider / optionsKey |
| IT-API-002 ~ 005 | submit-adapter | `npm test` | fieldDataList / save payload | | IT-API-002 ~ 005 | submit-adapter | `npm test` | fieldDataList / save payload |
| IT-DATE-001 ~ 002 | time-utils | `npm test` | 当天/历史日期判断 | | IT-DATE-001 ~ 002 | time-utils | `npm test` | 当天/历史日期判断 |
......
...@@ -2,16 +2,27 @@ ...@@ -2,16 +2,27 @@
| 页面 | 状态 | 触发 | UI 预期 | TEST-ID | | 页面 | 状态 | 触发 | UI 预期 | TEST-ID |
|------|------|------|---------|---------| |------|------|------|---------|---------|
| negotiationDetail | 占位 | 任意进入 | navigation-bar +「页面开发中」 | IT-PAGE-001 | | negotiationDetail | 可编辑/只读 | 周历选日 + dynamic-form(F3-1~F3-4 group) | 与 storeDailyReport 同引擎;mock 见 `NEGOTIATION_DAILY_API_SWITCH` | IT-PAGE-001 |
| storeDailyReport | 占位 | 任意进入 | navigation-bar +「页面开发中」 | IT-PAGE-001 | | storeDailyReport | 当天填写/回显 | 选中当天 | 表单可编辑、divider/group 动态渲染、底部「提交」 | IT-STORE-PAGE-002 |
| storeDailyReport | 非当天只读 | 选中非当天日期 | 只读变灰 + 无底部按钮 | IT-STORE-PAGE-005 |
| storeDailyReport | 加载失败 | 接口失败 | 空态 +「重新加载」 | IT-STORE-PAGE-008 |
| staffDailyReport | 当天填写/回显 | 选中当天(含已提交) | 表单可编辑、样式与新增一致,有值回显,底部「提交」 | IT-PAGE-002 | | staffDailyReport | 当天填写/回显 | 选中当天(含已提交) | 表单可编辑、样式与新增一致,有值回显,底部「提交」 | IT-PAGE-002 |
| staffDailyReport | 非当天只读 | 选中非当天日期(含历史日期) | 表单 disabled 灰色样式,隐藏底部按钮,仅可查看 | IT-PAGE-005 | | staffDailyReport | 非当天只读 | 选中非当天日期(含历史日期) | 表单 disabled 灰色样式,隐藏底部按钮,仅可查看 | IT-PAGE-005 |
| staffDailyReport | 调休 | `F1-1` 选「调休」 | 仅出勤字段可见,其余 destroy | IT-PAGE-006 | | staffDailyReport | 调休 | `F1-1` 选「调休」 | 仅出勤字段可见,其余 destroy | IT-PAGE-006 |
| staffDailyReport | 加载失败 | 接口失败或网络异常 | 空态文案 +「重新加载」,隐藏表单与提交 | IT-PAGE-008 |
## 门店日报 UI(Figma 229-8646 / 814-7748)
- 编辑态:当天可填写,divider 展示「延保 / 权益 / 轻改」区块标题(divider 显隐用 `ybCode`/`qyCode`/`qgCode`;F2-94「延保/权益」需门店 `sceneList` 同时含延保码与权益码)
- 详情态:非当天只读变灰,隐藏提交按钮
- group 子表单(Figma 229-8646):外层白卡片 + 标题/「+ 新增」胶囊按钮 + `N/M` 翻页 + 浅蓝内容区(`rgba(148,194,255,0.2)`)+ 每字段独立白圆角块(16rpx 间距)+ 删除图标;见 [group-repeater.md](./group-repeater.md)
- mock 切换见 [`apiSwitch.js`](../../packageDynamicForm/config/apiSwitch.js) 中 `STORE_DAILY_API_SWITCH`
## UI 布局(Figma 225-8129) ## UI 布局(Figma 225-8129)
- 日历以下:**纵向 scroll**,白卡片分区 - 日历以下:**纵向 scroll**,白卡片分区
- 固定字段(出勤/延保退单/备注)在第一张卡片 - 固定字段按 divider 拆成多张白卡片;divider 独立在灰底上(两侧虚线)
- `F2-1` 今日驻店人员:仅门店经营品牌含岚图(`brandId` 3067)时展示,选项走 `storeStaffList`
- 可见品牌 group(问界/享界…)**依次全量展示**,无 Tab 切换 - 可见品牌 group(问界/享界…)**依次全量展示**,无 Tab 切换
- 字段行:96rpx「信息录入」行(label 左 + value 右 + `#EFF0F2` 分割线) - 字段行:96rpx「信息录入」行(label 左 + value 右 + `#EFF0F2` 分割线)
- 备注:全宽浅底 textarea + 字数统计 - 备注:全宽浅底 textarea + 字数统计
...@@ -19,19 +30,39 @@ ...@@ -19,19 +30,39 @@
## Mock 数据说明 ## Mock 数据说明
- 本周一默认有一条 mock 回显(见 `packageDynamicForm/api/staffDailyReport.js`) 联调切换统一在 [`packageDynamicForm/config/apiSwitch.js`](../../packageDynamicForm/config/apiSwitch.js):
- 切换周日历日期可验证「空 / 已填 / 编辑」三态
- 真接口接入时替换 mock 层,页面与 form-engine 不变 | 联调阶段 | detail | schema | saveEcho |
|----------|--------|--------|----------|
| 本地开发 | mock | mock | mock |
| 详情联调 | **real** | mock | mock |
| 模板联调 | real | **real** | off |
| 上线 | real | real | off |
- `detail/schema = mock` 时分别走 `mockDynamicDetail.js` 与本地 schema fixture
- `brand = mock` 时返回五界经营品牌 ID 列表(3454 / 3503 / 3458 / 3574 / 3502)
- `scene = mock` 时返回 `MOCK_MERCHANT_SCENE_LIST`(轻改/权益/延保代表码)
- `save` 始终走 `dynamic.save`;`saveEcho = mock` 时提交成功后写入 mock 存储便于当天回显
- 切换周日历日期可验证「空 / 已填 / 只读」三态
## 工程优化(PR-1 / PR-B)
- `loadSeq` / `refreshSeq` 防止快速切日期与提交后刷新竞态
- `loading` + skeleton;失败时 `loadError` 空态 +「重新加载」
- `engine.init(schema, pageContext)` 保证初始化顺序
- `fetchPageContext` 不再重复请求场景接口;有记录时优先 `detail.baseSceneCode`
- `loadStaffDailyForm` 服务层封装并行加载
- 同 `reportDate` 复用 engine 实例
- scene / schema(real 模式)会话缓存;`onFieldChange` 按需 setData
## PageContext 三维过滤 ## PageContext 显隐过滤
| 维度 | 来源 | 说明 | | 维度 | 来源 | 说明 |
|------|------|------| |------|------|------|
| `sceneType` | 页面跳转 query `?sceneType=` | 精品首页通常 `1`,权益首页通常 `0`;直进页面 fallback `userInfo.sceneType` | | `sceneList` | `findAllSceneByMerchantId` | 门店全部 `baseSceneCode`;字段 `baseSceneCode[]` / divider 码表与之求交后决定是否显示 |
| `baseSceneCode` | `dj.api.scenemerchantref.findAllSceneByMerchantId` | 入参 `{ merchantId }`,按 `sceneType` 匹配列表项 |
| `brandIds` | `staffDailyReportMerchantCarBand` | 门店经营品牌 ID 列表,与 schema 字段 `brandId[]` / `filterBrandId[]` 匹配 | | `brandIds` | `staffDailyReportMerchantCarBand` | 门店经营品牌 ID 列表,与 schema 字段 `brandId[]` / `filterBrandId[]` 匹配 |
`brandIdMap`(mock-meta)为品牌字典;运行时显隐使用 `ctx.brandIds`。 `brandIdMap`(mock-meta)为品牌字典;运行时显隐使用 `ctx.brandIds` 与 `ctx.sceneList`,不再区分精品/权益入口 `sceneType`。
## 集成测试 ## 集成测试
...@@ -40,3 +71,4 @@ ...@@ -40,3 +71,4 @@
| IT-INT-001 | 动态渲染 | 进入页面 → 可见字段与 schema + PageContext 一致 | | IT-INT-001 | 动态渲染 | 进入页面 → 可见字段与 schema + PageContext 一致 |
| IT-INT-002 | 提交 | 填写必填项 → 提交 → 日历显示已填 | | IT-INT-002 | 提交 | 填写必填项 → 提交 → 日历显示已填 |
| IT-INT-003 | 当天再次提交 | 当天已提交 → 修改字段 → 提交 | 回显更新,日历仍显示已填 | | IT-INT-003 | 当天再次提交 | 当天已提交 → 修改字段 → 提交 | 回显更新,日历仍显示已填 |
| IT-STORE-GROUP-001 | group 增删翻页 | 门店日报 → 问界 group → 新增 2 行 → 翻页填写 → 删除 1 行 → 提交 | 回显 `F2-9` 数组行数与字段值一致 |
...@@ -12,10 +12,12 @@ ...@@ -12,10 +12,12 @@
## 首页入口 ## 首页入口
| TEST-ID | 场景 | 入口位置 | 菜单文案 | navigateToUrl | | TEST-ID | 场景 | 条件 | 入口位置 | 菜单文案 | navigateToUrl |
|---------|------|---------|---------|---------------| |---------|------|------|---------|---------|---------------|
| IT-MENU-001 | 精品 | tabIndex 首页 menu 网格 | 洽谈明细 / 门店日报 / 驻店日报-新 | 见上 | | IT-MENU-001 | 精品 | `userInfo.sceneType === 1` | tabIndex 首页 `menu` + `newMenu` 双网格 | 洽谈明细 / 门店日报 / 驻店日报-新(见权限) | 见上 |
| IT-MENU-002 | 权益 | packageEquity 首页 menu_box | 同上 | 见上 | | IT-MENU-002 | 权益 | `userInfo.sceneType === 0` | packageEquity 首页 menu_box | 同上(三入口均展示) | 见上 |
精品场景由 `appendDynamicFormTabIndexMenus` 同时写入 `menu` 与 `newMenu`(`newMenu` 项带 `sortVal`)。
## 图标(占位) ## 图标(占位)
...@@ -27,4 +29,22 @@ ...@@ -27,4 +29,22 @@
## 权限 ## 权限
当前三个入口**无额外权限过滤**,与计划一致「两场景首页均展示」。旧「驻店日报」(`tabWorkOrder.staffDaily` / `upgradeStaffDaily`)仍保留,新入口文案为「驻店日报-新」。 | 菜单 | 精品 tabIndex | 权益 packageEquity |
|------|---------------|-------------------|
| 洽谈明细 | 精品全员 | 全员 |
| 门店日报 | 精品全员 | 全员 |
| 驻店日报-新 | `isStaff` 或 `canSelectMultiStoreForStaffDaily`(与旧「驻店日报」一致) | 全员 |
旧「驻店日报」(`tabWorkOrder.staffDaily` / `upgradeStaffDaily`)仍保留,新入口文案为「驻店日报-新」。
## Schema 模版(配置中心)
`apiSwitch.schema = 'real'` 时,三份表单 Schema 从配置中心拉取(`GET` 后缀 `moduleUrl` + `env`):
| 表单 | moduleUrl |
|------|-----------|
| 驻店日报 | `staff-daily-template` |
| 门店日报 | `store-daily-template` |
| 洽谈明细 | `negotiation-details-template` |
实现:`packageDynamicForm/config/configCenter.js` → 各 `*DailyReportAdapters.fetchSchemaRootAdapter`。`schema = 'mock'` 仍使用 `fixtures/schema-*-full.js`。
...@@ -255,8 +255,9 @@ Accept: application/json ...@@ -255,8 +255,9 @@ Accept: application/json
| 规则 | 说明 | | 规则 | 说明 |
| --- | --- | | --- | --- |
| key 来源 | 必须为 schema 中叶子字段的 `key`(如 `F1-5-1`) | | key 来源 | 顶层固定字段为叶子 `key`(如 `F1-5-1`);**group 多行**为 `values[groupKey]` 数组 |
| group 不提交 | `F1-5` 等 group 节点不出现在 values 中 | | group 多行 | `values['F2-9'] = [{ 'F2-9-1': '4s-001', 'F2-9-2': 1 }, ...]`,`children[0]` 为行模板 |
| fieldDataList | group 子字段项含 `groupKey`、`rowIndex`、`fieldKey`、`fieldValue` |
| 隐藏字段 | 当前不可见字段不应出现(destroy 语义) | | 隐藏字段 | 当前不可见字段不应出现(destroy 语义) |
| 数值类型 | number 字段用 number,不用字符串 | | 数值类型 | number 字段用 number,不用字符串 |
| 出勤 | `F1-1`: `"1"`=在岗, `"2"`=调休 | | 出勤 | `F1-1`: `"1"`=在岗, `"2"`=调休 |
......
...@@ -113,9 +113,13 @@ interface FormSchemaRoot { ...@@ -113,9 +113,13 @@ interface FormSchemaRoot {
### 3.4 group 与 children ### 3.4 group 与 children
- `type: 'group'` 的节点**不参与提交**,仅作为视觉分组。 - `type: 'group'` 的节点在 schema 中为分组容器;提交时以 **`values[groupKey]` 对象数组** 表示多行子表(见 [group-repeater.md](./features/packageDynamicForm/group-repeater.md))。
- `children` 为二维数组 `FormField[][]`,当前约定**外层仅一层**,取 `children[0]` 作为子字段列表。 - `children` 为二维数组 `FormField[][]`,当前约定**外层仅一层**,取 `children[0]` 作为**单行模板**(字段定义),非多行数据本身。
- 每一行数据为 `{ [childKey]: value }`,如 `values['F2-9'] = [{ 'F2-9-1': '4s-001', 'F2-9-2': 1 }, ...]`。
- 子字段继承 group 的品牌上下文(group 可见时才渲染 children);子字段仍各自执行显隐算法(通常子字段 `brandId` 为 `[]`)。 - 子字段继承 group 的品牌上下文(group 可见时才渲染 children);子字段仍各自执行显隐算法(通常子字段 `brandId` 为 `[]`)。
- 可选 `rules.minRows` / `rules.maxRows` 限制行数;**0 行可不填子表**(不校验);有行时子字段 `required` 生效;`group.required` 不强制行数,行数下限仅由显式 `rules.minRows` 控制(且 0 行不触发)。
- 可选 `childrenShowRules`:行内子字段联动显隐(与 gl_tape `EditForm.itemShow` 相同 eval 约定),见 [group-repeater.md](./features/packageDynamicForm/group-repeater.md)。
- 运行时 UI 使用 `groupRowsCache[groupKey]`(`FormField[][]`);提交 `values[groupKey]` 为 `{ childKey: value }[]`。
--- ---
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
"@vant/area-data": "^1.5.1", "@vant/area-data": "^1.5.1",
"@vant/weapp": "^1.10.24", "@vant/weapp": "^1.10.24",
"dayjs": "^1.11.11", "dayjs": "^1.11.11",
"eval5": "^1.4.8",
"glsk-applet-component": "^1.0.0", "glsk-applet-component": "^1.0.0",
"glsk-map-jssdk": "^0.1.1", "glsk-map-jssdk": "^0.1.1",
"glsx-applet-component": "^1.1.29", "glsx-applet-component": "^1.1.29",
...@@ -75,6 +76,14 @@ ...@@ -75,6 +76,14 @@
"node": ">=6.0.0" "node": ">=6.0.0"
} }
}, },
"node_modules/@babel/runtime": {
"version": "7.29.7",
"resolved": "https://registry.npmmirror.com/@babel/runtime/-/runtime-7.29.7.tgz",
"integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/types": { "node_modules/@babel/types": {
"version": "7.28.6", "version": "7.28.6",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.6.tgz", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.6.tgz",
...@@ -128,6 +137,19 @@ ...@@ -128,6 +137,19 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@types/acorn": {
"version": "4.0.6",
"resolved": "https://registry.npmmirror.com/@types/acorn/-/acorn-4.0.6.tgz",
"integrity": "sha512-veQTnWP+1D/xbxVrPC3zHnCZRjSrKfhbMUlEA43iMZLu7EsnTtkJklIuwrCPbOi8YkvDQAiW05VQQFvvz9oieQ==",
"dependencies": {
"@types/estree": "*"
}
},
"node_modules/@types/estree": {
"version": "0.0.41",
"resolved": "https://registry.npmmirror.com/@types/estree/-/estree-0.0.41.tgz",
"integrity": "sha512-rIAmXyJlqw4KEBO7+u9gxZZSQHaCNnIzYrnNmYVpgfJhxTqO0brCX0SYpqUTkVI5mwwUwzmtspLBGBKroMeynA=="
},
"node_modules/@vant/area-data": { "node_modules/@vant/area-data": {
"version": "1.5.2", "version": "1.5.2",
"resolved": "https://registry.npmjs.org/@vant/area-data/-/area-data-1.5.2.tgz", "resolved": "https://registry.npmjs.org/@vant/area-data/-/area-data-1.5.2.tgz",
...@@ -145,11 +167,33 @@ ...@@ -145,11 +167,33 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/acorn": {
"version": "7.4.1",
"resolved": "https://registry.npmmirror.com/acorn/-/acorn-7.4.1.tgz",
"integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==",
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/dayjs": { "node_modules/dayjs": {
"version": "1.11.19", "version": "1.11.19",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz", "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz",
"integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==" "integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw=="
}, },
"node_modules/eval5": {
"version": "1.4.8",
"resolved": "https://registry.npmmirror.com/eval5/-/eval5-1.4.8.tgz",
"integrity": "sha512-sdc04TAeklUHrITxBWksrDsDBWqAvYs9VCS2cpSHrSqzTdva4JkILV+x7kVlyoUqp/g7kMyGS+4RMYgfkGciAw==",
"dependencies": {
"@babel/runtime": "^7.8.4",
"@types/acorn": "^4.0.5",
"@types/estree": "0.0.41",
"acorn": "^7.1.0"
}
},
"node_modules/glsk-applet-component": { "node_modules/glsk-applet-component": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/glsk-applet-component/-/glsk-applet-component-1.0.0.tgz", "resolved": "https://registry.npmjs.org/glsk-applet-component/-/glsk-applet-component-1.0.0.tgz",
...@@ -194,7 +238,6 @@ ...@@ -194,7 +238,6 @@
"integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==", "integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"prettier": "bin/prettier.cjs" "prettier": "bin/prettier.cjs"
}, },
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
"@vant/area-data": "^1.5.1", "@vant/area-data": "^1.5.1",
"@vant/weapp": "^1.10.24", "@vant/weapp": "^1.10.24",
"dayjs": "^1.11.11", "dayjs": "^1.11.11",
"eval5": "^1.4.8",
"glsk-applet-component": "^1.0.0", "glsk-applet-component": "^1.0.0",
"glsk-map-jssdk": "^0.1.1", "glsk-map-jssdk": "^0.1.1",
"glsx-applet-component": "^1.1.29", "glsx-applet-component": "^1.1.29",
......
/**
* 四级车型接口(对齐 App 动态表单 CarModelList + scrm carlife)
*/
const requestModule = require('~/utils/request/request.js')
const api = requestModule.default || requestModule
const { resolveMerchantCarBrandTree } = require('../form-engine/car-brand-merchant-tree.js')
const { MOCK_MERCHANT_CAR_BRAND_TREE } = require('../fixtures/car-brand-merchant-mock.js')
const CARLIFE_ROUTER = '/rop-scrm-carlife/router'
const CARLIFE_DOMAIN = 'scrm'
const MERCHANTS_ROUTER = '/rop-merchants/router'
const MERCHANTS_DOMAIN = 'merchants'
function getMerchantCarBrandList(merchantIdList = []) {
return api.post(
'merchants.api.open.merchant.info',
{
merchantIdList,
merchantInfoSwitch: {
brandFlag: true
}
},
[],
MERCHANTS_ROUTER,
MERCHANTS_DOMAIN
)
}
/**
* 动态表单 carBrandSelect L1+L2:门店主营树(App getMerchantCarBrandList)
*/
function fetchMerchantCarBrandTree(merchantId, options = {}) {
if (options.useMock) {
return Promise.resolve(MOCK_MERCHANT_CAR_BRAND_TREE)
}
if (!merchantId) {
return Promise.resolve([])
}
return getMerchantCarBrandList([merchantId]).then(res => resolveMerchantCarBrandTree(res))
}
module.exports = {
getCarBrandList(data = {}) {
return api.post(
'scrm.api.carlife.common.getOnlyCarBrandList',
data,
[],
CARLIFE_ROUTER,
CARLIFE_DOMAIN
)
},
getMerchantCarBrandList,
fetchMerchantCarBrandTree,
getCarSeriesList(data) {
return api.post(
'scrm.api.carlife.common.getCarSeriesList',
data,
[],
CARLIFE_ROUTER,
CARLIFE_DOMAIN
)
},
getCarTypeList(carSeriesId) {
return api.post(
'scrm.api.carlife.common.getCarTypeList',
{ carSeriesId },
[],
CARLIFE_ROUTER,
CARLIFE_DOMAIN
)
}
}
...@@ -5,13 +5,23 @@ function staffDailyReportMerchantCarBand(data) { ...@@ -5,13 +5,23 @@ function staffDailyReportMerchantCarBand(data) {
} }
function staffDailyReportDetailWeeklyList(data) { function staffDailyReportDetailWeeklyList(data) {
return api.post('dj.api.smartcarlife.staff.daily.report.weekly.list', data) // 暂时不调用 dj.api.smartcarlife.staff.daily.report.weekly.list
return Promise.resolve({ code: 0, message: 'ok', data: [] })
// return api.post('dj.api.smartcarlife.staff.daily.report.weekly.list', data)
} }
function dynamicDailyReportSave(data) { function dynamicDailyReportSave(data) {
return api.post('dj.api.smartcarlife.dailyReport.dynamic.save', data) return api.post('dj.api.smartcarlife.dailyReport.dynamic.save', data)
} }
function dynamicDailyReportDetail(data) {
return api.post('dj.api.smartcarlife.dailyReport.dynamic.detail', data)
}
function dynamicDailyReportSchema(data) {
return api.post('dj.api.smartcarlife.dailyReport.dynamic.schema', data)
}
function findAllSceneByMerchantId(data) { function findAllSceneByMerchantId(data) {
return api.post('dj.api.scenemerchantref.findAllSceneByMerchantId', data) return api.post('dj.api.scenemerchantref.findAllSceneByMerchantId', data)
} }
...@@ -20,5 +30,7 @@ module.exports = { ...@@ -20,5 +30,7 @@ module.exports = {
staffDailyReportMerchantCarBand, staffDailyReportMerchantCarBand,
staffDailyReportDetailWeeklyList, staffDailyReportDetailWeeklyList,
dynamicDailyReportSave, dynamicDailyReportSave,
dynamicDailyReportDetail,
dynamicDailyReportSchema,
findAllSceneByMerchantId findAllSceneByMerchantId
} }
import api from '~/utils/request/request.js'
/**
* 动态表单字段选项( multipleSelect 通过 optionsKey 拉取 )
* 联调时替换为真实接口名
*/
function fetchFieldOptions(data) {
return api.post('dj.api.smartcarlife.dailyReport.field.options', data)
}
module.exports = {
fetchFieldOptions
}
const { getMockOptionsByKey } = require('../fixtures/mock-field-options.js')
const { isStaffMockMode, isStoreMockMode, isNegotiationMockMode } = require('../config/apiSwitch.js')
let fieldOptionsApiModule = null
function getFieldOptionsApi() {
if (!fieldOptionsApiModule) {
fieldOptionsApiModule = require('./fieldOptions.js')
}
return fieldOptionsApiModule
}
function resolveMockMode(reportType = 'store') {
if (reportType === 'staff') return isStaffMockMode('fieldOptions')
if (reportType === 'negotiation') return isNegotiationMockMode('fieldOptions')
return isStoreMockMode('fieldOptions')
}
async function fetchFieldOptionsAdapter(params = {}) {
const { optionsKey, reportType = 'store' } = params
if (!optionsKey) {
return { code: 0, message: 'ok', data: [] }
}
if (resolveMockMode(reportType)) {
return {
code: 0,
message: 'ok',
data: getMockOptionsByKey(optionsKey)
}
}
const { fetchFieldOptions } = getFieldOptionsApi()
return fetchFieldOptions({
optionsKey: params.optionsKey,
merchantId: params.merchantId,
staffUuid: params.staffUuid,
reportDate: params.reportDate
})
}
module.exports = {
fetchFieldOptionsAdapter,
getFieldOptionsApi
}
const { fetchFieldOptionsAdapter } = require('./fieldOptionsAdapters.js')
const optionsCache = new Map()
function buildCacheKey(params = {}) {
return [
params.optionsKey || '',
params.merchantId || '',
params.staffUuid || '',
params.reportDate || '',
params.reportType || 'store'
].join('|')
}
async function fetchFieldOptions(params = {}, options = {}) {
const { useCache = true } = options
const cacheKey = buildCacheKey(params)
if (useCache && optionsCache.has(cacheKey)) {
return optionsCache.get(cacheKey)
}
const result = await fetchFieldOptionsAdapter(params)
if (result?.code === 0 && useCache) {
optionsCache.set(cacheKey, result)
}
return result
}
function clearFieldOptionsCache() {
optionsCache.clear()
}
module.exports = {
fetchFieldOptions,
clearFieldOptionsCache
}
...@@ -75,7 +75,6 @@ function initSampleDetail() { ...@@ -75,7 +75,6 @@ function initSampleDetail() {
reportTemplateId: DEFAULT_REPORT_TEMPLATE_ID, reportTemplateId: DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: 90001, dailyReportRecordId: 90001,
baseSceneCode: BOUTIQUE_PAGE_CONTEXT.baseSceneCode, baseSceneCode: BOUTIQUE_PAGE_CONTEXT.baseSceneCode,
sceneType: BOUTIQUE_PAGE_CONTEXT.sceneType,
fieldDataList: valuesToFieldDataList(values) fieldDataList: valuesToFieldDataList(values)
}) })
} }
...@@ -102,7 +101,6 @@ function fetchMockDynamicDetail(params = {}) { ...@@ -102,7 +101,6 @@ function fetchMockDynamicDetail(params = {}) {
reportTemplateId: reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID, reportTemplateId: reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: null, dailyReportRecordId: null,
baseSceneCode: BOUTIQUE_PAGE_CONTEXT.baseSceneCode, baseSceneCode: BOUTIQUE_PAGE_CONTEXT.baseSceneCode,
sceneType: BOUTIQUE_PAGE_CONTEXT.sceneType,
fieldDataList: [], fieldDataList: [],
jsonContent: '' jsonContent: ''
} }
...@@ -116,7 +114,6 @@ function fetchMockDynamicDetail(params = {}) { ...@@ -116,7 +114,6 @@ function fetchMockDynamicDetail(params = {}) {
reportTemplateId: record.reportTemplateId || reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID, reportTemplateId: record.reportTemplateId || reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: record.dailyReportRecordId || null, dailyReportRecordId: record.dailyReportRecordId || null,
baseSceneCode: record.baseSceneCode ?? BOUTIQUE_PAGE_CONTEXT.baseSceneCode, baseSceneCode: record.baseSceneCode ?? BOUTIQUE_PAGE_CONTEXT.baseSceneCode,
sceneType: record.sceneType ?? BOUTIQUE_PAGE_CONTEXT.sceneType,
fieldDataList: record.fieldDataList || [], fieldDataList: record.fieldDataList || [],
jsonContent: record.jsonContent || '' jsonContent: record.jsonContent || ''
} }
...@@ -133,7 +130,6 @@ function saveMockDynamicDetail(params = {}) { ...@@ -133,7 +130,6 @@ function saveMockDynamicDetail(params = {}) {
reportTemplateId: reportTemplateId || prev.reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID, reportTemplateId: reportTemplateId || prev.reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: dailyReportRecordId || prev.dailyReportRecordId || Date.now(), dailyReportRecordId: dailyReportRecordId || prev.dailyReportRecordId || Date.now(),
baseSceneCode: prev.baseSceneCode ?? BOUTIQUE_PAGE_CONTEXT.baseSceneCode, baseSceneCode: prev.baseSceneCode ?? BOUTIQUE_PAGE_CONTEXT.baseSceneCode,
sceneType: prev.sceneType ?? BOUTIQUE_PAGE_CONTEXT.sceneType,
fieldDataList: fieldDataList || prev.fieldDataList || [], fieldDataList: fieldDataList || prev.fieldDataList || [],
jsonContent: jsonContent || prev.jsonContent || '' jsonContent: jsonContent || prev.jsonContent || ''
} }
......
const { WARRANTY_PAGE_CONTEXT } = require('../fixtures/mock-meta.js')
const detailStore = new Map()
const DEFAULT_REPORT_TEMPLATE_ID = 10003
function formatDate(date) {
const y = date.getFullYear()
const m = `${date.getMonth() + 1}`.padStart(2, '0')
const d = `${date.getDate()}`.padStart(2, '0')
return `${y}-${m}-${d}`
}
function getStoreKey({ merchantId, staffUuid, reportDate }) {
return `${merchantId || '0'}:${staffUuid || '0'}:${reportDate}`
}
function delay(data, ms = 80) {
return new Promise(resolve => {
setTimeout(() => resolve(data), ms)
})
}
function fetchMockNegotiationDynamicDetail(params = {}) {
const { merchantId, staffUuid, reportDate, reportTemplateId } = params
const storeKey = getStoreKey({ merchantId, staffUuid, reportDate })
const record = detailStore.get(storeKey)
if (!record) {
return delay({
code: 0,
message: 'ok',
data: {
reportTemplateId: reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: null,
baseSceneCode: WARRANTY_PAGE_CONTEXT.baseSceneCode,
fieldDataList: [],
jsonContent: ''
}
})
}
return delay({
code: 0,
message: 'ok',
data: {
reportTemplateId: record.reportTemplateId || reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: record.dailyReportRecordId || null,
baseSceneCode: record.baseSceneCode ?? WARRANTY_PAGE_CONTEXT.baseSceneCode,
fieldDataList: record.fieldDataList || [],
jsonContent: record.jsonContent || ''
}
})
}
function saveMockNegotiationDynamicDetail(params = {}) {
const { merchantId, staffUuid, reportDate, reportTemplateId, dailyReportRecordId, fieldDataList, jsonContent } =
params
if (!reportDate) return null
const storeKey = getStoreKey({ merchantId, staffUuid, reportDate })
const prev = detailStore.get(storeKey) || {}
const nextRecord = {
reportTemplateId: reportTemplateId || prev.reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: dailyReportRecordId || prev.dailyReportRecordId || Date.now(),
baseSceneCode: prev.baseSceneCode ?? WARRANTY_PAGE_CONTEXT.baseSceneCode,
fieldDataList: fieldDataList || prev.fieldDataList || [],
jsonContent: jsonContent || prev.jsonContent || ''
}
detailStore.set(storeKey, nextRecord)
return nextRecord
}
module.exports = {
fetchMockNegotiationDynamicDetail,
saveMockNegotiationDynamicDetail,
DEFAULT_REPORT_TEMPLATE_ID
}
const { WARRANTY_PAGE_CONTEXT } = require('../fixtures/mock-meta.js')
const detailStore = new Map()
const DEFAULT_REPORT_TEMPLATE_ID = 10002
function formatDate(date) {
const y = date.getFullYear()
const m = `${date.getMonth() + 1}`.padStart(2, '0')
const d = `${date.getDate()}`.padStart(2, '0')
return `${y}-${m}-${d}`
}
function getStoreKey({ merchantId, staffUuid, reportDate }) {
return `${merchantId || '0'}:${staffUuid || '0'}:${reportDate}`
}
function getWarrantySampleValues() {
return {
'F2-1': ['staff-001', 'staff-002'],
'F2-2': 3,
'F2-30': 5,
'F2-36': 2,
'F2-3': 4,
'F2-9': [
{
'F2-9-1': '4s-001',
'F2-9-2': 1,
'F2-9-3': 2,
'F2-9-4': 3,
'F2-9-5': 1,
'F2-9-6': 0,
'F2-9-7': 0,
'F2-9-8': 0
},
{
'F2-9-1': '4s-002',
'F2-9-2': 2,
'F2-9-3': 1,
'F2-9-4': 0,
'F2-9-5': 0,
'F2-9-6': 1,
'F2-9-7': 0,
'F2-9-8': 1
}
]
}
}
function valuesToFieldDataList(values = {}, schemaLabels = {}) {
const items = []
Object.keys(values).forEach(fieldKey => {
const fieldValue = values[fieldKey]
if (Array.isArray(fieldValue) && fieldValue.length && typeof fieldValue[0] === 'object') {
fieldValue.forEach((row, rowIndex) => {
Object.keys(row || {}).forEach(childKey => {
const childValue = row[childKey]
if (childValue === undefined || childValue === null || childValue === '') {
return
}
items.push({
groupKey: fieldKey,
rowIndex,
fieldKey: childKey,
fieldName: schemaLabels[childKey] || childKey,
fieldType: childKey.endsWith('-1') ? 'select' : 'numberInput',
fieldValue: childValue
})
})
})
return
}
items.push({
fieldKey,
fieldName: schemaLabels[fieldKey] || fieldKey,
fieldType: fieldKey === 'F2-1' ? 'multipleSelect' : fieldKey.endsWith('-1') ? 'select' : 'numberInput',
fieldValue
})
})
return items
}
function initSampleDetail() {
const today = new Date()
const day = today.getDay()
const mondayOffset = day === 0 ? -6 : 1 - day
const monday = new Date(today)
monday.setDate(today.getDate() + mondayOffset)
const mondayStr = formatDate(monday)
const sampleKey = getStoreKey({
merchantId: 'mock',
staffUuid: 'mock',
reportDate: mondayStr
})
if (!detailStore.has(sampleKey)) {
const values = getWarrantySampleValues()
detailStore.set(sampleKey, {
reportTemplateId: DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: 91001,
baseSceneCode: WARRANTY_PAGE_CONTEXT.baseSceneCode,
fieldDataList: valuesToFieldDataList(values)
})
}
}
function delay(data, ms = 80) {
return new Promise(resolve => {
setTimeout(() => resolve(data), ms)
})
}
initSampleDetail()
function fetchMockStoreDynamicDetail(params = {}) {
const { merchantId, staffUuid, reportDate, reportTemplateId } = params
const storeKey = getStoreKey({ merchantId, staffUuid, reportDate })
const record = detailStore.get(storeKey)
if (!record) {
return delay({
code: 0,
message: 'ok',
data: {
reportTemplateId: reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: null,
baseSceneCode: WARRANTY_PAGE_CONTEXT.baseSceneCode,
fieldDataList: [],
jsonContent: ''
}
})
}
return delay({
code: 0,
message: 'ok',
data: {
reportTemplateId: record.reportTemplateId || reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: record.dailyReportRecordId || null,
baseSceneCode: record.baseSceneCode ?? WARRANTY_PAGE_CONTEXT.baseSceneCode,
fieldDataList: record.fieldDataList || [],
jsonContent: record.jsonContent || ''
}
})
}
function saveMockStoreDynamicDetail(params = {}) {
const { merchantId, staffUuid, reportDate, reportTemplateId, dailyReportRecordId, fieldDataList, jsonContent } =
params
if (!reportDate) return null
const storeKey = getStoreKey({ merchantId, staffUuid, reportDate })
const prev = detailStore.get(storeKey) || {}
const nextRecord = {
reportTemplateId: reportTemplateId || prev.reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: dailyReportRecordId || prev.dailyReportRecordId || Date.now(),
baseSceneCode: prev.baseSceneCode ?? WARRANTY_PAGE_CONTEXT.baseSceneCode,
fieldDataList: fieldDataList || prev.fieldDataList || [],
jsonContent: jsonContent || prev.jsonContent || ''
}
detailStore.set(storeKey, nextRecord)
return nextRecord
}
module.exports = {
fetchMockStoreDynamicDetail,
saveMockStoreDynamicDetail,
DEFAULT_REPORT_TEMPLATE_ID
}
const { buildPageContext, SCHEMA_OPTIONS_MAP } = require('../fixtures/mock-meta.js')
const { dynamicDailyReportSave } = require('./dynamicDailyReport.js')
const { DEFAULT_REPORT_TEMPLATE_ID } = require('./mockNegotiationDynamicDetail.js')
import { envIndex } from '~/config.js'
import {
buildDynamicSavePayload,
parseDetailValues,
mapBrandListToBrandIds,
mergeValuesIntoSchema
} from '../form-engine/submit-adapter.js'
import { normalizeSchemaRoot } from '../form-engine/schema-normalizer.js'
import { resolveBaseSceneCode } from '../form-engine/page-context.js'
const {
fetchDetailAdapter,
fetchSchemaRootAdapter,
fetchSceneAdapter,
fetchBrandAdapter,
fetchWeeklyAdapter,
saveEchoAdapter
} = require('./negotiationDailyReportAdapters.js')
const { isNegotiationMockMode } = require('../config/apiSwitch.js')
const IS_PRODUCTION = envIndex === 3
function normalizeUserInfo(userInfo = {}) {
const merchantId =
userInfo.merchantId ||
userInfo.shopMerchantId ||
userInfo.default4SStoreInfo?.merchantId ||
''
return {
merchantId,
yqMerchantId: userInfo.yqMerchantId || merchantId || '',
staffUuid: userInfo.uuid || userInfo.staffUuid || '',
baseSceneCode: userInfo.baseSceneCode,
merchantName: userInfo.merchantName || '',
staffName: userInfo.name || userInfo.staffName || ''
}
}
function buildPageContextFromSources({
userInfo = {},
brandIds = [],
detail = {},
baseSceneCode,
sceneList
} = {}) {
const normalized = normalizeUserInfo(userInfo)
return buildPageContext({ baseSceneCode }, brandIds, normalized, sceneList || [])
}
function unwrapResponse(result = {}) {
return {
code: result.code,
message: result.message || '请求失败',
data: result.data
}
}
async function fetchMerchantScene({ merchantId, detailBaseSceneCode, hasRecord } = {}) {
if (!merchantId) {
return {
code: 0,
message: 'ok',
baseSceneCode: resolveBaseSceneCode([], detailBaseSceneCode, hasRecord),
sceneList: []
}
}
const result = await fetchSceneAdapter({ merchantId })
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
return {
code: code ?? -1,
message,
baseSceneCode: resolveBaseSceneCode([], detailBaseSceneCode, hasRecord),
sceneList: []
}
}
const sceneList = Array.isArray(data) ? data : []
return {
code: 0,
message: 'ok',
baseSceneCode: resolveBaseSceneCode(sceneList, detailBaseSceneCode, hasRecord),
sceneList
}
}
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)
}
}
async function fetchPageContext(options = {}) {
const { userInfo = {}, brandIds = [], detail = {}, merchantScene = {} } = options
const hasRecord = !!detail.dailyReportRecordId
let baseSceneCode = resolveBaseSceneCode(
merchantScene.sceneList || [],
detail.baseSceneCode,
hasRecord
)
if (baseSceneCode == null) {
baseSceneCode = merchantScene.baseSceneCode ?? null
}
if (baseSceneCode == null) {
return {
code: -1,
message: '获取门店场景失败',
data: null
}
}
return {
code: 0,
message: 'ok',
data: buildPageContextFromSources({
userInfo,
brandIds,
detail,
baseSceneCode,
sceneList: merchantScene.sceneList || []
})
}
}
function buildEmptyDetail(reportTemplateId) {
return {
reportTemplateId: reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: null,
values: {}
}
}
async function fetchReportDetail({ merchantId, staffUuid, reportDate, reportTemplateId } = {}) {
if (!merchantId || !staffUuid || !reportDate) {
return {
code: 0,
message: 'ok',
data: buildEmptyDetail(reportTemplateId)
}
}
const result = await fetchDetailAdapter({
merchantId,
staffUuid,
reportDate,
reportTemplateId
})
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
return { code: code ?? -1, message, data: null }
}
return normalizeDetailResponse(data, reportTemplateId)
}
function normalizeDetailResponse(detail = {}, reportTemplateId) {
return {
code: 0,
message: 'ok',
data: {
reportTemplateId: detail.reportTemplateId || reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: detail.dailyReportRecordId || null,
baseSceneCode: detail.baseSceneCode,
values: parseDetailValues(detail)
}
}
}
async function fetchSchema({
reportTemplateId,
baseSceneCode,
merchantId,
detailValues = {}
} = {}) {
const result = await fetchSchemaRootAdapter({
reportTemplateId,
baseSceneCode,
merchantId
})
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
if (isNegotiationMockMode('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 normalizedRoot = normalizeSchemaRoot(data, SCHEMA_OPTIONS_MAP)
const schema = mergeValuesIntoSchema(normalizedRoot, detailValues)
return {
code: 0,
message: 'ok',
data: schema
}
}
async function fetchWeeklyList({
merchantId,
yqMerchantId,
staffUuid,
reportStartDate,
reportEndDate,
timeBean = {}
} = {}) {
if (!merchantId) {
return { code: 0, message: 'ok', data: [] }
}
const result = await fetchWeeklyAdapter({
merchantId,
yqMerchantId,
staffUuid,
reportTypeList: [-1],
reportStartDate,
reportEndDate,
...timeBean
})
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 : []
}
}
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 savePayload = buildDynamicSavePayload({
reportTemplateId,
dailyReportRecordId,
engine,
reportDate
})
if (!IS_PRODUCTION) {
console.log('[negotiationDailyReport] dynamic.save 提交数据结构', savePayload)
console.log('[negotiationDailyReport] dynamic.save jsonContent', JSON.parse(savePayload.jsonContent))
}
const pageContext = engine.getPageContext()
const userContext = normalizeUserInfo(wx.$util?.getUserInfo?.() || {})
const result = await dynamicDailyReportSave(savePayload)
const { code, message, data } = unwrapResponse(result)
if (code == 0) {
const savedRecord = saveEchoAdapter({
merchantId: pageContext.merchantId || userContext.merchantId,
staffUuid: userContext.staffUuid,
reportDate,
reportTemplateId,
dailyReportRecordId: data?.dailyReportRecordId || dailyReportRecordId,
fieldDataList: savePayload.fieldDataList,
jsonContent: savePayload.jsonContent
})
return {
code: 0,
message,
data: {
...(data || {}),
dailyReportRecordId: savedRecord?.dailyReportRecordId || data?.dailyReportRecordId || dailyReportRecordId
}
}
}
return {
code: code ?? -1,
message,
data
}
}
module.exports = {
fetchMerchantBrandIds,
fetchMerchantScene,
fetchPageContext,
fetchReportDetail,
fetchSchema,
fetchWeeklyList,
submitForm,
buildPageContextFromSources,
normalizeUserInfo
}
const schemaTemplate = require('../fixtures/schema-negotiation-full.js')
const { MOCK_MERCHANT_BRAND_LIST, MOCK_MERCHANT_SCENE_LIST } = require('../fixtures/mock-meta.js')
const { isNegotiationMockMode, isNegotiationSaveEchoEnabled } = require('../config/apiSwitch.js')
const {
fetchMockNegotiationDynamicDetail,
saveMockNegotiationDynamicDetail
} = require('./mockNegotiationDynamicDetail.js')
const {
getCachedScene,
setCachedScene,
getCachedSchema,
setCachedSchema
} = require('./negotiationDailyReportCache.js')
const {
fetchConfigCenterTemplate,
DYNAMIC_FORM_TEMPLATE_MODULE
} = require('../config/configCenter.js')
let dynamicDailyReportApiModule = null
function getDynamicDailyReportApi() {
if (!dynamicDailyReportApiModule) {
dynamicDailyReportApiModule = require('./dynamicDailyReport.js')
}
return dynamicDailyReportApiModule
}
async function fetchDetailAdapter(params = {}) {
if (isNegotiationMockMode('detail')) {
return fetchMockNegotiationDynamicDetail(params)
}
const { dynamicDailyReportDetail } = getDynamicDailyReportApi()
return dynamicDailyReportDetail(params)
}
async function fetchSchemaRootAdapter(params = {}) {
const { reportTemplateId, baseSceneCode, merchantId } = params
if (isNegotiationMockMode('schema')) {
return {
code: 0,
message: 'ok',
data: schemaTemplate
}
}
const moduleUrl = DYNAMIC_FORM_TEMPLATE_MODULE.negotiation
const cached = getCachedSchema(moduleUrl, baseSceneCode)
if (cached) {
return cached
}
const result = await fetchConfigCenterTemplate(moduleUrl)
setCachedSchema(moduleUrl, baseSceneCode, result)
return result
}
async function fetchSceneAdapter(params = {}) {
const { merchantId } = params
if (isNegotiationMockMode('scene')) {
return {
code: 0,
message: 'ok',
data: MOCK_MERCHANT_SCENE_LIST
}
}
const cached = getCachedScene(merchantId)
if (cached) {
return cached
}
const { findAllSceneByMerchantId } = getDynamicDailyReportApi()
const result = await findAllSceneByMerchantId({ merchantId })
setCachedScene(merchantId, result)
return result
}
async function fetchBrandAdapter(params = {}) {
if (isNegotiationMockMode('brand')) {
return { code: 0, message: 'ok', data: MOCK_MERCHANT_BRAND_LIST }
}
const { staffDailyReportMerchantCarBand } = getDynamicDailyReportApi()
return staffDailyReportMerchantCarBand(params)
}
async function fetchWeeklyAdapter(params = {}) {
if (isNegotiationMockMode('weekly')) {
return { code: 0, message: 'ok', data: [] }
}
const { staffDailyReportDetailWeeklyList } = getDynamicDailyReportApi()
return staffDailyReportDetailWeeklyList(params)
}
function saveEchoAdapter(params = {}) {
if (!isNegotiationSaveEchoEnabled()) {
return null
}
return saveMockNegotiationDynamicDetail(params)
}
module.exports = {
fetchDetailAdapter,
fetchSchemaRootAdapter,
fetchSceneAdapter,
fetchBrandAdapter,
fetchWeeklyAdapter,
saveEchoAdapter,
getDynamicDailyReportApi
}
const sceneCache = new Map()
const schemaCache = new Map()
function getSchemaCacheKey(reportTemplateId, baseSceneCode) {
return `${reportTemplateId || ''}:${baseSceneCode || ''}`
}
function getCachedScene(merchantId) {
if (!merchantId) return null
return sceneCache.get(merchantId) || null
}
function setCachedScene(merchantId, value) {
if (!merchantId) return
sceneCache.set(merchantId, value)
}
function getCachedSchema(reportTemplateId, baseSceneCode) {
return schemaCache.get(getSchemaCacheKey(reportTemplateId, baseSceneCode)) || null
}
function setCachedSchema(reportTemplateId, baseSceneCode, value) {
schemaCache.set(getSchemaCacheKey(reportTemplateId, baseSceneCode), value)
}
function clearNegotiationDailyReportCache() {
sceneCache.clear()
schemaCache.clear()
}
module.exports = {
getSchemaCacheKey,
getCachedScene,
setCachedScene,
getCachedSchema,
setCachedSchema,
clearNegotiationDailyReportCache
}
const schemaTemplate = require('../fixtures/schema-staff-daily-full.js') const { buildPageContext } = require('../fixtures/mock-meta.js')
const { const { dynamicDailyReportSave } = require('./dynamicDailyReport.js')
brandIdMap, const { DEFAULT_REPORT_TEMPLATE_ID } = require('./mockDynamicDetail.js')
baseSceneCodeMap, import { envIndex } from '~/config.js'
sceneTypeMap,
buildPageContext
} = require('../fixtures/mock-meta.js')
const {
staffDailyReportMerchantCarBand,
staffDailyReportDetailWeeklyList,
dynamicDailyReportSave,
findAllSceneByMerchantId
} = require('./dynamicDailyReport.js')
const { fetchMockDynamicDetail, saveMockDynamicDetail, DEFAULT_REPORT_TEMPLATE_ID } = require('./mockDynamicDetail.js')
import { import {
buildDynamicSavePayload, buildDynamicSavePayload,
parseDetailValues, parseDetailValues,
mapBrandListToBrandIds, mapBrandListToBrandIds,
mergeValuesIntoSchema mergeValuesIntoSchema
} from '~/utils/form-engine/submit-adapter.js' } from '../form-engine/submit-adapter.js'
import { import {
resolveBaseSceneCode, resolveBaseSceneCode
resolveSceneType } from '../form-engine/page-context.js'
} from '~/utils/form-engine/page-context.js' const {
fetchDetailAdapter,
fetchSchemaRootAdapter,
fetchSceneAdapter,
fetchBrandAdapter,
fetchWeeklyAdapter,
saveEchoAdapter
} = require('./staffDailyReportAdapters.js')
const { isStaffMockMode } = require('../config/apiSwitch.js')
const IS_PRODUCTION = envIndex === 3
function normalizeUserInfo(userInfo = {}) { function normalizeUserInfo(userInfo = {}) {
return { return {
merchantId: userInfo.merchantId || userInfo.shopMerchantId || '', merchantId: userInfo.merchantId || userInfo.shopMerchantId || '',
yqMerchantId: userInfo.yqMerchantId || userInfo.merchantId || '', yqMerchantId: userInfo.yqMerchantId || userInfo.merchantId || '',
staffUuid: userInfo.uuid || userInfo.staffUuid || '', staffUuid: userInfo.uuid || userInfo.staffUuid || '',
sceneType: userInfo.sceneType ?? 1,
baseSceneCode: userInfo.baseSceneCode, baseSceneCode: userInfo.baseSceneCode,
merchantName: userInfo.merchantName || '', merchantName: userInfo.merchantName || '',
staffName: userInfo.name || userInfo.staffName || '' staffName: userInfo.name || userInfo.staffName || ''
...@@ -39,37 +38,42 @@ function buildPageContextFromSources({ ...@@ -39,37 +38,42 @@ function buildPageContextFromSources({
userInfo = {}, userInfo = {},
brandIds = [], brandIds = [],
detail = {}, detail = {},
routeSceneType, baseSceneCode,
baseSceneCode sceneList
} = {}) { } = {}) {
const normalized = normalizeUserInfo(userInfo) const normalized = normalizeUserInfo(userInfo)
const sceneType = resolveSceneType({ routeSceneType, detail, userInfo })
return buildPageContext( return buildPageContext(
{ { baseSceneCode },
baseSceneCode,
sceneType
},
brandIds, brandIds,
normalized normalized,
sceneList || []
) )
} }
async function fetchMerchantScene({ merchantId, sceneType, detailBaseSceneCode } = {}) { function unwrapResponse(result = {}) {
return {
code: result.code,
message: result.message || '请求失败',
data: result.data
}
}
async function fetchMerchantScene({ merchantId, detailBaseSceneCode, hasRecord } = {}) {
if (!merchantId) { if (!merchantId) {
return { return {
code: 0, code: 0,
message: 'ok', message: 'ok',
baseSceneCode: resolveBaseSceneCode([], sceneType, detailBaseSceneCode), baseSceneCode: resolveBaseSceneCode([], detailBaseSceneCode, hasRecord),
sceneList: [] sceneList: []
} }
} }
const result = await findAllSceneByMerchantId({ merchantId }) const result = await fetchSceneAdapter({ merchantId })
const { code, message, data } = unwrapResponse(result) const { code, message, data } = unwrapResponse(result)
if (code != 0) { if (code != 0) {
return { return {
code: code ?? -1, code: code ?? -1,
message, message,
baseSceneCode: resolveBaseSceneCode([], sceneType, detailBaseSceneCode), baseSceneCode: resolveBaseSceneCode([], detailBaseSceneCode, hasRecord),
sceneList: [] sceneList: []
} }
} }
...@@ -77,39 +81,16 @@ async function fetchMerchantScene({ merchantId, sceneType, detailBaseSceneCode } ...@@ -77,39 +81,16 @@ async function fetchMerchantScene({ merchantId, sceneType, detailBaseSceneCode }
return { return {
code: 0, code: 0,
message: 'ok', message: 'ok',
baseSceneCode: resolveBaseSceneCode(sceneList, sceneType, detailBaseSceneCode), baseSceneCode: resolveBaseSceneCode(sceneList, detailBaseSceneCode, hasRecord),
sceneList sceneList
} }
} }
function unwrapResponse(result = {}) { async function fetchMerchantBrandIds({ merchantId } = {}) {
return {
code: result.code,
message: result.message || '请求失败',
data: result.data
}
}
function fetchMeta() {
return Promise.resolve({
code: 0,
message: 'ok',
data: {
brandIdMap: { ...brandIdMap },
baseSceneCodeMap: { ...baseSceneCodeMap },
sceneTypeMap: { ...sceneTypeMap }
}
})
}
async function fetchMerchantBrandIds({ merchantId, sceneType = 1 } = {}) {
if (!merchantId) { if (!merchantId) {
return { code: 0, message: 'ok', data: [] } return { code: 0, message: 'ok', data: [] }
} }
const result = await staffDailyReportMerchantCarBand({ const result = await fetchBrandAdapter({ merchantId })
merchantId,
sceneType
})
const { code, message, data } = unwrapResponse(result) const { code, message, data } = unwrapResponse(result)
if (code != 0) { if (code != 0) {
return { code: code ?? -1, message, data: [] } return { code: code ?? -1, message, data: [] }
...@@ -127,35 +108,16 @@ async function fetchPageContext(options = {}) { ...@@ -127,35 +108,16 @@ async function fetchPageContext(options = {}) {
userInfo = {}, userInfo = {},
brandIds = [], brandIds = [],
detail = {}, detail = {},
routeSceneType, merchantScene = {}
merchantScene
} = options } = options
const normalized = normalizeUserInfo(userInfo) const hasRecord = !!detail.dailyReportRecordId
const sceneType = resolveSceneType({ routeSceneType, detail, userInfo }) let baseSceneCode = resolveBaseSceneCode(
let baseSceneCode = merchantScene?.baseSceneCode merchantScene.sceneList || [],
detail.baseSceneCode,
if (baseSceneCode == null && merchantScene?.sceneList) { hasRecord
baseSceneCode = resolveBaseSceneCode(
merchantScene.sceneList,
sceneType,
detail.baseSceneCode
) )
} if (baseSceneCode == null) {
baseSceneCode = merchantScene.baseSceneCode ?? null
if (baseSceneCode == null && normalized.merchantId) {
const sceneRes = await fetchMerchantScene({
merchantId: normalized.merchantId,
sceneType,
detailBaseSceneCode: detail.baseSceneCode
})
if (sceneRes.code !== 0) {
return {
code: sceneRes.code,
message: sceneRes.message || '获取门店场景失败',
data: null
}
}
baseSceneCode = sceneRes.baseSceneCode
} }
if (baseSceneCode == null) { if (baseSceneCode == null) {
...@@ -173,42 +135,48 @@ async function fetchPageContext(options = {}) { ...@@ -173,42 +135,48 @@ async function fetchPageContext(options = {}) {
userInfo, userInfo,
brandIds, brandIds,
detail, detail,
routeSceneType, baseSceneCode,
baseSceneCode sceneList: merchantScene.sceneList || []
}) })
} }
} }
function buildEmptyDetail(reportTemplateId) {
return {
reportTemplateId: reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: null,
values: {}
}
}
async function fetchReportDetail({ async function fetchReportDetail({
merchantId, merchantId,
staffUuid, staffUuid,
reportDate, reportDate,
sceneType = 1,
reportTemplateId reportTemplateId
} = {}) { } = {}) {
if (!merchantId || !staffUuid || !reportDate) { if (!merchantId || !staffUuid || !reportDate) {
return { return {
code: 0, code: 0,
message: 'ok', message: 'ok',
data: { data: buildEmptyDetail(reportTemplateId)
reportTemplateId: reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: null,
values: {}
}
} }
} }
const result = await fetchMockDynamicDetail({
const result = await fetchDetailAdapter({
merchantId, merchantId,
staffUuid, staffUuid,
reportDate, reportDate,
sceneType,
reportTemplateId reportTemplateId
}) })
const { code, message, data } = unwrapResponse(result) const { code, message, data } = unwrapResponse(result)
if (code != 0) { if (code != 0) {
return { code: code ?? -1, message, data: null } return { code: code ?? -1, message, data: null }
} }
const detail = data || {} return normalizeDetailResponse(data, reportTemplateId)
}
function normalizeDetailResponse(detail = {}, reportTemplateId) {
return { return {
code: 0, code: 0,
message: 'ok', message: 'ok',
...@@ -216,26 +184,44 @@ async function fetchReportDetail({ ...@@ -216,26 +184,44 @@ async function fetchReportDetail({
reportTemplateId: detail.reportTemplateId || reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID, reportTemplateId: detail.reportTemplateId || reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: detail.dailyReportRecordId || null, dailyReportRecordId: detail.dailyReportRecordId || null,
baseSceneCode: detail.baseSceneCode, baseSceneCode: detail.baseSceneCode,
sceneType: detail.sceneType,
values: parseDetailValues(detail) values: parseDetailValues(detail)
} }
} }
} }
function fetchSchema({ detailValues = {} } = {}) { async function fetchSchema({
const schema = mergeValuesIntoSchema(schemaTemplate, detailValues) reportTemplateId,
return Promise.resolve({ baseSceneCode,
merchantId,
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 schema = mergeValuesIntoSchema(data, detailValues)
return {
code: 0, code: 0,
message: 'ok', message: 'ok',
data: schema data: schema
}) }
} }
async function fetchWeeklyList({ async function fetchWeeklyList({
merchantId, merchantId,
yqMerchantId, yqMerchantId,
staffUuid, staffUuid,
sceneType = 1,
reportStartDate, reportStartDate,
reportEndDate, reportEndDate,
timeBean = {} timeBean = {}
...@@ -243,11 +229,10 @@ async function fetchWeeklyList({ ...@@ -243,11 +229,10 @@ async function fetchWeeklyList({
if (!merchantId) { if (!merchantId) {
return { code: 0, message: 'ok', data: [] } return { code: 0, message: 'ok', data: [] }
} }
const result = await staffDailyReportDetailWeeklyList({ const result = await fetchWeeklyAdapter({
merchantId, merchantId,
yqMerchantId, yqMerchantId,
staffUuid, staffUuid,
sceneType,
reportTypeList: [-1], reportTypeList: [-1],
reportStartDate, reportStartDate,
reportEndDate, reportEndDate,
...@@ -281,15 +266,16 @@ async function submitForm(payload = {}) { ...@@ -281,15 +266,16 @@ async function submitForm(payload = {}) {
engine, engine,
reportDate reportDate
}) })
if (!IS_PRODUCTION) {
console.log('[staffDailyReport] dynamic.save 提交数据结构', savePayload) console.log('[staffDailyReport] dynamic.save 提交数据结构', savePayload)
// console.log('[staffDailyReport] dynamic.save jsonContent', json.parse(savePayload.jsonContent))
console.log('[staffDailyReport] dynamic.save jsonContent', JSON.parse(savePayload.jsonContent)) console.log('[staffDailyReport] dynamic.save jsonContent', JSON.parse(savePayload.jsonContent))
}
const pageContext = engine.getPageContext() const pageContext = engine.getPageContext()
const userContext = normalizeUserInfo(wx.$util?.getUserInfo?.() || {}) const userContext = normalizeUserInfo(wx.$util?.getUserInfo?.() || {})
const result = await dynamicDailyReportSave(savePayload) const result = await dynamicDailyReportSave(savePayload)
const { code, message, data } = unwrapResponse(result) const { code, message, data } = unwrapResponse(result)
if (code == 0) { if (code == 0) {
const savedRecord = saveMockDynamicDetail({ const savedRecord = saveEchoAdapter({
merchantId: pageContext.merchantId || userContext.merchantId, merchantId: pageContext.merchantId || userContext.merchantId,
staffUuid: userContext.staffUuid, staffUuid: userContext.staffUuid,
reportDate, reportDate,
...@@ -303,7 +289,7 @@ async function submitForm(payload = {}) { ...@@ -303,7 +289,7 @@ async function submitForm(payload = {}) {
message, message,
data: { data: {
...(data || {}), ...(data || {}),
dailyReportRecordId: savedRecord?.dailyReportRecordId dailyReportRecordId: savedRecord?.dailyReportRecordId || data?.dailyReportRecordId || dailyReportRecordId
} }
} }
} }
...@@ -315,7 +301,6 @@ async function submitForm(payload = {}) { ...@@ -315,7 +301,6 @@ async function submitForm(payload = {}) {
} }
module.exports = { module.exports = {
fetchMeta,
fetchMerchantBrandIds, fetchMerchantBrandIds,
fetchMerchantScene, fetchMerchantScene,
fetchPageContext, fetchPageContext,
......
const schemaTemplate = require('../fixtures/schema-staff-daily-full.js')
const { MOCK_MERCHANT_BRAND_LIST, MOCK_MERCHANT_SCENE_LIST } = require('../fixtures/mock-meta.js')
const { isStaffMockMode, isStaffSaveEchoEnabled } = require('../config/apiSwitch.js')
const { fetchMockDynamicDetail, saveMockDynamicDetail } = require('./mockDynamicDetail.js')
const {
getCachedScene,
setCachedScene,
getCachedSchema,
setCachedSchema
} = require('./staffDailyReportCache.js')
const {
fetchConfigCenterTemplate,
DYNAMIC_FORM_TEMPLATE_MODULE
} = require('../config/configCenter.js')
let dynamicDailyReportApiModule = null
function getDynamicDailyReportApi() {
if (!dynamicDailyReportApiModule) {
dynamicDailyReportApiModule = require('./dynamicDailyReport.js')
}
return dynamicDailyReportApiModule
}
function __setDynamicDailyReportApi(api) {
dynamicDailyReportApiModule = api
}
async function fetchDetailAdapter(params = {}) {
if (isStaffMockMode('detail')) {
return fetchMockDynamicDetail(params)
}
const { dynamicDailyReportDetail } = getDynamicDailyReportApi()
return dynamicDailyReportDetail(params)
}
async function fetchSchemaRootAdapter(params = {}) {
const { reportTemplateId, baseSceneCode, merchantId } = params
if (isStaffMockMode('schema')) {
return {
code: 0,
message: 'ok',
data: schemaTemplate
}
}
const moduleUrl = DYNAMIC_FORM_TEMPLATE_MODULE.staff
const cached = getCachedSchema(moduleUrl, baseSceneCode)
if (cached) {
return cached
}
const result = await fetchConfigCenterTemplate(moduleUrl)
setCachedSchema(moduleUrl, baseSceneCode, result)
return result
}
async function fetchSceneAdapter(params = {}) {
const { merchantId } = params
if (isStaffMockMode('scene')) {
return {
code: 0,
message: 'ok',
data: MOCK_MERCHANT_SCENE_LIST
}
}
const cached = getCachedScene(merchantId)
if (cached) {
return cached
}
const { findAllSceneByMerchantId } = getDynamicDailyReportApi()
const result = await findAllSceneByMerchantId({ merchantId })
setCachedScene(merchantId, result)
return result
}
async function fetchBrandAdapter(params = {}) {
if (isStaffMockMode('brand')) {
return { code: 0, message: 'ok', data: MOCK_MERCHANT_BRAND_LIST }
}
const { staffDailyReportMerchantCarBand } = getDynamicDailyReportApi()
return staffDailyReportMerchantCarBand(params)
}
async function fetchWeeklyAdapter(params = {}) {
if (isStaffMockMode('weekly')) {
return { code: 0, message: 'ok', data: [] }
}
const { staffDailyReportDetailWeeklyList } = getDynamicDailyReportApi()
return staffDailyReportDetailWeeklyList(params)
}
function saveEchoAdapter(params = {}) {
if (!isStaffSaveEchoEnabled()) {
return null
}
return saveMockDynamicDetail(params)
}
module.exports = {
fetchDetailAdapter,
fetchSchemaRootAdapter,
fetchSceneAdapter,
fetchBrandAdapter,
fetchWeeklyAdapter,
saveEchoAdapter,
getDynamicDailyReportApi,
__setDynamicDailyReportApi
}
const sceneCache = new Map()
const schemaCache = new Map()
function getSchemaCacheKey(reportTemplateId, baseSceneCode) {
return `${reportTemplateId || ''}:${baseSceneCode || ''}`
}
function getCachedScene(merchantId) {
if (!merchantId) return null
return sceneCache.get(merchantId) || null
}
function setCachedScene(merchantId, value) {
if (!merchantId) return
sceneCache.set(merchantId, value)
}
function getCachedSchema(reportTemplateId, baseSceneCode) {
return schemaCache.get(getSchemaCacheKey(reportTemplateId, baseSceneCode)) || null
}
function setCachedSchema(reportTemplateId, baseSceneCode, value) {
schemaCache.set(getSchemaCacheKey(reportTemplateId, baseSceneCode), value)
}
function clearStaffDailyReportCache() {
sceneCache.clear()
schemaCache.clear()
}
module.exports = {
getSchemaCacheKey,
getCachedScene,
setCachedScene,
getCachedSchema,
setCachedSchema,
clearStaffDailyReportCache
}
const { buildPageContext, SCHEMA_OPTIONS_MAP } = require('../fixtures/mock-meta.js')
const { dynamicDailyReportSave } = require('./dynamicDailyReport.js')
const { DEFAULT_REPORT_TEMPLATE_ID } = require('./mockStoreDynamicDetail.js')
import { envIndex } from '~/config.js'
import {
buildDynamicSavePayload,
parseDetailValues,
mapBrandListToBrandIds,
mergeValuesIntoSchema
} from '../form-engine/submit-adapter.js'
import { normalizeSchemaRoot } from '../form-engine/schema-normalizer.js'
import {
resolveBaseSceneCode
} from '../form-engine/page-context.js'
const {
fetchDetailAdapter,
fetchSchemaRootAdapter,
fetchSceneAdapter,
fetchBrandAdapter,
fetchWeeklyAdapter,
saveEchoAdapter
} = require('./storeDailyReportAdapters.js')
const { isStoreMockMode } = require('../config/apiSwitch.js')
const IS_PRODUCTION = envIndex === 3
function normalizeUserInfo(userInfo = {}) {
return {
merchantId: userInfo.merchantId || userInfo.shopMerchantId || '',
yqMerchantId: userInfo.yqMerchantId || userInfo.merchantId || '',
staffUuid: userInfo.uuid || userInfo.staffUuid || '',
baseSceneCode: userInfo.baseSceneCode,
merchantName: userInfo.merchantName || '',
staffName: userInfo.name || userInfo.staffName || ''
}
}
function buildPageContextFromSources({
userInfo = {},
brandIds = [],
detail = {},
baseSceneCode,
sceneList
} = {}) {
const normalized = normalizeUserInfo(userInfo)
return buildPageContext(
{ baseSceneCode },
brandIds,
normalized,
sceneList || []
)
}
function unwrapResponse(result = {}) {
return {
code: result.code,
message: result.message || '请求失败',
data: result.data
}
}
async function fetchMerchantScene({ merchantId, detailBaseSceneCode, hasRecord } = {}) {
if (!merchantId) {
return {
code: 0,
message: 'ok',
baseSceneCode: resolveBaseSceneCode([], detailBaseSceneCode, hasRecord),
sceneList: []
}
}
const result = await fetchSceneAdapter({ merchantId })
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
return {
code: code ?? -1,
message,
baseSceneCode: resolveBaseSceneCode([], detailBaseSceneCode, hasRecord),
sceneList: []
}
}
const sceneList = Array.isArray(data) ? data : []
return {
code: 0,
message: 'ok',
baseSceneCode: resolveBaseSceneCode(sceneList, detailBaseSceneCode, hasRecord),
sceneList
}
}
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)
}
}
async function fetchPageContext(options = {}) {
const {
userInfo = {},
brandIds = [],
detail = {},
merchantScene = {}
} = options
const hasRecord = !!detail.dailyReportRecordId
let baseSceneCode = resolveBaseSceneCode(
merchantScene.sceneList || [],
detail.baseSceneCode,
hasRecord
)
if (baseSceneCode == null) {
baseSceneCode = merchantScene.baseSceneCode ?? null
}
if (baseSceneCode == null) {
return {
code: -1,
message: '获取门店场景失败',
data: null
}
}
return {
code: 0,
message: 'ok',
data: buildPageContextFromSources({
userInfo,
brandIds,
detail,
baseSceneCode,
sceneList: merchantScene.sceneList || []
})
}
}
function buildEmptyDetail(reportTemplateId) {
return {
reportTemplateId: reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: null,
values: {}
}
}
async function fetchReportDetail({
merchantId,
staffUuid,
reportDate,
reportTemplateId
} = {}) {
if (!merchantId || !staffUuid || !reportDate) {
return {
code: 0,
message: 'ok',
data: buildEmptyDetail(reportTemplateId)
}
}
const result = await fetchDetailAdapter({
merchantId,
staffUuid,
reportDate,
reportTemplateId
})
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
return { code: code ?? -1, message, data: null }
}
return normalizeDetailResponse(data, reportTemplateId)
}
function normalizeDetailResponse(detail = {}, reportTemplateId) {
return {
code: 0,
message: 'ok',
data: {
reportTemplateId: detail.reportTemplateId || reportTemplateId || DEFAULT_REPORT_TEMPLATE_ID,
dailyReportRecordId: detail.dailyReportRecordId || null,
baseSceneCode: detail.baseSceneCode,
values: parseDetailValues(detail)
}
}
}
async function fetchSchema({
reportTemplateId,
baseSceneCode,
merchantId,
detailValues = {}
} = {}) {
const result = await fetchSchemaRootAdapter({
reportTemplateId,
baseSceneCode,
merchantId
})
const { code, message, data } = unwrapResponse(result)
if (code != 0) {
if (isStoreMockMode('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 normalizedRoot = normalizeSchemaRoot(data, SCHEMA_OPTIONS_MAP)
const schema = mergeValuesIntoSchema(normalizedRoot, detailValues)
return {
code: 0,
message: 'ok',
data: schema
}
}
async function fetchWeeklyList({
merchantId,
yqMerchantId,
staffUuid,
reportStartDate,
reportEndDate,
timeBean = {}
} = {}) {
if (!merchantId) {
return { code: 0, message: 'ok', data: [] }
}
const result = await fetchWeeklyAdapter({
merchantId,
yqMerchantId,
staffUuid,
reportTypeList: [-1],
reportStartDate,
reportEndDate,
...timeBean
})
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 : []
}
}
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 savePayload = buildDynamicSavePayload({
reportTemplateId,
dailyReportRecordId,
engine,
reportDate
})
if (!IS_PRODUCTION) {
console.log('[storeDailyReport] dynamic.save 提交数据结构', savePayload)
console.log('[storeDailyReport] dynamic.save jsonContent', JSON.parse(savePayload.jsonContent))
}
const pageContext = engine.getPageContext()
const userContext = normalizeUserInfo(wx.$util?.getUserInfo?.() || {})
const result = await dynamicDailyReportSave(savePayload)
const { code, message, data } = unwrapResponse(result)
if (code == 0) {
const savedRecord = saveEchoAdapter({
merchantId: pageContext.merchantId || userContext.merchantId,
staffUuid: userContext.staffUuid,
reportDate,
reportTemplateId,
dailyReportRecordId: data?.dailyReportRecordId || dailyReportRecordId,
fieldDataList: savePayload.fieldDataList,
jsonContent: savePayload.jsonContent
})
return {
code: 0,
message,
data: {
...(data || {}),
dailyReportRecordId: savedRecord?.dailyReportRecordId || data?.dailyReportRecordId || dailyReportRecordId
}
}
}
return {
code: code ?? -1,
message,
data
}
}
module.exports = {
fetchMerchantBrandIds,
fetchMerchantScene,
fetchPageContext,
fetchReportDetail,
fetchSchema,
fetchWeeklyList,
submitForm,
buildPageContextFromSources,
normalizeUserInfo
}
const schemaTemplate = require('../fixtures/schema-store-daily-full.js')
const { MOCK_MERCHANT_BRAND_LIST, MOCK_MERCHANT_SCENE_LIST } = require('../fixtures/mock-meta.js')
const { isStoreMockMode, isStoreSaveEchoEnabled } = require('../config/apiSwitch.js')
const { fetchMockStoreDynamicDetail, saveMockStoreDynamicDetail } = require('./mockStoreDynamicDetail.js')
const {
getCachedScene,
setCachedScene,
getCachedSchema,
setCachedSchema
} = require('./storeDailyReportCache.js')
const {
fetchConfigCenterTemplate,
DYNAMIC_FORM_TEMPLATE_MODULE
} = require('../config/configCenter.js')
let dynamicDailyReportApiModule = null
function getDynamicDailyReportApi() {
if (!dynamicDailyReportApiModule) {
dynamicDailyReportApiModule = require('./dynamicDailyReport.js')
}
return dynamicDailyReportApiModule
}
function __setDynamicDailyReportApi(api) {
dynamicDailyReportApiModule = api
}
async function fetchDetailAdapter(params = {}) {
if (isStoreMockMode('detail')) {
return fetchMockStoreDynamicDetail(params)
}
const { dynamicDailyReportDetail } = getDynamicDailyReportApi()
return dynamicDailyReportDetail(params)
}
async function fetchSchemaRootAdapter(params = {}) {
const { reportTemplateId, baseSceneCode, merchantId } = params
if (isStoreMockMode('schema')) {
return {
code: 0,
message: 'ok',
data: schemaTemplate
}
}
const moduleUrl = DYNAMIC_FORM_TEMPLATE_MODULE.store
const cached = getCachedSchema(moduleUrl, baseSceneCode)
if (cached) {
return cached
}
const result = await fetchConfigCenterTemplate(moduleUrl)
setCachedSchema(moduleUrl, baseSceneCode, result)
return result
}
async function fetchSceneAdapter(params = {}) {
const { merchantId } = params
if (isStoreMockMode('scene')) {
return {
code: 0,
message: 'ok',
data: MOCK_MERCHANT_SCENE_LIST
}
}
const cached = getCachedScene(merchantId)
if (cached) {
return cached
}
const { findAllSceneByMerchantId } = getDynamicDailyReportApi()
const result = await findAllSceneByMerchantId({ merchantId })
setCachedScene(merchantId, result)
return result
}
async function fetchBrandAdapter(params = {}) {
if (isStoreMockMode('brand')) {
return { code: 0, message: 'ok', data: MOCK_MERCHANT_BRAND_LIST }
}
const { staffDailyReportMerchantCarBand } = getDynamicDailyReportApi()
return staffDailyReportMerchantCarBand(params)
}
async function fetchWeeklyAdapter(params = {}) {
if (isStoreMockMode('weekly')) {
return { code: 0, message: 'ok', data: [] }
}
const { staffDailyReportDetailWeeklyList } = getDynamicDailyReportApi()
return staffDailyReportDetailWeeklyList(params)
}
function saveEchoAdapter(params = {}) {
if (!isStoreSaveEchoEnabled()) {
return null
}
return saveMockStoreDynamicDetail(params)
}
module.exports = {
fetchDetailAdapter,
fetchSchemaRootAdapter,
fetchSceneAdapter,
fetchBrandAdapter,
fetchWeeklyAdapter,
saveEchoAdapter,
getDynamicDailyReportApi,
__setDynamicDailyReportApi
}
const sceneCache = new Map()
const schemaCache = new Map()
function getSchemaCacheKey(reportTemplateId, baseSceneCode) {
return `${reportTemplateId || ''}:${baseSceneCode || ''}`
}
function getCachedScene(merchantId) {
if (!merchantId) return null
return sceneCache.get(merchantId) || null
}
function setCachedScene(merchantId, value) {
if (!merchantId) return
sceneCache.set(merchantId, value)
}
function getCachedSchema(reportTemplateId, baseSceneCode) {
return schemaCache.get(getSchemaCacheKey(reportTemplateId, baseSceneCode)) || null
}
function setCachedSchema(reportTemplateId, baseSceneCode, value) {
schemaCache.set(getSchemaCacheKey(reportTemplateId, baseSceneCode), value)
}
function clearStoreDailyReportCache() {
sceneCache.clear()
schemaCache.clear()
}
module.exports = {
getSchemaCacheKey,
getCachedScene,
setCachedScene,
getCachedSchema,
setCachedSchema,
clearStoreDailyReportCache
}
const { buildFixedFieldBlocks } = require('../../form-engine/fixed-field-layout.js')
/** 字段 type → 组件名映射(新增类型在此注册) */
const FIELD_COMPONENT_MAP = {
radio: 'form-field-radio',
numberInput: 'form-field-number',
textarea: 'form-field-textarea',
divider: 'form-field-divider',
select: 'form-field-select',
multipleSelect: 'form-field-multipleSelect',
input: 'form-field-input',
phoneInput: 'form-field-phone',
datetime: 'form-field-datetime',
carBrandSelect: 'form-field-carBrand'
}
Component({ Component({
properties: { properties: {
fixedFields: { fixedFields: {
type: Array, type: Array,
value: [] value: []
}, },
sectionGroups: {
type: Array,
value: []
},
groupFields: { groupFields: {
type: Array, type: Array,
value: [] value: []
...@@ -19,14 +39,67 @@ Component({ ...@@ -19,14 +39,67 @@ Component({
disabled: { disabled: {
type: Boolean, type: Boolean,
value: false value: false
},
requestContext: {
type: Object,
value: {}
},
groupActiveIndex: {
type: Object,
value: {}
},
groupRowVisibleMap: {
type: Object,
value: {}
},
groupRowTotalMap: {
type: Object,
value: {}
}
},
data: {
fieldComponentMap: FIELD_COMPONENT_MAP,
fixedFieldBlocks: []
},
observers: {
fixedFields: function (fixedFields) {
this.setData({
fixedFieldBlocks: buildFixedFieldBlocks(fixedFields || [])
})
}
},
lifetimes: {
attached() {
this.setData({
fixedFieldBlocks: buildFixedFieldBlocks(this.properties.fixedFields || [])
})
} }
}, },
methods: { methods: {
onFieldChange(e) { onFieldChange(e) {
this.triggerEvent('change', e.detail) this.triggerEvent('change', e.detail)
}, },
onFieldBlur(e) { onFieldBlur(e) {
this.triggerEvent('blur', e.detail) this.triggerEvent('blur', e.detail)
},
onGroupAdd(e) {
this.triggerEvent('groupadd', e.detail)
},
onGroupRemove(e) {
this.triggerEvent('groupremove', e.detail)
},
onGroupNav(e) {
this.triggerEvent('groupnav', e.detail)
},
onGroupFieldChange(e) {
this.triggerEvent('groupchange', e.detail)
},
onGroupFieldBlur(e) {
this.triggerEvent('groupblur', e.detail)
} }
} }
}) })
...@@ -3,6 +3,14 @@ ...@@ -3,6 +3,14 @@
"usingComponents": { "usingComponents": {
"form-field-radio": "../form-field-radio/form-field-radio", "form-field-radio": "../form-field-radio/form-field-radio",
"form-field-number": "../form-field-number/form-field-number", "form-field-number": "../form-field-number/form-field-number",
"form-field-textarea": "../form-field-textarea/form-field-textarea" "form-field-textarea": "../form-field-textarea/form-field-textarea",
"form-field-divider": "../form-field-divider/form-field-divider",
"form-field-select": "../form-field-select/form-field-select",
"form-field-multipleSelect": "../form-field-multipleSelect/form-field-multipleSelect",
"form-field-input": "../form-field-input/form-field-input",
"form-field-phone": "../form-field-phone/form-field-phone",
"form-field-datetime": "../form-field-datetime/form-field-datetime",
"form-field-carBrand": "../form-field-carBrand/form-field-carBrand",
"form-group-repeater": "../form-group-repeater/form-group-repeater"
} }
} }
<view class="dynamic-form {{ disabled ? 'is-readonly' : '' }}"> <view class="dynamic-form {{ disabled ? 'is-readonly' : '' }}">
<view class="form-section" wx:if="{{ fixedFields.length }}"> <block wx:for="{{ fixedFieldBlocks }}" wx:key="blockKey" wx:for-item="block">
<block wx:for="{{ fixedFields }}" wx:key="key"> <form-field-divider
wx:if="{{ block.type === 'divider' }}"
field="{{ block.field }}"
/>
<view wx:elif="{{ block.type === 'section' }}" class="form-section">
<block wx:for="{{ block.fields }}" wx:key="key" wx:for-item="item">
<form-field-radio <form-field-radio
wx:if="{{ item.type === 'radio' }}" wx:if="{{ item.type === 'radio' }}"
field="{{ item }}" field="{{ item }}"
...@@ -9,6 +14,58 @@ ...@@ -9,6 +14,58 @@
error="{{ errors[item.key] || '' }}" error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange" bind:change="onFieldChange"
/> />
<form-field-select
wx:elif="{{ item.type === 'select' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
request-context="{{ requestContext }}"
bind:change="onFieldChange"
/>
<form-field-input
wx:elif="{{ item.type === 'input' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
bind:blur="onFieldBlur"
/>
<form-field-phone
wx:elif="{{ item.type === 'phoneInput' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
bind:blur="onFieldBlur"
/>
<form-field-datetime
wx:elif="{{ item.type === 'datetime' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
/>
<form-field-carBrand
wx:elif="{{ item.type === 'carBrandSelect' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
/>
<form-field-multipleSelect
wx:elif="{{ item.type === 'multipleSelect' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
request-context="{{ requestContext }}"
bind:change="onFieldChange"
/>
<form-field-number <form-field-number
wx:elif="{{ item.type === 'numberInput' }}" wx:elif="{{ item.type === 'numberInput' }}"
field="{{ item }}" field="{{ item }}"
...@@ -28,25 +85,113 @@ ...@@ -28,25 +85,113 @@
/> />
</block> </block>
</view> </view>
</block>
<view <view
class="form-group-section" wx:for="{{ sectionGroups }}"
wx:for="{{ groupFields }}"
wx:key="key" wx:key="key"
wx:for-item="group" wx:for-item="section"
class="form-group-section"
> >
<view class="group-title {{ disabled ? 'is-disabled' : '' }}">{{ group.label }}</view> <view class="group-title {{ disabled ? 'is-disabled' : '' }}">{{ section.label }}</view>
<view class="form-section group-fields"> <view class="group-fields form-section">
<block wx:for="{{ group.children[0] }}" wx:key="key" wx:for-item="child"> <block wx:for="{{ section.children }}" wx:key="key" wx:for-item="item">
<form-field-radio
wx:if="{{ item.type === 'radio' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
/>
<form-field-select
wx:elif="{{ item.type === 'select' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
request-context="{{ requestContext }}"
bind:change="onFieldChange"
/>
<form-field-input
wx:elif="{{ item.type === 'input' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
bind:blur="onFieldBlur"
/>
<form-field-phone
wx:elif="{{ item.type === 'phoneInput' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
bind:blur="onFieldBlur"
/>
<form-field-datetime
wx:elif="{{ item.type === 'datetime' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
/>
<form-field-carBrand
wx:elif="{{ item.type === 'carBrandSelect' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
/>
<form-field-multipleSelect
wx:elif="{{ item.type === 'multipleSelect' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
request-context="{{ requestContext }}"
bind:change="onFieldChange"
/>
<form-field-number <form-field-number
field="{{ child }}" wx:elif="{{ item.type === 'numberInput' }}"
value="{{ values[child.key] }}" field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}" disabled="{{ disabled }}"
error="{{ errors[child.key] || '' }}" error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange" bind:change="onFieldChange"
bind:blur="onFieldBlur" bind:blur="onFieldBlur"
/> />
<form-field-textarea
wx:elif="{{ item.type === 'textarea' }}"
field="{{ item }}"
value="{{ values[item.key] }}"
disabled="{{ disabled }}"
error="{{ errors[item.key] || '' }}"
bind:change="onFieldChange"
/>
</block> </block>
</view> </view>
</view> </view>
<form-group-repeater
wx:for="{{ groupFields }}"
wx:key="key"
wx:for-item="group"
group="{{ group }}"
visible-row-fields="{{ groupRowVisibleMap[group.key] }}"
row-total="{{ groupRowTotalMap[group.key] || 0 }}"
active-index="{{ groupActiveIndex[group.key] || 0 }}"
disabled="{{ disabled }}"
errors="{{ errors }}"
request-context="{{ requestContext }}"
bind:add="onGroupAdd"
bind:remove="onGroupRemove"
bind:nav="onGroupNav"
bind:change="onGroupFieldChange"
bind:blur="onGroupFieldBlur"
/>
</view> </view>
const carBrandValueModule = require('../../form-engine/car-brand-value.js')
const normalizeCarBrandValue =
carBrandValueModule.normalizeCarBrandValue ||
carBrandValueModule.default?.normalizeCarBrandValue
Component({
properties: {
field: { type: Object, value: {} },
value: { type: null },
disabled: { type: Boolean, value: false },
error: { type: String, value: '' },
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
},
data: {
displayLabel: ''
},
observers: {
value: function (value) {
if (typeof normalizeCarBrandValue !== 'function') {
this.setData({ displayLabel: '' })
return
}
const normalized = normalizeCarBrandValue(value)
this.setData({
displayLabel: normalized?.displayText || ''
})
}
},
methods: {
onTap() {
if (this.data.disabled) return
const pages = getCurrentPages()
const page = pages[pages.length - 1]
if (!page || typeof page.openCarBrandForField !== 'function') {
return wx.$util?.showToast?.('当前页面不支持车型选择')
}
const field = this.data.field || {}
const rowIndex = this.properties.rowIndex
page.openCarBrandForField({
childKey: field.key,
groupKey: this.properties.groupKey || undefined,
rowIndex: rowIndex >= 0 ? rowIndex : undefined
})
}
}
})
<view class="form-info-row {{ disabled ? 'is-disabled' : '' }}" bindtap="onTap">
<view class="form-info-row__label">
<text>{{ field.label }}</text>
<text class="form-info-row__required" wx:if="{{ field.required }}">*</text>
</view>
<view class="form-info-row__value {{ displayLabel ? '' : 'is-placeholder' }}">
<text>{{ displayLabel || '请选择车型' }}</text>
<text class="form-info-row__arrow">›</text>
</view>
</view>
<view wx:if="{{ error }}" class="form-info-row__error">{{ error }}</view>
@import '../form-field-select/form-field-select.wxss';
function formatDateValue(value, withTime = false) {
if (!value) return ''
const date = value instanceof Date ? value : new Date(value)
if (Number.isNaN(date.getTime())) {
return typeof value === 'string' ? value : ''
}
const y = date.getFullYear()
const m = `${date.getMonth() + 1}`.padStart(2, '0')
const d = `${date.getDate()}`.padStart(2, '0')
if (!withTime) return `${y}-${m}-${d}`
const hh = `${date.getHours()}`.padStart(2, '0')
const mm = `${date.getMinutes()}`.padStart(2, '0')
return `${y}-${m}-${d} ${hh}:${mm}`
}
function endOfToday() {
const now = new Date()
return `${now.getFullYear()}-${`${now.getMonth() + 1}`.padStart(2, '0')}-${`${now.getDate()}`.padStart(2, '0')}`
}
Component({
properties: {
field: { type: Object, value: {} },
value: { type: null },
disabled: { type: Boolean, value: false },
error: { type: String, value: '' },
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
},
data: {
displayLabel: '',
pickerMode: 'date',
pickerValue: '',
endDate: ''
},
observers: {
'field, value': function (field, value) {
const rules = field?.rules || {}
const withTime = rules.format !== 'date'
this.setData({
pickerMode: withTime ? 'datetime' : 'date',
endDate: rules.maxDate === 'today' ? endOfToday() : '',
displayLabel: formatDateValue(value, withTime),
pickerValue: formatDateValue(value, withTime) || endOfToday()
})
}
},
methods: {
onChange(e) {
if (this.data.disabled) return
const nextValue = e.detail.value
this.setData({ displayLabel: nextValue, pickerValue: nextValue })
const detail = { key: this.data.field.key, value: nextValue }
if (this.properties.groupKey) {
detail.groupKey = this.properties.groupKey
const rowIndex = Number(this.properties.rowIndex)
if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
detail.rowIndex = rowIndex
}
}
this.triggerEvent('change', detail)
}
}
})
<view class="form-info-row {{ disabled ? 'is-disabled' : '' }}">
<view class="form-info-row__label">
<text>{{ field.label }}</text>
<text class="form-info-row__required" wx:if="{{ field.required }}">*</text>
</view>
<picker
mode="{{ pickerMode }}"
value="{{ pickerValue }}"
end="{{ endDate }}"
disabled="{{ disabled }}"
bindchange="onChange"
>
<view class="form-info-row__value {{ displayLabel ? '' : 'is-placeholder' }}">
<text>{{ displayLabel || '请选择' }}</text>
<text class="form-info-row__arrow">›</text>
</view>
</picker>
</view>
<view wx:if="{{ error }}" class="form-info-row__error">{{ error }}</view>
@import '../form-field-select/form-field-select.wxss';
Component({
properties: {
field: {
type: Object,
value: {}
}
}
})
<view class="form-divider">
<view class="form-divider__line"></view>
<text class="form-divider__text">{{ field.label }}</text>
<view class="form-divider__line"></view>
</view>
.form-divider {
display: flex;
align-items: center;
gap: 16rpx;
margin: 32rpx 0;
padding: 0 32rpx;
box-sizing: border-box;
}
.form-divider__line {
flex: 1;
height: 0;
border-top: 1rpx dashed #cfd3d9;
background: none;
}
.form-divider__text {
flex-shrink: 0;
font-size: 26rpx;
font-weight: 500;
color: #5a5e66;
line-height: 36rpx;
}
const DEFAULT_OCR_ICON =
'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/ocr_icon.png'
Component({
properties: {
field: {
type: Object,
value: {},
observer: 'observeField'
},
value: {
type: null,
observer: 'syncDisplayValue'
},
disabled: { type: Boolean, value: false },
error: { type: String, value: '' },
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
},
data: {
displayValue: '',
showOcr: false,
scanIcon: ''
},
lifetimes: {
attached() {
const app = typeof getApp === 'function' ? getApp() : null
const imgUrl = app?.globalData?.IMG_URL || wx.$util?.IMG_URL || ''
this.setData({
scanIcon: imgUrl ? `${imgUrl}ocr_icon.png` : DEFAULT_OCR_ICON
})
}
},
methods: {
observeField(field = {}) {
this.setData({
showOcr: field.prefixComponent === 'scan' && !this.data.disabled
})
},
syncDisplayValue(value) {
const displayValue =
value === null || value === undefined ? '' : String(value)
this.setData({ displayValue })
},
onInput(e) {
if (this.data.disabled) return
const rawValue = e.detail.value
const field = this.properties.field || {}
this.setData({ displayValue: rawValue })
const detail = { key: field.key, value: rawValue }
if (this.properties.groupKey) {
detail.groupKey = this.properties.groupKey
const rowIndex = Number(this.properties.rowIndex)
if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
detail.rowIndex = rowIndex
}
}
this.triggerEvent('change', detail)
},
onBlur() {
const field = this.properties.field || {}
this.triggerEvent('blur', {
key: field.key,
value: this.properties.value
})
},
onOcr() {
if (this.data.disabled) return
const pages = getCurrentPages()
const page =
pages.find(p => typeof p.openVinOcrForField === 'function') ||
pages[pages.length - 1]
if (!page || typeof page.openVinOcrForField !== 'function') {
return wx.$util?.showToast?.('当前页面不支持识别')
}
const field = this.properties.field || {}
const groupKey = this.properties.groupKey || undefined
let rowIndex = Number(this.properties.rowIndex)
if (groupKey && (Number.isNaN(rowIndex) || rowIndex < 0)) {
const active = page.data?.groupActiveIndex?.[groupKey]
rowIndex =
active != null && active !== '' && !Number.isNaN(Number(active))
? Number(active)
: 0
}
page.openVinOcrForField({
childKey: field.key,
groupKey,
rowIndex: groupKey ? rowIndex : undefined
})
}
}
})
<view class="form-info-row {{ disabled ? 'is-disabled' : '' }}">
<view class="form-info-row__label">
<text>{{ field.label }}</text>
<text class="form-info-row__required" wx:if="{{ field.required }}">*</text>
</view>
<view class="form-info-row__input-wrap">
<input
value="{{ displayValue }}"
class="form-info-row__input {{ error ? 'is-error' : '' }}"
placeholder="{{ disabled ? '' : '请输入' }}"
placeholder-class="form-info-row__placeholder"
disabled="{{ disabled }}"
maxlength="{{ field.rules.maxLength || 140 }}"
bindinput="onInput"
bindblur="onBlur"
/>
<view wx:if="{{ showOcr }}" class="form-info-row__scan" bindtap="onOcr">
<image
wx:if="{{ scanIcon }}"
class="form-info-row__scan-icon"
src="{{ scanIcon }}"
mode="aspectFit"
/>
</view>
</view>
</view>
<view wx:if="{{ error }}" class="form-info-row__error">{{ error }}</view>
@import '../form-field-radio/form-field-radio.wxss';
.form-info-row__input-wrap {
display: flex;
align-items: center;
flex: 1;
min-width: 0;
justify-content: flex-end;
}
.form-info-row__input {
flex: 1;
min-width: 120rpx;
height: 96rpx;
text-align: right;
font-size: 28rpx;
line-height: 40rpx;
color: #292d33;
}
.form-info-row.is-disabled .form-info-row__input {
color: #5a5e66;
}
.form-info-row__input.is-error {
color: #f24724;
}
/* 与 form-field-select「请选择」占位文案一致 */
.form-info-row__placeholder {
color: #bec1c7;
font-size: 28rpx;
line-height: 40rpx;
}
.form-info-row__scan {
display: flex;
align-items: center;
justify-content: center;
margin-left: 16rpx;
flex-shrink: 0;
width: 48rpx;
height: 48rpx;
}
.form-info-row__scan-icon {
width: 40rpx;
height: 40rpx;
}
const { fetchFieldOptions } = require('../../api/fieldOptionsService.js')
Component({
properties: {
field: {
type: Object,
value: {}
},
value: {
type: null,
value: []
},
disabled: {
type: Boolean,
value: false
},
error: {
type: String,
value: ''
},
requestContext: {
type: Object,
value: {}
},
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
},
data: {
displayLabel: '',
showPicker: false,
pickerOptions: [],
loadingOptions: false
},
observers: {
'field, value': function (field, value) {
this.updateDisplayLabel(field, value)
}
},
methods: {
buildChangeDetail(value) {
const detail = { key: this.data.field.key, value }
if (this.properties.groupKey) {
detail.groupKey = this.properties.groupKey
const rowIndex = Number(this.properties.rowIndex)
if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
detail.rowIndex = rowIndex
}
}
return detail
},
updateDisplayLabel(field, value) {
const selectedValues = Array.isArray(value) ? value.map(String) : value ? [String(value)] : []
const options = this.data.pickerOptions.length
? this.data.pickerOptions
: field?.options || []
const labels = options
.filter(item => selectedValues.includes(String(item.value)))
.map(item => item.label)
this.setData({
displayLabel: labels.length ? labels.join('、') : ''
})
},
getStaticOptions() {
const options = this.data.field?.options || []
return options.length ? options : []
},
buildFetchParams() {
const ctx = this.data.requestContext || {}
const field = this.data.field || {}
return {
optionsKey: field.optionsKey,
merchantId: ctx.merchantId,
staffUuid: ctx.staffUuid,
reportDate: ctx.reportDate,
reportType: ctx.reportType || 'store'
}
},
async loadOptions() {
const field = this.data.field || {}
if (!field.optionsKey) {
const options = this.getStaticOptions()
this.setData({ pickerOptions: options })
return options
}
this.setData({ loadingOptions: true })
try {
const res = await fetchFieldOptions(this.buildFetchParams())
if (res?.code !== 0) {
wx.$util?.showToast?.(res?.message || '获取选项失败')
return []
}
const options = Array.isArray(res.data) ? res.data : []
this.setData({ pickerOptions: options })
return options
} catch (error) {
console.error(error)
wx.$util?.showToast?.('获取选项失败')
return []
} finally {
this.setData({ loadingOptions: false })
}
},
async onTap() {
if (this.data.disabled) return
let options = this.data.pickerOptions
if (this.data.field?.optionsKey) {
options = await this.loadOptions()
} else {
options = this.getStaticOptions()
this.setData({ pickerOptions: options })
}
if (!options.length) {
return wx.$util?.showToast?.('暂无可选项')
}
this.updateDisplayLabel(this.data.field, this.data.value)
this.setData({ showPicker: true })
},
onPickerConfirm(e) {
const value = e.detail?.value || []
this.setData({ showPicker: false })
this.updateDisplayLabel(this.data.field, value)
this.triggerEvent('change', this.buildChangeDetail(value))
},
onPickerCancel() {
this.setData({ showPicker: false })
}
}
})
{
"component": true,
"usingComponents": {
"form-picker-popup": "../form-picker-popup/form-picker-popup"
}
}
<view class="form-info-row {{ disabled ? 'is-disabled' : '' }}" bindtap="onTap">
<view class="form-info-row__label">
<text>{{ field.label }}</text>
<text class="form-info-row__required" wx:if="{{ field.required }}">*</text>
</view>
<view class="form-info-row__value {{ displayLabel ? '' : 'is-placeholder' }}">
<text>{{ displayLabel || '请选择' }}</text>
<text class="form-info-row__arrow">›</text>
</view>
</view>
<view wx:if="{{ error }}" class="form-info-row__error">{{ error }}</view>
<form-picker-popup
show="{{ showPicker }}"
title="{{ field.label }}"
options="{{ pickerOptions }}"
value="{{ value }}"
loading="{{ loadingOptions }}"
bind:confirm="onPickerConfirm"
bind:cancel="onPickerCancel"
/>
...@@ -15,11 +15,24 @@ Component({ ...@@ -15,11 +15,24 @@ Component({
error: { error: {
type: String, type: String,
value: '' value: ''
} },
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
}, },
data: { data: {
displayValue: '' displayValue: '',
unit: ''
},
observers: {
field: function (field) {
const f = field || {}
const unit = f.unit || f.rules?.unit || ''
if (unit !== this.data.unit) {
this.setData({ unit })
}
}
}, },
methods: { methods: {
...@@ -40,10 +53,15 @@ Component({ ...@@ -40,10 +53,15 @@ Component({
} }
} }
this.setData({ displayValue: rawValue }) this.setData({ displayValue: rawValue })
this.triggerEvent('change', { const detail = { key: this.data.field.key, value }
key: this.data.field.key, if (this.properties.groupKey) {
value detail.groupKey = this.properties.groupKey
}) const rowIndex = Number(this.properties.rowIndex)
if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
detail.rowIndex = rowIndex
}
}
this.triggerEvent('change', detail)
}, },
onBlur() { onBlur() {
this.triggerEvent('blur', { this.triggerEvent('blur', {
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
bindinput="onInput" bindinput="onInput"
bindblur="onBlur" bindblur="onBlur"
/> />
<text wx:if="{{ field.rules.unit }}" class="form-info-row__unit">{{ field.rules.unit }}</text> <text wx:if="{{ unit }}" class="form-info-row__unit">{{ unit }}</text>
</view> </view>
</view> </view>
<view wx:if="{{ error }}" class="form-info-row__error">{{ error }}</view> <view wx:if="{{ error }}" class="form-info-row__error">{{ error }}</view>
Component({
properties: {
field: { type: Object, value: {} },
value: {
type: null,
observer: 'syncDisplayValue'
},
disabled: { type: Boolean, value: false },
error: { type: String, value: '' },
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
},
data: { displayValue: '' },
methods: {
syncDisplayValue(value) {
const displayValue =
value === null || value === undefined ? '' : String(value)
this.setData({ displayValue })
},
onInput(e) {
if (this.data.disabled) return
const rawValue = e.detail.value.replace(/\D/g, '').slice(0, 11)
this.setData({ displayValue: rawValue })
const detail = { key: this.data.field.key, value: rawValue }
if (this.properties.groupKey) {
detail.groupKey = this.properties.groupKey
const rowIndex = Number(this.properties.rowIndex)
if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
detail.rowIndex = rowIndex
}
}
this.triggerEvent('change', detail)
},
onBlur() {
this.triggerEvent('blur', {
key: this.data.field.key,
value: this.data.value
})
}
}
})
<view class="form-info-row {{ disabled ? 'is-disabled' : '' }}">
<view class="form-info-row__label">
<text>{{ field.label }}</text>
<text class="form-info-row__required" wx:if="{{ field.required }}">*</text>
</view>
<view class="form-info-row__input-wrap">
<input
value="{{ displayValue }}"
class="form-info-row__input {{ error ? 'is-error' : '' }}"
placeholder="{{ disabled ? '' : '请输入手机号' }}"
placeholder-class="form-info-row__placeholder"
disabled="{{ disabled }}"
type="number"
maxlength="11"
bindinput="onInput"
bindblur="onBlur"
/>
</view>
</view>
<view wx:if="{{ error }}" class="form-info-row__error">{{ error }}</view>
@import '../form-field-input/form-field-input.wxss';
...@@ -14,16 +14,27 @@ Component({ ...@@ -14,16 +14,27 @@ Component({
error: { error: {
type: String, type: String,
value: '' value: ''
} },
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
}, },
methods: { methods: {
buildChangeDetail(value) {
const detail = { key: this.data.field.key, value }
if (this.properties.groupKey) {
detail.groupKey = this.properties.groupKey
const rowIndex = Number(this.properties.rowIndex)
if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
detail.rowIndex = rowIndex
}
}
return detail
},
onSelect(e) { onSelect(e) {
if (this.data.disabled) return if (this.data.disabled) return
const { value } = e.currentTarget.dataset const { value } = e.currentTarget.dataset
this.triggerEvent('change', { this.triggerEvent('change', this.buildChangeDetail(value))
key: this.data.field.key,
value
})
} }
} }
}) })
const { fetchFieldOptions } = require('../../api/fieldOptionsService.js')
Component({
properties: {
field: { type: Object, value: {} },
value: { type: null },
disabled: { type: Boolean, value: false },
error: { type: String, value: '' },
requestContext: { type: Object, value: {} },
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
},
data: {
displayLabel: '',
showPicker: false,
pickerOptions: [],
loadingOptions: false
},
observers: {
'field, value, pickerOptions': function (field, value) {
const options = this.data.pickerOptions.length
? this.data.pickerOptions
: field?.options || []
const matched = options.find(item => String(item.value) === String(value))
this.setData({
displayLabel: matched?.label || (value ? String(value) : '')
})
}
},
methods: {
buildChangeDetail(value) {
const detail = { key: this.data.field.key, value }
if (this.properties.groupKey) {
detail.groupKey = this.properties.groupKey
const rowIndex = Number(this.properties.rowIndex)
if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
detail.rowIndex = rowIndex
}
}
return detail
},
getStaticOptions() {
return this.data.field?.options?.length ? this.data.field.options : []
},
buildFetchParams() {
const ctx = this.data.requestContext || {}
const field = this.data.field || {}
return {
optionsKey: field.optionsKey,
merchantId: ctx.merchantId,
staffUuid: ctx.staffUuid,
reportDate: ctx.reportDate,
reportType: ctx.reportType || 'store'
}
},
async loadOptions() {
const field = this.data.field || {}
if (!field.optionsKey) {
const options = this.getStaticOptions()
this.setData({ pickerOptions: options })
return options
}
this.setData({ loadingOptions: true })
try {
const res = await fetchFieldOptions(this.buildFetchParams())
if (res?.code !== 0) {
wx.$util?.showToast?.(res?.message || '获取选项失败')
return []
}
const options = Array.isArray(res.data) ? res.data : []
this.setData({ pickerOptions: options })
return options
} catch (error) {
console.error(error)
wx.$util?.showToast?.('获取选项失败')
return []
} finally {
this.setData({ loadingOptions: false })
}
},
async onTap() {
if (this.data.disabled) return
let options = this.data.pickerOptions
if (this.data.field?.optionsKey) {
options = await this.loadOptions()
} else {
options = this.getStaticOptions()
this.setData({ pickerOptions: options })
}
if (!options.length) {
return wx.$util?.showToast?.('暂无可选项')
}
if (options.length <= 6 && !this.data.field?.optionsKey) {
wx.showActionSheet({
itemList: options.map(item => item.label),
success: res => {
const selected = options[res.tapIndex]
if (!selected) return
this.triggerEvent('change', this.buildChangeDetail(selected.value))
}
})
return
}
this.setData({ showPicker: true })
},
onPickerConfirm(e) {
const values = e.detail?.value || []
const selected = values[0]
this.setData({ showPicker: false })
this.triggerEvent('change', this.buildChangeDetail(selected))
},
onPickerCancel() {
this.setData({ showPicker: false })
}
}
})
{
"component": true,
"usingComponents": {
"form-picker-popup": "../form-picker-popup/form-picker-popup"
}
}
<view class="form-info-row {{ disabled ? 'is-disabled' : '' }}" bindtap="onTap">
<view class="form-info-row__label">
<text>{{ field.label }}</text>
<text class="form-info-row__required" wx:if="{{ field.required }}">*</text>
</view>
<view class="form-info-row__value {{ displayLabel ? '' : 'is-placeholder' }}">
<text>{{ displayLabel || '请选择' }}</text>
<text class="form-info-row__arrow">›</text>
</view>
</view>
<view wx:if="{{ error }}" class="form-info-row__error">{{ error }}</view>
<form-picker-popup
show="{{ showPicker }}"
title="{{ field.label }}"
options="{{ pickerOptions }}"
value="{{ value }}"
loading="{{ loadingOptions }}"
bind:confirm="onPickerConfirm"
bind:cancel="onPickerCancel"
/>
@import '../form-field-radio/form-field-radio.wxss';
.form-info-row__value {
display: flex;
align-items: center;
justify-content: flex-end;
flex: 1;
font-size: 28rpx;
color: #292d33;
line-height: 40rpx;
}
.form-info-row__value.is-placeholder {
color: #bec1c7;
}
.form-info-row.is-disabled .form-info-row__value {
color: #5a5e66;
}
.form-info-row__arrow {
margin-left: 8rpx;
color: #bec1c7;
font-size: 32rpx;
line-height: 1;
}
...@@ -15,13 +15,15 @@ Component({ ...@@ -15,13 +15,15 @@ Component({
error: { error: {
type: String, type: String,
value: '' value: ''
} },
groupKey: { type: String, value: '' },
rowIndex: { type: Number, value: -1 }
}, },
data: { data: {
currentLength: 0 currentLength: 0
}, },
observers: { observers: {
value(value) { value: function (value) {
this.setData({ this.setData({
currentLength: (value || '').length currentLength: (value || '').length
}) })
...@@ -30,10 +32,15 @@ Component({ ...@@ -30,10 +32,15 @@ Component({
methods: { methods: {
onInput(e) { onInput(e) {
if (this.data.disabled) return if (this.data.disabled) return
this.triggerEvent('change', { const detail = { key: this.data.field.key, value: e.detail.value }
key: this.data.field.key, if (this.properties.groupKey) {
value: e.detail.value detail.groupKey = this.properties.groupKey
}) const rowIndex = Number(this.properties.rowIndex)
if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
detail.rowIndex = rowIndex
}
}
this.triggerEvent('change', detail)
} }
} }
}) })
Component({
options: {
styleIsolation: 'apply-shared'
},
properties: {
group: {
type: Object,
value: {}
},
visibleRowFields: {
type: Array,
value: []
},
rowTotal: {
type: Number,
value: 0
},
activeIndex: {
type: Number,
value: 0
},
disabled: {
type: Boolean,
value: false
},
errors: {
type: Object,
value: {}
},
requestContext: {
type: Object,
value: {}
}
},
methods: {
getActiveRowIndex() {
const total = this.properties.rowTotal || 0
let index = this.properties.activeIndex || 0
if (total > 0 && index >= total) index = total - 1
if (index < 0) index = 0
return index
},
onAdd() {
if (this.properties.disabled) return
this.triggerEvent('add', { groupKey: this.properties.group?.key })
},
onRemove() {
if (this.properties.disabled) return
this.triggerEvent('remove', {
groupKey: this.properties.group?.key,
rowIndex: this.getActiveRowIndex()
})
},
onNav(e) {
const direction = Number(e.currentTarget.dataset.direction) || 0
this.triggerEvent('nav', {
groupKey: this.properties.group?.key,
direction
})
},
resolveRowIndexFromDetail(detail = {}) {
const raw = detail.rowIndex
if (raw !== undefined && raw !== null && raw !== '') {
const index = Number(raw)
if (!Number.isNaN(index) && index >= 0) {
return index
}
}
return this.getActiveRowIndex()
},
onFieldChange(e) {
const childKey = e.detail?.key
const value = e.detail?.value
if (!childKey) return
this.triggerEvent('change', {
groupKey: this.properties.group?.key,
rowIndex: this.resolveRowIndexFromDetail(e.detail),
childKey,
value
})
},
onFieldBlur(e) {
this.triggerEvent('blur', {
...e.detail,
groupKey: this.properties.group?.key,
rowIndex: this.resolveRowIndexFromDetail(e.detail)
})
}
}
})
{
"component": true,
"usingComponents": {
"form-field-radio": "../form-field-radio/form-field-radio",
"form-field-number": "../form-field-number/form-field-number",
"form-field-textarea": "../form-field-textarea/form-field-textarea",
"form-field-select": "../form-field-select/form-field-select",
"form-field-multipleSelect": "../form-field-multipleSelect/form-field-multipleSelect",
"form-field-input": "../form-field-input/form-field-input",
"form-field-phone": "../form-field-phone/form-field-phone",
"form-field-datetime": "../form-field-datetime/form-field-datetime",
"form-field-carBrand": "../form-field-carBrand/form-field-carBrand"
}
}
<view class="group-repeater">
<view class="group-repeater__section">
<view class="group-repeater__header">
<view class="group-repeater__title {{ disabled ? 'is-disabled' : '' }}">{{ group.label }}</view>
<view
wx:if="{{ !disabled }}"
class="group-repeater__add-btn"
bindtap="onAdd"
>
<view class="group-repeater__add-icon"></view>
<text class="group-repeater__add-text">新增</text>
</view>
</view>
<view wx:if="{{ rowTotal > 0 }}" class="group-repeater__nav">
<view
class="group-repeater__nav-btn {{ rowTotal <= 1 || activeIndex <= 0 ? 'is-disabled' : '' }}"
data-direction="-1"
bindtap="onNav"
>
<view class="group-repeater__nav-arrow group-repeater__nav-arrow--left"></view>
</view>
<view class="group-repeater__nav-text">{{ rowTotal ? activeIndex + 1 : 0 }}/{{ rowTotal }}</view>
<view
class="group-repeater__nav-btn {{ !rowTotal || activeIndex + 1 >= rowTotal ? 'is-disabled' : '' }}"
data-direction="1"
bindtap="onNav"
>
<view class="group-repeater__nav-arrow group-repeater__nav-arrow--right"></view>
</view>
</view>
<view wx:if="{{ rowTotal > 0 }}" class="group-repeater__card">
<view class="group-repeater__card-hd">
<text class="group-repeater__row-label">第{{ rowTotal ? activeIndex + 1 : 0 }}行</text>
<view wx:if="{{ !disabled }}" class="group-repeater__delete" bindtap="onRemove">
<image
class="group-repeater__delete-icon"
src="/images/delete.png"
mode="aspectFit"
/>
</view>
</view>
<view class="group-repeater__fields">
<block
wx:for="{{ visibleRowFields }}"
wx:key="_wxRowKey"
wx:for-item="child"
>
<form-field-radio
wx:if="{{ child.type === 'radio' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
bind:change="onFieldChange"
/>
<form-field-select
wx:elif="{{ child.type === 'select' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled || child.disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
request-context="{{ requestContext }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
bind:change="onFieldChange"
/>
<form-field-input
wx:elif="{{ child.type === 'input' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled || child.disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
bind:change="onFieldChange"
bind:blur="onFieldBlur"
/>
<form-field-phone
wx:elif="{{ child.type === 'phoneInput' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled || child.disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
bind:change="onFieldChange"
bind:blur="onFieldBlur"
/>
<form-field-datetime
wx:elif="{{ child.type === 'datetime' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled || child.disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
bind:change="onFieldChange"
/>
<form-field-carBrand
wx:elif="{{ child.type === 'carBrandSelect' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled || child.disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
/>
<form-field-multipleSelect
wx:elif="{{ child.type === 'multipleSelect' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
request-context="{{ requestContext }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
bind:change="onFieldChange"
/>
<form-field-number
wx:elif="{{ child.type === 'numberInput' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
bind:change="onFieldChange"
bind:blur="onFieldBlur"
/>
<form-field-textarea
wx:elif="{{ child.type === 'textarea' }}"
id="{{ child._wxRowKey }}"
field="{{ child }}"
value="{{ child.value }}"
disabled="{{ disabled }}"
error="{{ errors[group.key + '__' + activeIndex + '__' + child.key] || '' }}"
group-key="{{ group.key }}"
row-index="{{ activeIndex }}"
bind:change="onFieldChange"
/>
</block>
</view>
</view>
</view>
<view wx:if="{{ errors[group.key] }}" class="group-repeater__group-error">{{ errors[group.key] }}</view>
</view>
/* Figma 229-8646 / gl_tape list-box + EditForm 浅底子表单 */
.group-repeater {
margin-bottom: 32rpx;
}
/* 整块白卡片:四边统一 32rpx,标题区上下留白一致 */
.group-repeater__section {
background: #fff;
border-radius: 32rpx;
padding: 32rpx;
box-sizing: border-box;
overflow: hidden;
}
.group-repeater__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0;
box-sizing: border-box;
}
.group-repeater__title {
flex: 1;
min-width: 0;
padding-right: 16rpx;
font-size: 32rpx;
font-weight: 600;
color: #292d33;
line-height: 44rpx;
}
.group-repeater__title.is-disabled {
color: #5a5e66;
}
.group-repeater__add-btn {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
height: 64rpx;
padding: 0 32rpx;
background: rgba(44, 102, 247, 0.1);
border-radius: 32rpx;
box-sizing: border-box;
}
.group-repeater__add-icon {
position: relative;
width: 28rpx;
height: 28rpx;
margin-right: 10rpx;
flex-shrink: 0;
}
.group-repeater__add-icon::before,
.group-repeater__add-icon::after {
position: absolute;
content: '';
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #347bff;
border-radius: 4rpx;
}
.group-repeater__add-icon::before {
width: 4rpx;
height: 28rpx;
}
.group-repeater__add-icon::after {
width: 28rpx;
height: 4rpx;
}
.group-repeater__add-text {
font-size: 30rpx;
font-weight: 500;
color: #347bff;
line-height: 1;
}
.group-repeater__nav {
display: flex;
align-items: center;
justify-content: center;
margin-top: 24rpx;
padding: 0;
box-sizing: border-box;
}
.group-repeater__nav-btn {
display: flex;
align-items: center;
justify-content: center;
width: 56rpx;
height: 56rpx;
}
.group-repeater__nav-btn.is-disabled {
opacity: 0.35;
}
.group-repeater__nav-text {
min-width: 88rpx;
margin: 0 32rpx;
font-size: 28rpx;
font-weight: 500;
color: #292d33;
text-align: center;
line-height: 40rpx;
}
.group-repeater__nav-arrow {
width: 16rpx;
height: 16rpx;
border-top: 4rpx solid #347bff;
border-right: 4rpx solid #347bff;
box-sizing: border-box;
}
.group-repeater__nav-arrow--left {
transform: rotate(-135deg);
}
.group-repeater__nav-arrow--right {
transform: rotate(45deg);
}
.group-repeater__nav-btn.is-disabled .group-repeater__nav-arrow {
border-color: #bec1c7;
}
/* 浅蓝子表单容器 */
.group-repeater__card {
margin-top: 24rpx;
padding: 32rpx;
background: rgba(148, 194, 255, 0.2);
border-radius: 24rpx;
box-sizing: border-box;
}
.group-repeater__card-hd {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 24rpx;
}
.group-repeater__row-label {
font-size: 28rpx;
font-weight: 500;
color: #5a5e66;
line-height: 40rpx;
}
.group-repeater__delete {
display: flex;
align-items: center;
justify-content: center;
width: 64rpx;
height: 64rpx;
border-radius: 32rpx;
background: rgba(44, 102, 247, 0.1);
}
.group-repeater__delete-icon {
width: 36rpx;
height: 36rpx;
opacity: 0.55;
}
.group-repeater__fields {
display: flex;
flex-direction: column;
}
/* 每个字段独立白卡片(Figma) */
.group-repeater__field-item {
margin-bottom: 16rpx;
border-radius: 16rpx;
overflow: hidden;
background: #fff;
}
.group-repeater__field-item:last-child {
margin-bottom: 0;
}
.group-repeater__group-error {
padding: 16rpx 0 0;
font-size: 24rpx;
color: #ff4d4f;
line-height: 34rpx;
}
/* 子表单内字段行:独立白块,去掉列表分割线 */
.group-repeater__field-item .form-info-row {
min-height: 96rpx;
border-bottom: none;
border-radius: 16rpx;
background: #fff;
}
.group-repeater__field-item .form-info-row__error {
padding: 0 32rpx 16rpx;
background: #fff;
}
/* 长 label 可换行(如「今日店端实际发券数(其他品牌)」) */
.group-repeater .form-info-row__label {
max-width: 420rpx;
flex-wrap: wrap;
line-height: 40rpx;
}
.group-repeater__field-item .form-textarea-block {
border-bottom: none;
border-radius: 16rpx;
background: #fff;
}
.group-repeater__field-item .form-textarea-block__error {
padding: 0 32rpx 16rpx;
background: #fff;
}
Component({
properties: {
show: {
type: Boolean,
value: false
},
title: {
type: String,
value: '请选择'
},
height: {
type: String,
value: '70%'
},
options: {
type: Array,
value: []
},
value: {
type: Array,
value: []
},
loading: {
type: Boolean,
value: false
}
},
data: {
optionRows: [],
draftValues: []
},
observers: {
show: function (show) {
if (show) {
this.syncOptionRows()
}
},
'options, value': function () {
if (this.properties.show) {
this.syncOptionRows()
}
}
},
methods: {
normalizeValues(value) {
if (!Array.isArray(value)) {
return value == null || value === '' ? [] : [String(value)]
}
return value.map(item => String(item))
},
syncOptionRows() {
const draftValues = this.normalizeValues(this.properties.value)
const optionRows = (this.properties.options || []).map(option => ({
label: option.label,
value: option.value,
active: draftValues.includes(String(option.value))
}))
this.setData({
optionRows,
draftValues
})
},
onToggle(e) {
const index = e.currentTarget.dataset.index
const row = this.data.optionRows[index]
if (!row) return
const draftValues = [...this.data.draftValues]
const valueStr = String(row.value)
const hitIndex = draftValues.indexOf(valueStr)
if (hitIndex === -1) {
draftValues.push(valueStr)
} else {
draftValues.splice(hitIndex, 1)
}
const optionRows = this.data.optionRows.map(item => ({
...item,
active: draftValues.includes(String(item.value))
}))
this.setData({
draftValues,
optionRows
})
},
onConfirm() {
const values = this.data.draftValues.map(value => {
const matched = (this.properties.options || []).find(
item => String(item.value) === String(value)
)
return matched ? matched.value : value
})
this.triggerEvent('confirm', { value: values })
},
onCancel() {
this.triggerEvent('cancel')
}
}
})
{
"component": true,
"usingComponents": {
"popup": "/components/Popup/Popup"
}
}
<popup
show="{{ show }}"
title="{{ title }}"
height="{{ height }}"
bindconfirm="onConfirm"
bindcancel="onCancel"
>
<scroll-view scroll-y class="picker-popup__scroll">
<view wx:if="{{ loading }}" class="picker-popup__loading">加载中...</view>
<block wx:elif="{{ optionRows.length }}">
<view
class="picker-popup__item {{ item.active ? 'is-active' : '' }}"
wx:for="{{ optionRows }}"
wx:key="value"
data-index="{{ index }}"
bindtap="onToggle"
>
<view class="picker-popup__icon">
<image class="picker-popup__icon-img" src="/components/images/choose.png" mode="aspectFit" />
</view>
<view class="picker-popup__label">{{ item.label }}</view>
</view>
</block>
<view wx:else class="picker-popup__empty">暂无可选项</view>
</scroll-view>
</popup>
.picker-popup__scroll {
height: 100%;
}
.picker-popup__loading,
.picker-popup__empty {
display: flex;
align-items: center;
justify-content: center;
height: 200rpx;
font-size: 28rpx;
color: #888;
}
.picker-popup__item {
position: relative;
display: flex;
align-items: center;
box-sizing: border-box;
min-height: 88rpx;
padding: 0 32rpx 0 92rpx;
font-size: 28rpx;
color: #333;
border-bottom: 2rpx solid #ebedf0;
}
.picker-popup__item:last-child {
border-bottom: none;
}
.picker-popup__item.is-active {
color: #347bff;
font-weight: 700;
}
.picker-popup__icon {
display: none;
position: absolute;
left: 20rpx;
top: 50%;
width: 32rpx;
height: 32rpx;
transform: translateY(-50%);
}
.picker-popup__item.is-active .picker-popup__icon {
display: block;
}
.picker-popup__icon-img {
width: 32rpx;
height: 32rpx;
}
.picker-popup__label {
flex: 1;
line-height: 40rpx;
}
/** 每项: 'mock' | 'real' — 联调时只改对应 key */
const STAFF_DAILY_API_SWITCH = {
detail: 'mock',
schema: 'mock',
save: 'real',
saveEcho: 'mock',
scene: 'real',
brand: 'mock',
weekly: 'mock',
fieldOptions: 'mock'
}
const STORE_DAILY_API_SWITCH = {
detail: 'mock',
schema: 'mock',
save: 'real',
saveEcho: 'mock',
scene: 'real',
brand: 'mock',
weekly: 'mock',
fieldOptions: 'mock'
}
const NEGOTIATION_DAILY_API_SWITCH = {
detail: 'mock',
schema: 'mock',
save: 'real',
saveEcho: 'mock',
scene: 'real',
brand: 'mock',
weekly: 'mock',
fieldOptions: 'mock'
}
function isStaffMockMode(key) {
return STAFF_DAILY_API_SWITCH[key] === 'mock'
}
function isStaffSaveEchoEnabled() {
return STAFF_DAILY_API_SWITCH.saveEcho === 'mock'
}
function isStoreMockMode(key) {
return STORE_DAILY_API_SWITCH[key] === 'mock'
}
function isStoreSaveEchoEnabled() {
return STORE_DAILY_API_SWITCH.saveEcho === 'mock'
}
function isNegotiationMockMode(key) {
return NEGOTIATION_DAILY_API_SWITCH[key] === 'mock'
}
function isNegotiationSaveEchoEnabled() {
return NEGOTIATION_DAILY_API_SWITCH.saveEcho === 'mock'
}
module.exports = {
STAFF_DAILY_API_SWITCH,
STORE_DAILY_API_SWITCH,
NEGOTIATION_DAILY_API_SWITCH,
isStaffMockMode,
isStaffSaveEchoEnabled,
isStoreMockMode,
isStoreSaveEchoEnabled,
isNegotiationMockMode,
isNegotiationSaveEchoEnabled,
isMockMode: isStaffMockMode,
isSaveEchoEnabled: isStaffSaveEchoEnabled
}
const CONFIG_CENTER_BASE = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config'
const ENV_MAP = ['develop', 'develop', 'test', 'production', 'beta']
function resolveEnvIndex() {
if (typeof wx === 'undefined') {
return 2
}
try {
const { envIndex } = require('~/config.js')
return envIndex ?? 2
} catch {
return 2
}
}
const DYNAMIC_FORM_TEMPLATE_MODULE = {
staff: 'staff-daily-template',
store: 'store-daily-template',
negotiation: 'negotiation-details-template'
}
const templateCache = new Map()
let requestImpl = null
function getRequestImpl() {
if (requestImpl) {
return requestImpl
}
if (typeof wx !== 'undefined' && wx.request) {
return options =>
new Promise((resolve, reject) => {
wx.request({
...options,
success: resolve,
fail: reject
})
})
}
return null
}
function __setConfigCenterRequest(impl) {
requestImpl = impl
}
function getTemplateCacheKey(moduleUrl) {
const env = ENV_MAP[resolveEnvIndex()] || 'develop'
return `${env}:${moduleUrl}`
}
function normalizeConfigToSchemaRoot(raw) {
if (!raw) {
throw new Error('配置中心返回空数据')
}
let payload = raw
if (typeof raw === 'string') {
payload = JSON.parse(raw)
}
if (Array.isArray(payload)) {
return {
version: '2.0.0',
list: payload
}
}
if (Array.isArray(payload.list)) {
return payload
}
if (payload.content != null) {
return normalizeConfigToSchemaRoot(payload.content)
}
if (payload.data != null) {
return normalizeConfigToSchemaRoot(payload.data)
}
throw new Error('配置中心模版格式无效,缺少 list 字段')
}
function fetchConfigCenterTemplate(moduleUrl, options = {}) {
const { useCache = true } = options
if (!moduleUrl) {
return Promise.reject(new Error('moduleUrl 不能为空'))
}
const cacheKey = getTemplateCacheKey(moduleUrl)
if (useCache && templateCache.has(cacheKey)) {
return Promise.resolve(templateCache.get(cacheKey))
}
const request = getRequestImpl()
if (!request) {
return Promise.reject(new Error('wx.request 不可用'))
}
const env = ENV_MAP[resolveEnvIndex()] || 'develop'
const url = `${CONFIG_CENTER_BASE}?moduleUrl=${encodeURIComponent(moduleUrl)}&env=${encodeURIComponent(env)}`
return request({
url,
method: 'GET',
dataType: 'json',
responseType: 'text'
}).then(response => {
const schemaRoot = normalizeConfigToSchemaRoot(response.data)
const result = {
code: 0,
message: 'ok',
data: schemaRoot
}
if (useCache) {
templateCache.set(cacheKey, result)
}
return result
})
}
function clearConfigCenterTemplateCache() {
templateCache.clear()
}
module.exports = {
CONFIG_CENTER_BASE,
ENV_MAP,
DYNAMIC_FORM_TEMPLATE_MODULE,
normalizeConfigToSchemaRoot,
fetchConfigCenterTemplate,
clearConfigCenterTemplateCache,
__setConfigCenterRequest
}
/** App CarModelList 结构:letter + name/id + childs(子品牌) */
const MOCK_MERCHANT_CAR_BRAND_TREE = [
{
letter: 'A',
id: 3454,
name: '问界',
childs: [
{ id: 34541, name: 'AITO' },
{ id: 34542, name: '问界汽车' }
]
},
{
letter: 'L',
id: 3067,
name: '岚图',
childs: [{ id: 30671, name: '岚图汽车' }]
}
]
module.exports = {
MOCK_MERCHANT_CAR_BRAND_TREE
}
const MOCK_STORE_STAFF_LIST = [
{ label: '张三', value: 'staff-001' },
{ label: '李四', value: 'staff-002' },
{ label: '王五', value: 'staff-003' }
]
const MOCK_4S_STAFF_LIST = [
{ label: '交付专员A', value: '4s-001' },
{ label: '交付专员B', value: '4s-002' },
{ label: '售后专员A', value: '4s-101' },
{ label: '销售顾问A', value: '4s-201' },
{ label: 'SA专员A', value: '4s-301' }
]
const MOCK_ORDER_LIST = [
{ label: '订单-20260501', value: 'order-001' },
{ label: '订单-20260502', value: 'order-002' }
]
const FIELD_OPTIONS_MAP = {
storeStaffList: MOCK_STORE_STAFF_LIST,
'4sStaffList': MOCK_4S_STAFF_LIST,
orderList: MOCK_ORDER_LIST
}
function getMockOptionsByKey(optionsKey = '') {
return FIELD_OPTIONS_MAP[optionsKey] ? [...FIELD_OPTIONS_MAP[optionsKey]] : []
}
module.exports = {
MOCK_STORE_STAFF_LIST,
MOCK_4S_STAFF_LIST,
FIELD_OPTIONS_MAP,
getMockOptionsByKey
}
...@@ -25,14 +25,22 @@ const sceneTypeMap = { ...@@ -25,14 +25,22 @@ const sceneTypeMap = {
const ALL_BRAND_IDS = Object.values(brandIdMap) const ALL_BRAND_IDS = Object.values(brandIdMap)
const MOCK_MERCHANT_BRAND_IDS = [3454, 3503, 3458, 3574, 3502, 3067]
const MOCK_MERCHANT_BRAND_LIST = MOCK_MERCHANT_BRAND_IDS.map(brandId => ({ brandId }))
const MOCK_MERCHANT_SCENE_LIST = [
{ baseSceneCode: 100101 },
{ baseSceneCode: 110101 },
{ baseSceneCode: 110201 },
{ baseSceneCode: 110202 }
]
const BOUTIQUE_PAGE_CONTEXT = { const BOUTIQUE_PAGE_CONTEXT = {
baseSceneCode: 100101, baseSceneCode: 100101
sceneType: 1
} }
const WARRANTY_PAGE_CONTEXT = { const WARRANTY_PAGE_CONTEXT = {
baseSceneCode: 110201, baseSceneCode: 110201
sceneType: 0
} }
const MOCK_SCENE_PRESETS = { const MOCK_SCENE_PRESETS = {
...@@ -45,11 +53,36 @@ const MOCK_SCENE_OPTIONS = [ ...@@ -45,11 +53,36 @@ const MOCK_SCENE_OPTIONS = [
{ key: 'warranty', label: '延保' } { key: 'warranty', label: '延保' }
] ]
function buildPageContext(preset = {}, brandIds = [], userInfo = {}) { const MOCK_STORE_STAFF_LIST = [
{ label: '张三', value: 'staff-001' },
{ label: '李四', value: 'staff-002' },
{ label: '王五', value: 'staff-003' }
]
const MOCK_4S_STAFF_LIST = [
{ label: '交付专员A', value: '4s-001' },
{ label: '交付专员B', value: '4s-002' },
{ label: '售后专员A', value: '4s-101' },
{ label: '销售顾问A', value: '4s-201' },
{ label: 'SA专员A', value: '4s-301' }
]
const MOCK_ORDER_LIST = [
{ label: '订单-20260501', value: 'order-001' },
{ label: '订单-20260502', value: 'order-002' }
]
const SCHEMA_OPTIONS_MAP = {
storeStaffList: MOCK_STORE_STAFF_LIST,
'4sStaffList': MOCK_4S_STAFF_LIST,
orderList: MOCK_ORDER_LIST
}
function buildPageContext(preset = {}, brandIds = [], userInfo = {}, sceneList = []) {
return { return {
baseSceneCode: preset.baseSceneCode, baseSceneCode: preset.baseSceneCode,
sceneType: preset.sceneType,
brandIds: [...brandIds], brandIds: [...brandIds],
sceneList: [...sceneList],
merchantId: userInfo.merchantId || '', merchantId: userInfo.merchantId || '',
merchantName: userInfo.merchantName || '演示门店', merchantName: userInfo.merchantName || '演示门店',
staffName: userInfo.name || '演示员工' staffName: userInfo.name || '演示员工'
...@@ -65,5 +98,11 @@ module.exports = { ...@@ -65,5 +98,11 @@ module.exports = {
WARRANTY_PAGE_CONTEXT, WARRANTY_PAGE_CONTEXT,
MOCK_SCENE_PRESETS, MOCK_SCENE_PRESETS,
MOCK_SCENE_OPTIONS, MOCK_SCENE_OPTIONS,
SCHEMA_OPTIONS_MAP,
MOCK_STORE_STAFF_LIST,
MOCK_4S_STAFF_LIST,
MOCK_MERCHANT_BRAND_IDS,
MOCK_MERCHANT_BRAND_LIST,
MOCK_MERCHANT_SCENE_LIST,
buildPageContext buildPageContext
} }
/**
* 解析门店主营品牌树(对齐 App CarModelList / getMerchantCarBrandList)
*/
export function resolveMerchantCarBrandTree(response) {
if (!response) return []
const payload = response.data !== undefined ? response.data : response
if (!payload) return []
let list = []
if (Array.isArray(payload)) {
if (payload[0]?.carBrandList) {
list = payload[0].carBrandList
} else if (payload[0]?.letter != null || payload[0]?.name != null) {
list = payload
}
} else if (payload.carBrandList) {
list = payload.carBrandList
}
if (!Array.isArray(list)) return []
return list.filter(item => item && (item.name != null || item.id != null))
}
/**
* 四级车型值模型(对齐 packageEquity carInfo / App GLForm)
*/
/** 待 App 联调:schema childKey -> 后端 fieldKey 列表 */
const CAR_BRAND_SUBMIT_KEY_MAP = {
// 示例: 'F3-1-6': ['vehicleBrandId', 'vehicleBrandName', ...]
}
const CAR_BRAND_FIELD_KEYS = [
'vehicleBrandId',
'vehicleBrandName',
'vehicleSubBrandId',
'vehicleSubBrandName',
'vehicleSeriesId',
'vehicleSeriesName',
'vehicleShapeId',
'vehicleShapeName'
]
export function buildDisplayText(carInfo = {}) {
const parts = [
carInfo.vehicleBrandName,
carInfo.vehicleSubBrandName,
carInfo.vehicleSeriesName,
carInfo.vehicleShapeName
].filter(part => part != null && part !== '')
return parts.join('/')
}
export function normalizeCarBrandValue(raw) {
if (raw == null || raw === '') {
return null
}
if (typeof raw === 'string') {
try {
const parsed = JSON.parse(raw)
if (parsed && typeof parsed === 'object') {
return normalizeCarBrandObject(parsed)
}
} catch (error) {
return {
displayText: raw
}
}
return { displayText: raw }
}
if (typeof raw === 'object') {
return normalizeCarBrandObject(raw)
}
return null
}
function normalizeCarBrandObject(obj = {}) {
const next = {}
CAR_BRAND_FIELD_KEYS.forEach(key => {
if (obj[key] != null && obj[key] !== '') {
next[key] = obj[key]
}
})
if (obj.displayText) {
next.displayText = obj.displayText
} else {
next.displayText = buildDisplayText(next)
}
return next
}
export function normalizeCarInfoFromPick(carInfo = {}) {
const next = normalizeCarBrandObject(carInfo)
if (!next) return null
if (!next.displayText) {
next.displayText = buildDisplayText(next)
}
return next
}
export function isCarBrandComplete(value) {
const normalized = normalizeCarBrandValue(value)
if (!normalized) return false
return normalized.vehicleShapeId != null && normalized.vehicleShapeId !== ''
}
/**
* 按 App 映射展开 fieldDataList;无映射时返回单条 JSON 占位
*/
export function flattenCarBrandForSubmit(childKey, value) {
const normalized = normalizeCarBrandValue(value)
if (!normalized) return []
const mapKeys = CAR_BRAND_SUBMIT_KEY_MAP[childKey]
if (Array.isArray(mapKeys) && mapKeys.length) {
return mapKeys
.filter(key => normalized[key] != null && normalized[key] !== '')
.map(fieldKey => ({
fieldKey,
fieldValue: normalized[fieldKey]
}))
}
return [
{
fieldKey: childKey,
fieldValue: JSON.stringify(normalized)
}
]
}
export { CAR_BRAND_SUBMIT_KEY_MAP, CAR_BRAND_FIELD_KEYS }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!