Commit cb968742 by 张立顺

refactor: scope work order user context

1 parent c5acef00
# 精品工单用户上下文接口清单
## 上下文字段与消费者
| 上下文字段 | 原始用户字段 | 精品工单消费者 | 关联接口或提交字段 |
| --- | --- | --- | --- |
| `sceneType` | 顶层 `sceneType` | 最近场景、场景列表、订单类型配置 | `scene.recent.getUserScene`、`scene.config.getUserScene` |
| `phone` | 顶层 `phone`,子用户回退 | 最近场景、场景列表 | 上述两个场景接口的 `phone` |
| `parkMerchantId` | 顶层 `merchantId`,子用户回退 | 合作门店、Router 初始化后的订单 | `query4SRefByYqShopByLogin.merchantId`、`sellerMerchantId` |
| `shopMerchantId` | 顶层/子用户 `shopMerchantId`,默认 4S 门店回退 | 场景列表、门店配置、客户档案、门店筛选 | `getUserScene.merchantId`、`shopMerchantPointConfig.get.merchantId`、客户列表 `merchantId` |
| `operatorId` | `subLoginUser.uuid`,顶层 `uuid` 回退 | 上一单销售顾问、订单初始化 | `order.getLastUser.sellerUserId`、`sellerUserId` |
| `operatorName` | `subLoginUser.name`,顶层 `name` 回退 | 订单初始化 | `sellerName` |
| `parkMerchantName` | 顶层 `merchantName`,子用户回退 | 订单初始化 | `sellerMerchantName` |
## 提交接口
规范化字段先写入 `orderObj`,再由现有提交策略选择接口:
- `dj.api.smartcarlife.order.createWithPay`
- `dj.api.smartcarlife.order.supplementOrder`
- `dj.api.smartcarlife.order.preliminaryOrder`
sessionId 不属于用户上下文,由现有统一请求层附加。
{
"id": "work-order-user-context",
"title": "精品工单用户上下文适配器",
"sourceProject": "dj-car-boutique-work-wechat",
"affectedPaths": [
"tabWorkOrder/pages/createOrder",
"components/CustomerInfo/CustomerInfo.js",
"docs/migrations/work-order-user-context"
],
"interfaces": [
"dj.api.smartcarlife.scene.recent.getUserScene",
"dj.api.smartcarlife.scene.config.getUserScene",
"dj.api.smartcarlife.order.getLastUser",
"dj.api.scenemerchantref.query4SRefByYqShopByLogin",
"dj.api.smartcarlife.shopMerchantPointConfig.get",
"dj.api.smartcarlife.order.search.containPackageGoods",
"dj.api.smartcarlife.order.createWithPay",
"dj.api.smartcarlife.order.supplementOrder",
"dj.api.smartcarlife.order.preliminaryOrder"
],
"tests": [
{
"id": "work-order-user-context-unit",
"file": "tabWorkOrder/pages/createOrder/tests/workOrderUserContext.test.mjs",
"level": "unit",
"expectedBefore": "pass",
"status": "pass"
},
{
"id": "work-order-user-context-page-integration",
"file": "tabWorkOrder/pages/createOrder/tests/createOrderUserContextIntegration.test.mjs",
"level": "integration",
"expectedBefore": "pass",
"status": "pass"
}
],
"baseline": {
"command": "git rev-parse --short HEAD",
"result": "c5acef0"
},
"apiInventory": "docs/migrations/work-order-user-context/api-inventory.md",
"acceptance": "docs/migrations/work-order-user-context/test-acceptance.md",
"verification": {
"commands": [
{
"command": "npm run test:workOrderMigration",
"status": "pass"
},
{
"command": "npm run test:createOrder",
"status": "pass"
},
{
"command": "npm run test:orderLifecycle",
"status": "pass"
},
{
"command": "npm run check:workOrderClosure",
"status": "pass"
}
]
}
}
# 精品工单用户上下文验收映射
## 固定用户期望
| 语义字段 | 期望值 |
| --- | --- |
| `sceneType` | `1` |
| `phone` | `18372203315` |
| `parkMerchantId` | `44211025` |
| `shopMerchantId` | `44210895` |
| `operatorId` | `6825aaebf4f04f6a8a4c3d5a9b26c914` |
| `operatorName` | `0523ymt` |
| `parkMerchantName` | `流程测试园区门店` |
## 行为验收
1. 顶层 `sceneType=1` 生效,不读取 `subLoginUser.sceneType=7` 作为精品工单场景。
2. 合作门店接口使用园区 ID `44211025`。
3. 场景、门店配置和客户档案默认使用门店 ID `44210895`。
4. 操作人优先使用 `subLoginUser.uuid/name`,字段缺失时回退顶层用户。
5. 原始用户为空时返回字段齐全的空上下文,不抛异常。
6. 共享 Router、统一请求 session、其他工作台功能和 OCR 行为不变。
## 验证结果
验证运行时:Node.js `v24.14.0`。
| 验证项 | 结果 |
| --- | --- |
| 精品工单迁移测试 | 33/33 通过 |
| 新增工单测试 | 112/112 通过 |
| 订单生命周期测试 | 69 通过、3 个显式 live 跳过、0 失败 |
| 静态依赖闭包 | 扫描 238 个文件,无缺失依赖、死路由或缺失 API |
# 精品工单用户上下文适配器实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 新增仅供精品工单迁移使用的用户上下文适配器,并让新增工单主链路统一消费规范化的园区、门店、场景和操作人字段。
**Architecture:** 在 `createOrder/services` 中新增无副作用的映射函数和一个集中读取 `wx.$util.getUserInfo()` 的运行时入口。新增工单页面持有 `workOrderUserContext`,专用员工选择服务接收该上下文,共享客户组件只通过页面显式传参获得门店 ID;共享 Router、全局用户工具和请求层保持不变。
**Tech Stack:** 微信小程序 JavaScript、ES modules、Node.js 24、`node:test`、现有 migration readiness 脚本。
## Global Constraints
- 只改本次精品工单迁移闭包,不改目标项目其他原有功能。
- 当前分支直接开发,不创建分支或 worktree。
- 工作台新建入口继续传递 `skipOrderGuards=true`。
- 固定用户与固定 sessionId 模拟保持启用。
- OCR 不新增用户上下文依赖。
- 生产代码必须在对应失败测试验证后再写入。
---
### Task 1: 建立迁移证据和失败测试
**Files:**
- Create: `docs/migrations/work-order-user-context/manifest.json`
- Create: `docs/migrations/work-order-user-context/api-inventory.md`
- Create: `docs/migrations/work-order-user-context/test-acceptance.md`
- Create: `tabWorkOrder/pages/createOrder/tests/workOrderUserContext.test.mjs`
**Interfaces:**
- Consumes: `createWorkOrderUserContext(userInfo)`(测试先定义期望,生产模块尚不存在)
- Produces: 已通过 pre 门禁的迁移清单和可观察的 RED 测试
- [ ] **Step 1: 写映射行为测试**
```js
import { createWorkOrderUserContext } from '../services/workOrderUserContext.js'
test('separates park and shop identities while preferring the sub-login operator', () => {
const context = createWorkOrderUserContext({
merchantId: 44211025,
shopMerchantId: 44210895,
sceneType: 1,
phone: '18372203315',
merchantName: '流程测试园区门店',
uuid: 'top-user',
name: 'top-name',
subLoginUser: { uuid: 'sub-user', name: 'sub-name', sceneType: 7 }
})
assert.deepEqual(context, {
sceneType: 1,
phone: '18372203315',
parkMerchantId: 44211025,
shopMerchantId: 44210895,
operatorId: 'sub-user',
operatorName: 'sub-name',
parkMerchantName: '流程测试园区门店'
})
})
```
- [ ] **Step 2: 运行测试并确认 RED**
Run: `node scripts/run-node-tests.mjs tabWorkOrder/pages/createOrder/tests/workOrderUserContext.test.mjs`
Expected: FAIL,因为 `services/workOrderUserContext.js` 尚不存在。
- [ ] **Step 3: 创建迁移 manifest 和配套文档**
Manifest 记录受影响目录、场景/门店/员工/客户/提交接口、RED 测试状态和最终验证命令;接口清单记录每个上下文字段的接口消费者;验收文档记录固定用户的字面期望值。
- [ ] **Step 4: 执行迁移 pre 门禁**
Run: `npm run check:migration -- --manifest docs/migrations/work-order-user-context/manifest.json --phase pre`
Expected: PASS,允许开始业务代码修改。
### Task 2: 实现纯用户上下文适配器
**Files:**
- Create: `tabWorkOrder/pages/createOrder/services/workOrderUserContext.js`
- Test: `tabWorkOrder/pages/createOrder/tests/workOrderUserContext.test.mjs`
**Interfaces:**
- Consumes: 原始登录用户对象或 `wx.$util.getUserInfo()`
- Produces: `createWorkOrderUserContext(userInfo)`、`getWorkOrderUserContext(readUserInfo?)`
- [ ] **Step 1: 实现最小映射和集中读取函数**
```js
export function createWorkOrderUserContext(userInfo = {}) {
const user = userInfo || {}
const subUser = user.subLoginUser || {}
return {
sceneType: user.sceneType ?? '',
phone: user.phone || subUser.phone || '',
parkMerchantId: user.merchantId || subUser.merchantId || '',
shopMerchantId:
user.shopMerchantId ||
subUser.shopMerchantId ||
user.default4SStoreInfo?.merchantId ||
'',
operatorId: subUser.uuid || user.uuid || '',
operatorName: subUser.name || user.name || '',
parkMerchantName: user.merchantName || subUser.merchantName || ''
}
}
export function getWorkOrderUserContext(
readUserInfo = () => wx.$util.getUserInfo()
) {
return createWorkOrderUserContext(readUserInfo?.() || {})
}
```
- [ ] **Step 2: 运行适配器测试并确认 GREEN**
Run: `node scripts/run-node-tests.mjs tabWorkOrder/pages/createOrder/tests/workOrderUserContext.test.mjs`
Expected: PASS。
- [ ] **Step 3: 补充回退和空值用例**
增加顶层字段缺失时对子用户/default4SStoreInfo 的回退测试,以及空输入输出完整空上下文的测试。
- [ ] **Step 4: 运行完整适配器测试**
Run: `node scripts/run-node-tests.mjs tabWorkOrder/pages/createOrder/tests/workOrderUserContext.test.mjs`
Expected: PASS。
### Task 3: 接入新增工单页面和专用服务
**Files:**
- Modify: `tabWorkOrder/pages/createOrder/createOrder.js`
- Modify: `tabWorkOrder/pages/createOrder/createOrder.wxml`
- Modify: `tabWorkOrder/pages/createOrder/components/merchant-staff-picker/merchant-staff-picker.js`
- Modify: `tabWorkOrder/pages/createOrder/services/merchantStaffSelection.js`
- Test: `tabWorkOrder/pages/createOrder/tests/workOrderUserContext.test.mjs`
**Interfaces:**
- Consumes: `getWorkOrderUserContext()` 和 `createWorkOrderUserContext(userInfo)`
- Produces: 页面数据 `workOrderUserContext`,员工服务上下文参数 `userContext`
- [ ] **Step 1: 写页面消费契约的失败测试**
测试加载真实页面模块时捕获 `Page` 配置,调用 Router `init`,断言页面保存完整上下文,并使用规范化的园区和操作人字段写入提交对象。场景、门店配置和员工服务的字段映射由同一个纯适配器测试覆盖。
- [ ] **Step 2: 运行契约测试并确认 RED**
Run: `node scripts/run-node-tests.mjs tabWorkOrder/pages/createOrder/tests/workOrderUserContext.test.mjs`
Expected: FAIL,因为页面尚未保存或消费 `workOrderUserContext`。
- [ ] **Step 3: 最小接入页面方法**
将页面初始化、最近场景、场景列表、最近销售、Router `init` 和门店配置改为使用上下文。原始 `userInfo` 仅保留给非本次范围的扫码礼券兼容判断。
- [ ] **Step 4: 接入员工选择和客户档案显式门店参数**
将 picker 属性改为 `userContext`,服务使用 `parkMerchantId/shopMerchantId/operatorId`;WXML 的 `customerInfo` 显式传递 `merchantId="{{ workOrderUserContext.shopMerchantId || 0 }}"`。
- [ ] **Step 5: 运行新增工单测试**
Run: `npm run test:createOrder`
Expected: PASS。
### Task 4: 更新迁移状态并完成验证
**Files:**
- Modify: `docs/migrations/work-order-user-context/manifest.json`
- Modify: `docs/migrations/work-order-user-context/test-acceptance.md`
**Interfaces:**
- Consumes: 已实现功能和测试结果
- Produces: post 门禁可复核的最终迁移证据
- [ ] **Step 1: 运行专项与全量迁移验证**
Run:
```powershell
npm run test:workOrderMigration
npm run test:createOrder
npm run test:orderLifecycle
npm run check:workOrderClosure
```
Expected: 全部 PASS。
- [ ] **Step 2: 更新 manifest 状态**
将适配器测试从 `expectedBefore: "fail"` 更新为 `expectedBefore: "pass"`、`status: "pass"`,并登记上面的成功命令。
- [ ] **Step 3: 执行迁移 post 门禁**
Run: `npm run check:migration -- --manifest docs/migrations/work-order-user-context/manifest.json --phase post`
Expected: PASS。
- [ ] **Step 4: 检查差异质量**
Run: `git diff --check`
Expected: 无空白错误;工作区其他既有修改保持不变。
...@@ -37,7 +37,7 @@ Component({ ...@@ -37,7 +37,7 @@ Component({
type: Object, type: Object,
value: {} value: {}
}, },
userInfo: { userContext: {
type: Object, type: Object,
value: {} value: {}
}, },
...@@ -67,7 +67,7 @@ Component({ ...@@ -67,7 +67,7 @@ Component({
* show=true 时加载门店与员工;失败 toast 并通知页面关闭 * show=true 时加载门店与员工;失败 toast 并通知页面关闭
*/ */
async loadPickerData() { async loadPickerData() {
const { mode, orderObj, userInfo, pointsMultiRole, orderCreateType } = const { mode, orderObj, userContext, pointsMultiRole, orderCreateType } =
this.properties this.properties
if (!mode) return if (!mode) return
...@@ -86,7 +86,7 @@ Component({ ...@@ -86,7 +86,7 @@ Component({
try { try {
const result = await loadStaffPicker(mode, { const result = await loadStaffPicker(mode, {
orderObj, orderObj,
userInfo, userContext,
orderCreateType, orderCreateType,
keyWord: '' keyWord: ''
}) })
......
...@@ -60,6 +60,10 @@ import { ...@@ -60,6 +60,10 @@ import {
isAllowedLimitedOrderType isAllowedLimitedOrderType
} from './services/orderMerchantConfig' } from './services/orderMerchantConfig'
import { import {
createWorkOrderUserContext,
getWorkOrderUserContext
} from './services/workOrderUserContext'
import {
normalizeSceneColumns, normalizeSceneColumns,
resolveAutoScene, resolveAutoScene,
toSceneFields toSceneFields
...@@ -191,6 +195,7 @@ Page({ ...@@ -191,6 +195,7 @@ Page({
goodsList: [], goodsList: [],
goodsData: [], goodsData: [],
userInfo: {}, userInfo: {},
workOrderUserContext: null,
requiredList: [], requiredList: [],
isErrorOrder: false, isErrorOrder: false,
isAlreadyExistOrder: false, isAlreadyExistOrder: false,
...@@ -654,23 +659,20 @@ Page({ ...@@ -654,23 +659,20 @@ Page({
wx.$router.go('tabWorkOrder.ocr', { type }) wx.$router.go('tabWorkOrder.ocr', { type })
}, },
async prefillRecentScene() { async prefillRecentScene() {
const freshUserInfo = wx.$util.getUserInfo() || {} const userContext =
const userInfo = this.data.workOrderUserContext || getWorkOrderUserContext()
(this.data.userInfo && Object.keys(this.data.userInfo).length
? this.data.userInfo
: freshUserInfo) || {}
const currentCode = this.data.orderObj?.baseSceneCode || '' const currentCode = this.data.orderObj?.baseSceneCode || ''
if (currentCode) return if (currentCode) return
try { try {
const res = await api.getRecentUserScene({ const res = await api.getRecentUserScene({
sceneType: String(userInfo.sceneType || ''), sceneType: String(userContext.sceneType || ''),
phone: userInfo.phone phone: userContext.phone
}) })
const recent = res?.code == 0 ? res?.data : null const recent = res?.code == 0 ? res?.data : null
const baseSceneCode = recent?.baseSceneCode || '' const baseSceneCode = recent?.baseSceneCode || ''
if (!baseSceneCode) return if (!baseSceneCode) return
this.setData({ this.setData({
userInfo, workOrderUserContext: userContext,
'orderObj.baseSceneCode': baseSceneCode, 'orderObj.baseSceneCode': baseSceneCode,
'orderObj.sceneType': recent?.sceneType 'orderObj.sceneType': recent?.sceneType
}) })
...@@ -727,18 +729,15 @@ Page({ ...@@ -727,18 +729,15 @@ Page({
* 拉取场景列表并自动选中:优先匹配已有 baseSceneCode(含 recent 预填),否则取第一项 * 拉取场景列表并自动选中:优先匹配已有 baseSceneCode(含 recent 预填),否则取第一项
*/ */
async getUserSceneList() { async getUserSceneList() {
const freshUserInfo = wx.$util.getUserInfo() || {} const userContext =
const userInfo = this.data.workOrderUserContext || getWorkOrderUserContext()
(this.data.userInfo && Object.keys(this.data.userInfo).length
? this.data.userInfo
: freshUserInfo) || {}
try { try {
const { orderObj } = this.data const { orderObj } = this.data
const merchantId = const merchantId =
orderObj?.merchantId || userInfo?.shopMerchantId || '' orderObj?.merchantId || userContext.shopMerchantId || ''
const res = await api.getUserScene({ const res = await api.getUserScene({
sceneType: String(userInfo.sceneType || ''), sceneType: String(userContext.sceneType || ''),
phone: userInfo.phone, phone: userContext.phone,
merchantId merchantId
}) })
const list = const list =
...@@ -748,7 +747,7 @@ Page({ ...@@ -748,7 +747,7 @@ Page({
const { scene: currentScene } = resolveAutoScene(currentCode, sceneColumns) const { scene: currentScene } = resolveAutoScene(currentCode, sceneColumns)
const sceneFields = toSceneFields(currentScene) const sceneFields = toSceneFields(currentScene)
const patch = { const patch = {
userInfo, workOrderUserContext: userContext,
sceneColumns sceneColumns
} }
if (currentScene) { if (currentScene) {
...@@ -831,11 +830,12 @@ Page({ ...@@ -831,11 +830,12 @@ Page({
* @see resolveDefaultSelection * @see resolveDefaultSelection
*/ */
async prefillLastSeller() { async prefillLastSeller() {
const { orderObj, userInfo, orderCreateType } = this.data const { orderObj, workOrderUserContext: userContext, orderCreateType } =
this.data
try { try {
const patch = await resolveDefaultSelection({ const patch = await resolveDefaultSelection({
orderObj, orderObj,
userInfo, userContext: userContext || getWorkOrderUserContext(),
orderCreateType orderCreateType
}) })
if (!patch) return if (!patch) return
...@@ -872,7 +872,7 @@ Page({ ...@@ -872,7 +872,7 @@ Page({
* @see clearOrderCouponFields @see resetCouponComponent * @see clearOrderCouponFields @see resetCouponComponent
*/ */
input(e) { input(e) {
let { orderObj, userInfo, goodsList } = this.data let { orderObj, goodsList } = this.data
let { value } = e.detail let { value } = e.detail
let { name } = e.currentTarget.dataset let { name } = e.currentTarget.dataset
let prop = `orderObj.${name}` let prop = `orderObj.${name}`
...@@ -1622,7 +1622,7 @@ Page({ ...@@ -1622,7 +1622,7 @@ Page({
this._setOrderObjInvoked = true this._setOrderObjInvoked = true
let { let {
scene, scene,
userInfo, workOrderUserContext,
isErrorOrder, isErrorOrder,
showTips, showTips,
associateOrderType, associateOrderType,
...@@ -1720,10 +1720,10 @@ Page({ ...@@ -1720,10 +1720,10 @@ Page({
if (scene) { if (scene) {
orderObj.customerCouponId = orderObj.id orderObj.customerCouponId = orderObj.id
orderObj.orderSource = ORDER_SOURCE.COMBINATION orderObj.orderSource = ORDER_SOURCE.COMBINATION
orderObj.sellerMerchantName = userInfo.merchantName orderObj.sellerMerchantName = workOrderUserContext?.parkMerchantName || ''
orderObj.sellerName = userInfo.name orderObj.sellerName = workOrderUserContext?.operatorName || ''
orderObj.sellerMerchantId = userInfo.merchantId orderObj.sellerMerchantId = workOrderUserContext?.parkMerchantId || ''
orderObj.sellerUserId = userInfo.uuid orderObj.sellerUserId = workOrderUserContext?.operatorId || ''
delete orderObj.remark delete orderObj.remark
} else { } else {
orderObj.orderSource = orderObj.orderSource orderObj.orderSource = orderObj.orderSource
...@@ -1857,13 +1857,13 @@ Page({ ...@@ -1857,13 +1857,13 @@ Page({
// console.log(app.globalData.YQorderSetting, 'app.globalData.YQorderSetting?.yqPhoneConfig') // console.log(app.globalData.YQorderSetting, 'app.globalData.YQorderSetting?.yqPhoneConfig')
// console.log(options, 'options') // console.log(options, 'options')
const userInfo = wx.$util.getUserInfo() || {} const workOrderUserContext = getWorkOrderUserContext()
const initialCreateAllGoodsFlag = resolveCreateAllGoodsFlag( const initialCreateAllGoodsFlag = resolveCreateAllGoodsFlag(
undefined, undefined,
userInfo.sceneType workOrderUserContext.sceneType
) )
this.setData({ this.setData({
userInfo workOrderUserContext
}) })
this.applyOrderTypeConfig(initialCreateAllGoodsFlag, { this.applyOrderTypeConfig(initialCreateAllGoodsFlag, {
preserveOrderType: true preserveOrderType: true
...@@ -1951,14 +1951,18 @@ Page({ ...@@ -1951,14 +1951,18 @@ Page({
}, },
init(userInfo) { init(userInfo) {
let { scene, orderObj } = this.data let { scene, orderObj } = this.data
const workOrderUserContext = createWorkOrderUserContext(userInfo)
if (!orderObj.sellerMerchantName) { if (!orderObj.sellerMerchantName) {
orderObj.sellerMerchantName = userInfo.merchantName orderObj.sellerMerchantName = workOrderUserContext.parkMerchantName
orderObj.sellerName = userInfo.name orderObj.sellerName = workOrderUserContext.operatorName
orderObj.sellerMerchantId = userInfo.merchantId orderObj.sellerMerchantId = workOrderUserContext.parkMerchantId
orderObj.sellerUserId = userInfo.uuid orderObj.sellerUserId = workOrderUserContext.operatorId
this.setData({ this.setData({
orderObj orderObj,
workOrderUserContext
}) })
} else {
this.setData({ workOrderUserContext })
} }
if (scene) { if (scene) {
this.applyCouponFromScene(userInfo, scene) this.applyCouponFromScene(userInfo, scene)
...@@ -2849,8 +2853,9 @@ Page({ ...@@ -2849,8 +2853,9 @@ Page({
}, },
getShopMerchantPointConfig() { getShopMerchantPointConfig() {
const { userInfo } = this.data const userContext =
const shopMerchantId = userInfo?.shopMerchantId this.data.workOrderUserContext || getWorkOrderUserContext()
const shopMerchantId = userContext.shopMerchantId
if (!shopMerchantId) return if (!shopMerchantId) return
api.getShopMerchantPointConfig({ merchantId: shopMerchantId }).then(res => { api.getShopMerchantPointConfig({ merchantId: shopMerchantId }).then(res => {
...@@ -2859,7 +2864,7 @@ Page({ ...@@ -2859,7 +2864,7 @@ Page({
const { pointsMultiRole, createAllGoodsFlag: rawFlag } = res.data const { pointsMultiRole, createAllGoodsFlag: rawFlag } = res.data
const createAllGoodsFlag = resolveCreateAllGoodsFlag( const createAllGoodsFlag = resolveCreateAllGoodsFlag(
rawFlag, rawFlag,
userInfo?.sceneType userContext.sceneType
) )
if (pointsMultiRole == 'Y') { if (pointsMultiRole == 'Y') {
......
...@@ -708,7 +708,7 @@ value="{{ orderObj.remark }}" ...@@ -708,7 +708,7 @@ value="{{ orderObj.remark }}"
show="{{ staffPickerBox }}" show="{{ staffPickerBox }}"
mode="{{ staffPickerMode }}" mode="{{ staffPickerMode }}"
orderObj="{{ orderObj }}" orderObj="{{ orderObj }}"
userInfo="{{ userInfo }}" userContext="{{ workOrderUserContext }}"
pointsMultiRole="{{ pointsMultiRole }}" pointsMultiRole="{{ pointsMultiRole }}"
orderCreateType="{{ orderCreateType }}" orderCreateType="{{ orderCreateType }}"
bind:confirm="onStaffPickerConfirm" bind:confirm="onStaffPickerConfirm"
...@@ -776,7 +776,12 @@ value="{{ orderObj.remark }}" ...@@ -776,7 +776,12 @@ value="{{ orderObj.remark }}"
bindcancel="onPagePopupCancel" bindcancel="onPagePopupCancel"
data-popup-key="skuGoodsBox" data-popup-key="skuGoodsBox"
></sku-goods> ></sku-goods>
<customerInfo show="{{ customerInfoBox }}" bindconfirm="chooseCustomerInfo" bindcancel="onCustomerInfoCancel" /> <customerInfo
show="{{ customerInfoBox }}"
merchantId="{{ workOrderUserContext.shopMerchantId || 0 }}"
bindconfirm="chooseCustomerInfo"
bindcancel="onCustomerInfoCancel"
/>
<van-popup show="{{ showSource }}" position="bottom" bind:close="onCloseSource"> <van-popup show="{{ showSource }}" position="bottom" bind:close="onCloseSource">
<van-picker <van-picker
show-toolbar show-toolbar
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
/** /**
* @typedef {Object} PickerContext * @typedef {Object} PickerContext
* @property {Object} [orderObj] * @property {Object} [orderObj]
* @property {Object} [userInfo] * @property {Object} [userContext] 精品工单规范化用户上下文
* @property {string} [orderCreateType] * @property {string} [orderCreateType]
* @property {MerchantItem[]} [merchantList] * @property {MerchantItem[]} [merchantList]
* @property {string} [keyWord] * @property {string} [keyWord]
......
...@@ -54,7 +54,7 @@ const SCENE = 1 ...@@ -54,7 +54,7 @@ const SCENE = 1
* @param {import('./merchantStaffSelection.helpers').PickerContext} context * @param {import('./merchantStaffSelection.helpers').PickerContext} context
*/ */
async function fetchMerchantList(mode, context) { async function fetchMerchantList(mode, context) {
const { orderObj = {}, userInfo = {} } = context const { orderObj = {}, userContext = {} } = context
const config = getModeConfig(mode) const config = getModeConfig(mode)
const isSalesLike = const isSalesLike =
mode === STAFF_MODE.SALES || mode === STAFF_MODE.DELIVERY mode === STAFF_MODE.SALES || mode === STAFF_MODE.DELIVERY
...@@ -62,7 +62,7 @@ async function fetchMerchantList(mode, context) { ...@@ -62,7 +62,7 @@ async function fetchMerchantList(mode, context) {
let data = [] let data = []
if (isSalesLike) { if (isSalesLike) {
const res = await api.getSceneMerchantRefStoreList({ const res = await api.getSceneMerchantRefStoreList({
merchantId: userInfo.merchantId, merchantId: userContext.parkMerchantId,
scene: SCENE, scene: SCENE,
staffUUID: orderObj.sellerUserId staffUUID: orderObj.sellerUserId
}) })
...@@ -71,7 +71,7 @@ async function fetchMerchantList(mode, context) { ...@@ -71,7 +71,7 @@ async function fetchMerchantList(mode, context) {
} }
data = res.data || [] data = res.data || []
if (config.singleSeller) { if (config.singleSeller) {
data = data.filter(item => item.merchantId == userInfo.shopMerchantId) data = data.filter(item => item.merchantId == userContext.shopMerchantId)
} }
} else { } else {
const res = await api.getYQList() const res = await api.getYQList()
...@@ -85,7 +85,7 @@ async function fetchMerchantList(mode, context) { ...@@ -85,7 +85,7 @@ async function fetchMerchantList(mode, context) {
} }
/** 销售顾问:优先订单回显,否则上一单同店,再否则列表首项 */ /** 销售顾问:优先订单回显,否则上一单同店,再否则列表首项 */
async function resolveSalesMerchantSelection(merchants, orderObj, userInfo) { async function resolveSalesMerchantSelection(merchants, orderObj, userContext) {
const config = getModeConfig(STAFF_MODE.SALES) const config = getModeConfig(STAFF_MODE.SALES)
let selectedMerchantId = orderObj[config.merchantIdField] || '' let selectedMerchantId = orderObj[config.merchantIdField] || ''
let selectedMerchantName = orderObj[config.merchantNameField] || '' let selectedMerchantName = orderObj[config.merchantNameField] || ''
...@@ -94,12 +94,11 @@ async function resolveSalesMerchantSelection(merchants, orderObj, userInfo) { ...@@ -94,12 +94,11 @@ async function resolveSalesMerchantSelection(merchants, orderObj, userInfo) {
selectedMerchantId = orderObj.merchantId selectedMerchantId = orderObj.merchantId
selectedMerchantName = orderObj.merchantName selectedMerchantName = orderObj.merchantName
} else if (!orderObj.employeeName) { } else if (!orderObj.employeeName) {
const sellerUserId = const sellerUserId = userContext.operatorId
userInfo?.subLoginUser?.uuid || userInfo?.uuid
if (sellerUserId) { if (sellerUserId) {
const res = await api.getLastUserOrderInfo({ sellerUserId }) const res = await api.getLastUserOrderInfo({ sellerUserId })
const last = res?.data const last = res?.data
if (last && last.merchantId == userInfo?.shopMerchantId) { if (last && last.merchantId == userContext.shopMerchantId) {
selectedMerchantId = last.merchantId selectedMerchantId = last.merchantId
selectedMerchantName = last.merchantName selectedMerchantName = last.merchantName
} }
...@@ -210,7 +209,7 @@ export async function fetchStaff(mode, merchantId, context = {}) { ...@@ -210,7 +209,7 @@ export async function fetchStaff(mode, merchantId, context = {}) {
* @param {import('./merchantStaffSelection.helpers').PickerContext} [context] * @param {import('./merchantStaffSelection.helpers').PickerContext} [context]
*/ */
export async function fetchMerchants(mode, context = {}) { export async function fetchMerchants(mode, context = {}) {
const { orderObj = {}, userInfo = {} } = context const { orderObj = {}, userContext = {} } = context
const merchantsRaw = await fetchMerchantList(mode, context) const merchantsRaw = await fetchMerchantList(mode, context)
let selectedMerchantId = '' let selectedMerchantId = ''
let selectedMerchantName = '' let selectedMerchantName = ''
...@@ -219,7 +218,7 @@ export async function fetchMerchants(mode, context = {}) { ...@@ -219,7 +218,7 @@ export async function fetchMerchants(mode, context = {}) {
const resolved = await resolveSalesMerchantSelection( const resolved = await resolveSalesMerchantSelection(
merchantsRaw, merchantsRaw,
orderObj, orderObj,
userInfo userContext
) )
selectedMerchantId = resolved.selectedMerchantId selectedMerchantId = resolved.selectedMerchantId
selectedMerchantName = resolved.selectedMerchantName selectedMerchantName = resolved.selectedMerchantName
...@@ -272,17 +271,17 @@ export async function loadStaffPicker(mode, context = {}) { ...@@ -272,17 +271,17 @@ export async function loadStaffPicker(mode, context = {}) {
* @returns {Promise<Object|null>} 写入 orderObj 的字段补丁,无预填则 null * @returns {Promise<Object|null>} 写入 orderObj 的字段补丁,无预填则 null
*/ */
export async function resolveDefaultSelection(context = {}) { export async function resolveDefaultSelection(context = {}) {
const { orderObj = {}, userInfo = {}, orderCreateType } = context const { orderObj = {}, userContext = {}, orderCreateType } = context
if (orderObj.userId) return null if (orderObj.userId) return null
if (orderCreateType === 'additionRecordOrder') return null if (orderCreateType === 'additionRecordOrder') return null
const sellerUserId = userInfo?.subLoginUser?.uuid || userInfo?.uuid const sellerUserId = userContext.operatorId
if (!sellerUserId) return null if (!sellerUserId) return null
try { try {
const res = await api.getLastUserOrderInfo({ sellerUserId }) const res = await api.getLastUserOrderInfo({ sellerUserId })
const last = res?.data const last = res?.data
if (last && last.merchantId == userInfo?.shopMerchantId) { if (last && last.merchantId == userContext.shopMerchantId) {
return { return {
merchantId: last.merchantId || '', merchantId: last.merchantId || '',
merchantName: last.merchantName || '', merchantName: last.merchantName || '',
......
/**
* 将原始登录用户转换为精品工单使用的稳定语义字段。
* 本模块不修改原始用户,也不承载接口或页面副作用。
*/
export function createWorkOrderUserContext(userInfo = {}) {
const user = userInfo || {}
const subUser = user.subLoginUser || {}
return {
sceneType: user.sceneType ?? '',
phone: user.phone || subUser.phone || '',
parkMerchantId: user.merchantId || subUser.merchantId || '',
shopMerchantId:
user.shopMerchantId ||
subUser.shopMerchantId ||
user.default4SStoreInfo?.merchantId ||
'',
operatorId: subUser.uuid || user.uuid || '',
operatorName: subUser.name || user.name || '',
parkMerchantName: user.merchantName || subUser.merchantName || ''
}
}
/**
* 精品工单运行时唯一的原始用户读取入口。
* readUserInfo 可注入,便于在不依赖小程序全局对象的环境中验证映射。
*/
export function getWorkOrderUserContext(
readUserInfo = () => wx.$util.getUserInfo()
) {
return createWorkOrderUserContext(readUserInfo?.() || {})
}
import assert from 'node:assert/strict'
import { register } from 'node:module'
import test from 'node:test'
register(
'../../../../tests/work-order-migration/shims/create-order-context-loader.mjs',
import.meta.url
)
test('router init normalizes the operator and merchant fields before submission', async () => {
let pageConfig
globalThis.getApp = () => ({ globalData: {} })
globalThis.Page = config => {
pageConfig = config
}
globalThis.wx = {
getAccountInfoSync: () => ({
miniProgram: {
appId: 'test-app-id',
envVersion: 'develop'
}
}),
getSystemInfoSync: () => ({ platform: 'devtools' }),
getStorageSync: () => '',
$util: {
getUserInfo: () => ({})
}
}
await import(`../createOrder.js?user-context=${Date.now()}`)
const page = {
data: {
scene: '',
orderObj: {},
workOrderUserContext: null
},
setData(patch) {
Object.assign(this.data, patch)
}
}
const rawUser = {
merchantId: 44211025,
merchantName: '流程测试园区门店',
shopMerchantId: 44210895,
sceneType: 1,
phone: '18372203315',
uuid: 'top-user',
name: 'top-name',
subLoginUser: {
uuid: 'sub-user',
name: 'sub-name'
}
}
pageConfig.init.call(page, rawUser)
assert.deepEqual(page.data.workOrderUserContext, {
sceneType: 1,
phone: '18372203315',
parkMerchantId: 44211025,
shopMerchantId: 44210895,
operatorId: 'sub-user',
operatorName: 'sub-name',
parkMerchantName: '流程测试园区门店'
})
assert.deepEqual(page.data.orderObj, {
sellerMerchantName: '流程测试园区门店',
sellerName: 'sub-name',
sellerMerchantId: 44211025,
sellerUserId: 'sub-user'
})
})
import assert from 'node:assert/strict'
import test from 'node:test'
import {
createWorkOrderUserContext,
getWorkOrderUserContext
} from '../services/workOrderUserContext.js'
test('separates park and shop identities while preferring the sub-login operator', () => {
const context = createWorkOrderUserContext({
merchantId: 44211025,
shopMerchantId: 44210895,
sceneType: 1,
phone: '18372203315',
merchantName: '流程测试园区门店',
uuid: 'top-user',
name: 'top-name',
subLoginUser: {
uuid: 'sub-user',
name: 'sub-name',
sceneType: 7
}
})
assert.deepEqual(context, {
sceneType: 1,
phone: '18372203315',
parkMerchantId: 44211025,
shopMerchantId: 44210895,
operatorId: 'sub-user',
operatorName: 'sub-name',
parkMerchantName: '流程测试园区门店'
})
})
test('falls back to sub-login and default shop fields when top-level values are absent', () => {
const context = createWorkOrderUserContext({
subLoginUser: {
merchantId: 9001,
shopMerchantId: '',
phone: '18800001111',
uuid: 'sub-user',
name: 'sub-name',
merchantName: '子账号园区'
},
default4SStoreInfo: {
merchantId: 9002
}
})
assert.deepEqual(context, {
sceneType: '',
phone: '18800001111',
parkMerchantId: 9001,
shopMerchantId: 9002,
operatorId: 'sub-user',
operatorName: 'sub-name',
parkMerchantName: '子账号园区'
})
})
test('returns a complete empty context for a missing user', () => {
assert.deepEqual(createWorkOrderUserContext(null), {
sceneType: '',
phone: '',
parkMerchantId: '',
shopMerchantId: '',
operatorId: '',
operatorName: '',
parkMerchantName: ''
})
})
test('reads the raw user once through the injectable runtime boundary', () => {
let readCount = 0
const context = getWorkOrderUserContext(() => {
readCount += 1
return {
merchantId: 7100,
shopMerchantId: 7200,
sceneType: 1,
phone: '18812345678',
merchantName: '测试园区',
uuid: 'operator-1',
name: '测试员工'
}
})
assert.equal(readCount, 1)
assert.deepEqual(context, {
sceneType: 1,
phone: '18812345678',
parkMerchantId: 7100,
shopMerchantId: 7200,
operatorId: 'operator-1',
operatorName: '测试员工',
parkMerchantName: '测试园区'
})
})
import { existsSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const shimDir = path.dirname(fileURLToPath(import.meta.url))
const projectRoot = path.resolve(shimDir, '../../..')
const mockApiUrl = pathToFileURL(path.join(shimDir, 'mock-api.mjs')).href
const mockUtilUrl = pathToFileURL(path.join(shimDir, 'mock-util.mjs')).href
function resolveExistingModule(candidate) {
const candidates = [candidate, `${candidate}.js`, path.join(candidate, 'index.js')]
return candidates.find(item => existsSync(item))
}
export async function resolve(specifier, context, nextResolve) {
if (specifier === '~/utils/util' || specifier === '~/utils/util.js') {
return { shortCircuit: true, url: mockUtilUrl }
}
if (
specifier === '~/api/api' ||
specifier === '~/api/api.js' ||
(specifier === '../../api' && context.parentURL?.includes('/createOrder/'))
) {
return { shortCircuit: true, url: mockApiUrl }
}
if (specifier.startsWith('./') || specifier.startsWith('../')) {
const parentPath = fileURLToPath(context.parentURL)
const candidate = path.resolve(path.dirname(parentPath), specifier)
const tabWorkOrderApi = path.join(projectRoot, 'tabWorkOrder', 'api')
const projectApi = path.join(projectRoot, 'api', 'api')
if (
candidate === tabWorkOrderApi ||
candidate === `${tabWorkOrderApi}.js` ||
candidate === projectApi ||
candidate === `${projectApi}.js`
) {
return { shortCircuit: true, url: mockApiUrl }
}
}
if (specifier.startsWith('~/')) {
const mapped = resolveExistingModule(
path.join(projectRoot, specifier.slice(2))
)
if (mapped) {
return { shortCircuit: true, url: pathToFileURL(mapped).href }
}
}
if (
(specifier.startsWith('./') || specifier.startsWith('../')) &&
!/\.(?:m?js|json|node)$/.test(specifier)
) {
const parentPath = fileURLToPath(context.parentURL)
const mapped = resolveExistingModule(
path.resolve(path.dirname(parentPath), specifier)
)
if (mapped) {
return { shortCircuit: true, url: pathToFileURL(mapped).href }
}
}
return nextResolve(specifier, context)
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!