Commit bb03848e by 张立顺

配置规则

1 parent f7a61958
---
description: 微信小程序改动通用规范:JSDoc、跨页影响、测试
alwaysApply: true
---
# 微信小程序改动通用规范
每次代码改动须完成以下三项,无需用户重复提醒。
## A. JSDoc 与注释
- 新增/修改的 **export 函数、service 模块、页面编排方法** 必须有 JSDoc(`@param` / `@returns`,说明业务「为什么」)
- 服务层文件头用 `@file` 说明模块职责与边界(不调 setData、不 getPageInstance 等)
- 复杂分支用简短中文行内注释,避免复述代码
- 范例:
- `tabWorkOrder/pages/createOrder/services/merchantStaffSelection.helpers.js`
- `tabWorkOrder/pages/createOrder/services/orderCouponEffects.js`
## B. 跨页影响分析(改前必查)
改动前检索引用,在回复中简要说明影响面:
| 改动类型 | 检索方式 | 典型共享点 |
|----------|----------|------------|
| `components/**` 全局组件 | `rg` 组件名 / `usingComponents` | Merchant-Seles(10+ 页)、Coupon、Popup |
| `api/**`、`store/**` | `rg` 函数名 / API 方法名 | 多分包共用 |
| 页面 `services/**` | 默认仅本页;若上移需全库检索 | — |
**引用 `Merchant-Seles` 的页面**(改全局组件前必须评估):
- tabWorkOrder:defeatOrder、additionRecordOrder、createArchives、premiumUpgrade、updateOrderInfo
- packageEquity:createDeafeatOrder、createDeafeatOrderAi、carQuotation/updateOrderInfo
**原则**:未明确要求跨页改造时,不改全局共享组件及其他引用页;优先在页面内 `services/` + 本地组件演进。
## C. 测试(改后必做)
- **纯函数 / service**:在 `tests/` 下补 `*.test.mjs`(`node:test` + `createRequire`),运行并报告结果
- **createOrder services**:`npm run test:createOrder`
- **全量**:`npm test`
- 无测试的新纯函数应补最小覆盖
- 页面/UI 逻辑无法自动化时,列出手动回归路径
## 改动自检清单
- [ ] 新增/修改函数已补 JSDoc
- [ ] 已检索跨页引用并说明影响面
- [ ] 已运行相关测试(或说明手动回归项)
---
description: createOrder 员工选择与礼券联动领域约定
globs: tabWorkOrder/pages/createOrder/**
alwaysApply: false
---
# createOrder 员工选择 / 礼券联动
## 员工选择架构(禁止回退)
`createOrder` 使用三层结构,**不要**再引入 `Merchant-Seles` 或通过 `wx.$router.getPageInstance()` 改父页面:
| 层 | 路径 | 职责 |
|----|------|------|
| UI | `tabWorkOrder/pages/createOrder/components/merchant-staff-picker/` | 纯展示,事件上报 |
| 服务 | `services/merchantStaffSelection.js` + `.helpers.js` | API、字段映射、「系统」兜底 |
| 编排 | `createOrder.js` | setData、清礼券、重载商品 |
三种模式 `STAFF_MODE`:`sales` / `conversion` / `delivery`,字段映射见 `merchantStaffSelection.helpers.js` 中 `MODE_CONFIG`。
## 「系统」销售顾问兜底
满足**全部**条件时注入 `{ uuid: -1, staffName: '系统' }`:
- `mode === sales`
- 仅 1 个合作门店
- `orderObj` 尚无 `merchantId` / `merchantName`
- `orderCreateType !== 'additionRecordOrder'`
- 员工接口返回空列表
额外规则:
- **搜索中**(`keyWord` 非空)不注入,显示「暂无数据」
- `userId === -1` 时弹窗须回显「系统」(`shouldEchoSystemStaff`)
- `useSystemStaffFallback === true` 时 `openStaffPicker` 自动 `onStaffPickerConfirm`
逻辑变更先改 `merchantStaffSelection.helpers.js`,再改 `.js` 与页面。
## 礼券副作用
礼券清空统一用 `services/orderCouponEffects.js`:
- `clearOrderCouponFields(orderObj)` — 删除 `couponName`、`customerCouponCode`、`customerCouponId`、`merchantCouponId`
- `resetCouponComponent(page)` — 重置 `#coupon` 组件 UI
**必须清空**的场景:
1. 确认变更**销售顾问**(`sales` 模式,`onStaffPickerConfirm`)
2. 车主**手机号**输入变为合法号码(`input`)
3. **补录导航**后(`navigator`)
**不清礼券**:交付专员(`delivery`)变更。
新增清空场景时先扩展 `orderCouponEffects.js`,不要在页面散落 `delete orderObj.couponName`。
## Coupon 组件契约
- 页面挂载:`<coupon id="coupon" merchantId="{{ orderObj.merchantId }}" ... />`
- 手机号失焦:`phoneBlur` → `customerPhoneBlur`
- 选礼券确认:`bindconfirm="chooseCoupon"`
不改全局 `tabWorkOrder/components/Coupon/Coupon.js` 除非用户明确要求跨页改造。
## 改动检查清单
- [ ] 员工逻辑在 service 层,组件无 API / 无 getPageInstance
- [ ] 礼券清空走 `orderCouponEffects`,三处调用保持一致
- [ ] 导出函数与页面编排方法补 JSDoc
- [ ] 纯函数补/更新 `tabWorkOrder/pages/createOrder/tests/*.test.mjs`
...@@ -15,9 +15,10 @@ ...@@ -15,9 +15,10 @@
"prettier-plugin-mp": "^2.5.0" "prettier-plugin-mp": "^2.5.0"
}, },
"scripts": { "scripts": {
"test": "node --test packageDynamicForm/tests/**/*.test.mjs tabIndex/tests/**/*.test.mjs packageEquity/tests/**/*.test.mjs", "test": "node --test packageDynamicForm/tests/**/*.test.mjs tabIndex/tests/**/*.test.mjs packageEquity/tests/**/*.test.mjs tabWorkOrder/pages/createOrder/tests/**/*.test.mjs",
"test:tabIndex": "node --test tabIndex/tests/**/*.test.mjs", "test:tabIndex": "node --test tabIndex/tests/**/*.test.mjs",
"test:equity": "node --test packageEquity/tests/**/*.test.mjs", "test:equity": "node --test packageEquity/tests/**/*.test.mjs",
"test:dynamicForm": "node --test packageDynamicForm/tests/**/*.test.mjs" "test:dynamicForm": "node --test packageDynamicForm/tests/**/*.test.mjs",
"test:createOrder": "node --test tabWorkOrder/pages/createOrder/tests/**/*.test.mjs"
} }
} }
/**
* @file 员工选择弹窗 — 纯展示组件(createOrder 专用)
*
* 不调 API、不读写页面 orderObj;由页面传入列表与选中态,通过事件上报交互。
*
* 事件契约:
* - confirm:{ merchant, staff } 用户点击确认
* - cancel:关闭弹窗
* - merchantchange:{ merchantId, merchant } 切换门店
* - staffchange:{ staffId, staff, index } 切换员工
* - search:{ keyword } 姓名搜索(销售/交付模式)
* - togglemore:展开/收起门店列表
*/
Component({ Component({
properties: { properties: {
/** 是否显示弹窗 */
show: { show: {
type: Boolean, type: Boolean,
value: false value: false
......
...@@ -14,6 +14,8 @@ import { ...@@ -14,6 +14,8 @@ import {
fetchStaff, fetchStaff,
getModeConfig, getModeConfig,
getPickerLabels, getPickerLabels,
getSelectedMerchant,
getSelectedStaff,
hasStaffConflict, hasStaffConflict,
loadStaffPicker, loadStaffPicker,
resolveDefaultSelection, resolveDefaultSelection,
...@@ -21,6 +23,10 @@ import { ...@@ -21,6 +23,10 @@ import {
updateStaffSelection updateStaffSelection
} from './services/merchantStaffSelection' } from './services/merchantStaffSelection'
import { import {
clearOrderCouponFields,
resetCouponComponent
} from './services/orderCouponEffects'
import {
PAY_TYPE, PAY_TYPE,
PAY_TYPE_MAP, PAY_TYPE_MAP,
ORDER_SOURCE, ORDER_SOURCE,
...@@ -397,6 +403,10 @@ Page({ ...@@ -397,6 +403,10 @@ Page({
showTips: false showTips: false
}) })
}, },
/**
* 补录订单导航回调:路由到补录流程后清空销售顾问与礼券。
* @see clearOrderCouponFields
*/
async navigator(e) { async navigator(e) {
let { selectOutTradeNoArr } = e.detail let { selectOutTradeNoArr } = e.detail
let { paymentMethod, isErrorOrder, orderCreateType } = this.data let { paymentMethod, isErrorOrder, orderCreateType } = this.data
...@@ -412,21 +422,12 @@ Page({ ...@@ -412,21 +422,12 @@ Page({
if (isErrorOrder) return if (isErrorOrder) return
let { orderObj } = this.data let { orderObj } = this.data
// 如果是补录 需清订单的空礼券和商品 清空销售顾问 // 补录导航后:清空销售顾问与礼券,避免沿用上一笔无效数据
let deleteName = [ ;['employeeName', 'userId', 'orderSource'].forEach(item => {
'employeeName',
'userId',
'orderSource',
'couponName',
'customerCouponCode',
'customerCouponId'
]
deleteName.map(item => {
if (orderObj[item]) delete orderObj[item] if (orderObj[item]) delete orderObj[item]
}) })
console.log(orderObj.customerCouponId, '被删除了') clearOrderCouponFields(orderObj)
let goodsList = [] let goodsList = []
console.log(this.data.orderObj)
this.setData({ this.setData({
orderObj, orderObj,
goodsList goodsList
...@@ -636,8 +637,14 @@ Page({ ...@@ -636,8 +637,14 @@ Page({
}) })
} }
}, },
// --- 员工选择(merchant-staff-picker 编排)---
/**
* 打开员工/门店选择弹窗,按 mode 拉取列表。
* sales 且 useSystemStaffFallback 时自动确认(对齐旧版 defaultChecked)。
* @param {import('./services/merchantStaffSelection.helpers').StaffMode} mode
*/
async openStaffPicker(mode) { async openStaffPicker(mode) {
const { orderObj, userInfo, pointsMultiRole } = this.data const { orderObj, userInfo, pointsMultiRole, orderCreateType } = this.data
const labels = getPickerLabels(mode, pointsMultiRole) const labels = getPickerLabels(mode, pointsMultiRole)
const config = getModeConfig(mode) const config = getModeConfig(mode)
...@@ -656,35 +663,55 @@ Page({ ...@@ -656,35 +663,55 @@ Page({
const result = await loadStaffPicker(mode, { const result = await loadStaffPicker(mode, {
orderObj, orderObj,
userInfo, userInfo,
orderCreateType,
keyWord: '' keyWord: ''
}) })
wx.$util.hideLoading() wx.$util.hideLoading()
this.setData({ this.setData(
'staffPicker.merchantList': result.merchantList, {
'staffPicker.staffList': result.staffList, 'staffPicker.merchantList': result.merchantList,
'staffPicker.moreMerchant': result.moreMerchant, 'staffPicker.staffList': result.staffList,
'staffPicker.selectedMerchantId': result.selectedMerchantId, 'staffPicker.moreMerchant': result.moreMerchant,
'staffPicker.selectedStaffId': result.selectedStaffId 'staffPicker.selectedMerchantId': result.selectedMerchantId,
}) 'staffPicker.selectedStaffId': result.selectedStaffId
},
() => {
if (
mode === STAFF_MODE.SALES &&
result.useSystemStaffFallback &&
getSelectedStaff(result.staffList)?.uuid == -1
) {
this.onStaffPickerConfirm({
detail: {
merchant: getSelectedMerchant(result.merchantList),
staff: getSelectedStaff(result.staffList)
}
})
}
}
)
} catch (e) { } catch (e) {
wx.$util.hideLoading() wx.$util.hideLoading()
wx.$util.showToast(e?.message || '加载失败') wx.$util.showToast(e?.message || '加载失败')
} }
}, },
/** 关闭员工选择弹窗 */
onStaffPickerCancel() { onStaffPickerCancel() {
this.setData({ this.setData({
'staffPicker.visible': false, 'staffPicker.visible': false,
'staffPicker.keyWord': '' 'staffPicker.keyWord': ''
}) })
}, },
/** 展开/收起超过 3 个的门店列表 */
onStaffPickerToggleMore() { onStaffPickerToggleMore() {
this.setData({ this.setData({
'staffPicker.moreMerchant': !this.data.staffPicker.moreMerchant 'staffPicker.moreMerchant': !this.data.staffPicker.moreMerchant
}) })
}, },
/** 切换门店后重新拉取员工列表 */
async onStaffPickerMerchantChange(e) { async onStaffPickerMerchantChange(e) {
const { merchantId, merchant } = e.detail const { merchantId, merchant } = e.detail
const { staffPicker, orderObj } = this.data const { staffPicker, orderObj, orderCreateType } = this.data
if (!merchantId || staffPicker.selectedMerchantId == merchantId) return if (!merchantId || staffPicker.selectedMerchantId == merchantId) return
const config = getModeConfig(staffPicker.mode) const config = getModeConfig(staffPicker.mode)
...@@ -709,6 +736,8 @@ Page({ ...@@ -709,6 +736,8 @@ Page({
[config.staffIdField]: '', [config.staffIdField]: '',
[config.staffNameField]: '' [config.staffNameField]: ''
}, },
merchantList,
orderCreateType,
keyWord: staffPicker.keyWord keyWord: staffPicker.keyWord
}) })
wx.$util.hideLoading() wx.$util.hideLoading()
...@@ -721,6 +750,7 @@ Page({ ...@@ -721,6 +750,7 @@ Page({
wx.$util.showToast(err?.message || '加载员工失败') wx.$util.showToast(err?.message || '加载员工失败')
} }
}, },
/** 选择员工;sales/delivery 与对端角色互斥时 toast 拦截 */
onStaffPickerStaffChange(e) { onStaffPickerStaffChange(e) {
const { staffId } = e.detail const { staffId } = e.detail
const { staffPicker, orderObj } = this.data const { staffPicker, orderObj } = this.data
...@@ -736,9 +766,10 @@ Page({ ...@@ -736,9 +766,10 @@ Page({
'staffPicker.selectedStaffId': staffId 'staffPicker.selectedStaffId': staffId
}) })
}, },
/** 按姓名搜索员工(仅 searchEnabled 模式) */
async onStaffPickerSearch(e) { async onStaffPickerSearch(e) {
const keyword = e.detail.keyword || '' const keyword = e.detail.keyword || ''
const { staffPicker, orderObj } = this.data const { staffPicker, orderObj, orderCreateType } = this.data
const merchantId = staffPicker.selectedMerchantId const merchantId = staffPicker.selectedMerchantId
if (!merchantId) return if (!merchantId) return
...@@ -746,6 +777,8 @@ Page({ ...@@ -746,6 +777,8 @@ Page({
try { try {
const staffResult = await fetchStaff(staffPicker.mode, merchantId, { const staffResult = await fetchStaff(staffPicker.mode, merchantId, {
orderObj, orderObj,
merchantList: staffPicker.merchantList,
orderCreateType,
keyWord: keyword keyWord: keyword
}) })
this.setData({ this.setData({
...@@ -756,6 +789,10 @@ Page({ ...@@ -756,6 +789,10 @@ Page({
wx.$util.showToast(err?.message || '搜索失败') wx.$util.showToast(err?.message || '搜索失败')
} }
}, },
/**
* 确认员工选择:写入 orderObj。
* sales 模式会清空礼券与商品,并在已选场景时重载商品列表。
*/
onStaffPickerConfirm(e) { onStaffPickerConfirm(e) {
const { merchant, staff } = e.detail const { merchant, staff } = e.detail
const { staffPicker, orderObj, goodsList } = this.data const { staffPicker, orderObj, goodsList } = this.data
...@@ -778,10 +815,7 @@ Page({ ...@@ -778,10 +815,7 @@ Page({
let nextGoodsList = goodsList let nextGoodsList = goodsList
if (mode === STAFF_MODE.SALES) { if (mode === STAFF_MODE.SALES) {
delete nextOrderObj.couponName clearOrderCouponFields(nextOrderObj)
delete nextOrderObj.merchantCouponId
delete nextOrderObj.customerCouponId
delete nextOrderObj.customerCouponCode
nextGoodsList = [] nextGoodsList = []
const hasSceneSelected = const hasSceneSelected =
...@@ -811,6 +845,10 @@ Page({ ...@@ -811,6 +845,10 @@ Page({
'staffPicker.keyWord': '' 'staffPicker.keyWord': ''
}) })
}, },
/**
* onLoad 预填销售顾问:上一单同店或单门店「系统」兜底。
* @see resolveDefaultSelection
*/
async prefillLastSeller() { async prefillLastSeller() {
const { orderObj, userInfo, orderCreateType } = this.data const { orderObj, userInfo, orderCreateType } = this.data
try { try {
...@@ -887,35 +925,29 @@ Page({ ...@@ -887,35 +925,29 @@ Page({
phone: userInfo.phone phone: userInfo.phone
}).catch(() => {}) }).catch(() => {})
}, },
/**
* 表单输入;手机号变为合法号码时清空礼券/商品并重置 Coupon 组件。
* @see clearOrderCouponFields @see resetCouponComponent
*/
input(e) { input(e) {
let { orderObj, userInfo, goodsList } = this.data let { orderObj, userInfo, 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}`
if (name == 'customer.customerPhone' && phoneRex.test(value)) { if (name == 'customer.customerPhone' && phoneRex.test(value)) {
// 如果手机号有变动 需清订单的空礼券和商品 // 手机号变更:礼券与商品可能失效,清空并同步 Coupon 组件 UI
let deleteName = [ if (orderObj.orderSource) delete orderObj.orderSource
'orderSource', clearOrderCouponFields(orderObj)
'couponName',
'customerCouponCode',
'customerCouponId'
]
deleteName.map(item => {
if (orderObj[item]) delete orderObj[item]
})
delete orderObj.merchantCouponId
delete orderObj.isPhoneQuery delete orderObj.isPhoneQuery
console.log('input这里没了')
if (orderObj.selectPayType != 0) { if (orderObj.selectPayType != 0) {
goodsList = [] goodsList = []
} }
// goodsList = []
this.setData({ this.setData({
orderObj, orderObj,
goodsList, goodsList,
returnFun: false returnFun: false
}) })
this.selectComponent('#coupon')?.resetSelection?.() resetCouponComponent(this)
this.setGoodsTotal(goodsList) this.setGoodsTotal(goodsList)
} }
// 车架号字段特殊处理 // 车架号字段特殊处理
...@@ -928,6 +960,9 @@ Page({ ...@@ -928,6 +960,9 @@ Page({
}) })
}, },
/**
* 手机号失焦:通知 #coupon 组件按当前手机号刷新礼券列表
*/
phoneBlur() { phoneBlur() {
this.selectComponent('#coupon')?.customerPhoneBlur && this.selectComponent('#coupon')?.customerPhoneBlur &&
this.selectComponent('#coupon')?.customerPhoneBlur() this.selectComponent('#coupon')?.customerPhoneBlur()
...@@ -1012,6 +1047,10 @@ Page({ ...@@ -1012,6 +1047,10 @@ Page({
car: `${carBrand}|${carType}` car: `${carBrand}|${carType}`
}) })
}, },
/**
* Coupon 组件确认回调(弹窗内选礼券后的展示名)
* @see tabWorkOrder/components/Coupon/Coupon.js
*/
chooseCoupon(e) { chooseCoupon(e) {
console.log(e) console.log(e)
let { name } = e.detail let { name } = e.detail
...@@ -1522,6 +1561,11 @@ Page({ ...@@ -1522,6 +1561,11 @@ Page({
}) })
} }
}, },
/**
* 路由/接口回显写入 orderObj(编辑、再次下单、扫码礼券等)。
* 含礼券字段从 customerCoupon 回显的逻辑。
* @param {Object} options 订单详情或路由入参
*/
setOrderObj(options) { setOrderObj(options) {
let { let {
scene, scene,
...@@ -1606,6 +1650,7 @@ Page({ ...@@ -1606,6 +1650,7 @@ Page({
// debugger // debugger
// 是再次下单的 就删除优惠券字段 不是就赋值 // 是再次下单的 就删除优惠券字段 不是就赋值
// || orderObj.associatedOrderCode // || orderObj.associatedOrderCode
// 编辑/再次下单:从 customerCoupon 回显礼券字段到 orderObj
if (orderObj.customerCoupon && orderObj.constructionFlag != 'Y') { if (orderObj.customerCoupon && orderObj.constructionFlag != 'Y') {
orderObj.couponName = orderObj.customerCoupon.couponName orderObj.couponName = orderObj.customerCoupon.couponName
orderObj.customerCouponCode = orderObj.customerCouponCode =
...@@ -1756,7 +1801,12 @@ Page({ ...@@ -1756,7 +1801,12 @@ Page({
// 添加埋点 // 添加埋点
wx.$track.setTrackData(0, 'submit_order', {}, '', 1) wx.$track.setTrackData(0, 'submit_order', {}, '', 1)
}, },
/** 扫码 / scene 礼券:需在路由策略 setData 写入 scene 之后调用(见 onRoute) */ /**
* 扫码 / scene 礼券入参:解析 scene 并拉取礼券详情写入订单。
* 须在路由策略 setData 写入 scene 之后调用(见 onRoute / onShow)。
* @param {Object} userInfo
* @param {string} sceneRaw 编码后的 scene 参数字符串
*/
applyCouponFromScene(userInfo, sceneRaw) { applyCouponFromScene(userInfo, sceneRaw) {
if (!sceneRaw) return if (!sceneRaw) return
let scene = decodeURIComponent(sceneRaw) let scene = decodeURIComponent(sceneRaw)
......
/**
* @file createOrder 员工选择 — 纯函数层(无 API、无页面副作用)
*
* 架构:merchant-staff-picker(UI)→ merchantStaffSelection.js(API)→ 本文件(映射/兜底)
*
* 三种模式与 orderObj 字段:
* - sales:merchantId/merchantName + userId/employeeName(销售顾问/录单员)
* - conversion:sellerMerchantId/sellerMerchantName + sellerUserId/sellerName(转化人员)
* - delivery:merchantId/merchantName + deliveryUserId/deliveryEmployeeName(交付专员)
*/
/**
* @typedef {'sales'|'conversion'|'delivery'} StaffMode
*/
/**
* @typedef {Object} MerchantItem
* @property {string|number} merchantId
* @property {string} merchantName
* @property {boolean} [active]
*/
/**
* @typedef {Object} StaffItem
* @property {string|number} uuid
* @property {string} staffName
* @property {boolean} [active]
*/
/**
* @typedef {Object} PickerContext
* @property {Object} [orderObj]
* @property {Object} [userInfo]
* @property {string} [orderCreateType]
* @property {MerchantItem[]} [merchantList]
* @property {string} [keyWord]
*/
/** @type {Record<string, StaffMode>} */
export const STAFF_MODE = { export const STAFF_MODE = {
SALES: 'sales', SALES: 'sales',
CONVERSION: 'conversion', CONVERSION: 'conversion',
...@@ -46,10 +85,19 @@ const MODE_CONFIG = { ...@@ -46,10 +85,19 @@ const MODE_CONFIG = {
} }
} }
/**
* 获取模式配置(字段映射、标题、互斥字段等)
* @param {StaffMode} mode
*/
export function getModeConfig(mode) { export function getModeConfig(mode) {
return MODE_CONFIG[mode] || MODE_CONFIG[STAFF_MODE.SALES] return MODE_CONFIG[mode] || MODE_CONFIG[STAFF_MODE.SALES]
} }
/**
* 弹窗展示文案;积分多角色时销售顾问标题带「录单员」
* @param {StaffMode} mode
* @param {string} [pointsMultiRole] 'Y' 表示积分多角色
*/
export function getPickerLabels(mode, pointsMultiRole) { export function getPickerLabels(mode, pointsMultiRole) {
const config = getModeConfig(mode) const config = getModeConfig(mode)
if (mode === STAFF_MODE.SALES && pointsMultiRole === 'Y') { if (mode === STAFF_MODE.SALES && pointsMultiRole === 'Y') {
...@@ -66,6 +114,11 @@ export function getPickerLabels(mode, pointsMultiRole) { ...@@ -66,6 +114,11 @@ export function getPickerLabels(mode, pointsMultiRole) {
} }
} }
/**
* 标记门店选中态;选中项在列表第 4 位及以后时建议展开列表
* @param {MerchantItem[]} list
* @param {string|number} selectedId
*/
export function markMerchantActive(list, selectedId) { export function markMerchantActive(list, selectedId) {
const merchants = (list || []).map(item => ({ const merchants = (list || []).map(item => ({
...item, ...item,
...@@ -77,6 +130,10 @@ export function markMerchantActive(list, selectedId) { ...@@ -77,6 +130,10 @@ export function markMerchantActive(list, selectedId) {
return { merchants, moreMerchant } return { merchants, moreMerchant }
} }
/**
* @param {StaffItem[]} list
* @param {string|number} selectedId
*/
export function markStaffActive(list, selectedId) { export function markStaffActive(list, selectedId) {
return (list || []).map(item => ({ return (list || []).map(item => ({
...item, ...item,
...@@ -84,11 +141,84 @@ export function markStaffActive(list, selectedId) { ...@@ -84,11 +141,84 @@ export function markStaffActive(list, selectedId) {
})) }))
} }
/**
* 员工接口无数据时的兜底选项
* @param {StaffItem[]} staffList
* @returns {StaffItem[]}
*/
function buildSystemStaffFallback(staffList) { function buildSystemStaffFallback(staffList) {
if (staffList.length) return staffList if (staffList.length) return staffList
return [{ uuid: -1, staffName: '系统', active: true }] return [{ uuid: -1, staffName: '系统', active: true }]
} }
/**
* 是否应注入「系统」销售顾问(对齐旧版 defaultChecked 条件)
* 须同时满足:销售模式、仅 1 个门店、订单尚无 merchant、非补录单
* @param {StaffMode} mode
* @param {PickerContext} [context]
*/
export function shouldUseSystemStaffFallback(mode, context = {}) {
const { orderObj = {}, orderCreateType, merchantList = [] } = context
return (
mode === STAFF_MODE.SALES &&
merchantList.length === 1 &&
!orderObj.merchantId &&
!orderObj.merchantName &&
orderCreateType !== 'additionRecordOrder'
)
}
/**
* 订单已选 userId=-1 时,弹窗需回显「系统」
* @param {StaffMode} mode
* @param {Object} [orderObj]
*/
export function shouldEchoSystemStaff(mode, orderObj = {}) {
return mode === STAFF_MODE.SALES && orderObj.userId == -1
}
/**
* 按条件向员工列表注入「系统」;搜索中(有 keyWord)不注入,避免与「暂无数据」冲突
* @param {StaffMode} mode
* @param {StaffItem[]} staffList
* @param {PickerContext} [context]
*/
export function applySystemStaffFallbackIfNeeded(mode, staffList, context = {}) {
const { orderObj = {}, keyWord = '' } = context
if (mode !== STAFF_MODE.SALES || keyWord) return staffList
const needsSystem =
shouldUseSystemStaffFallback(mode, context) ||
shouldEchoSystemStaff(mode, orderObj)
if (!needsSystem) return staffList
if (!staffList.length) {
return buildSystemStaffFallback(staffList)
}
if (
shouldEchoSystemStaff(mode, orderObj) &&
!staffList.some(item => item.uuid == -1)
) {
return [{ uuid: -1, staffName: '系统' }, ...staffList]
}
return staffList
}
/**
* @param {StaffItem} staff
*/
export function isSystemStaff(staff) {
return staff?.uuid == -1 && staff?.staffName === '系统'
}
/**
* 单门店且无员工列表时的默认 orderObj 补丁(含「系统」销售顾问)
* @param {MerchantItem[]} merchantList
* @param {StaffItem[]} staffList
* @returns {Object|null}
*/
export function buildSalesSingleMerchantDefault(merchantList, staffList) { export function buildSalesSingleMerchantDefault(merchantList, staffList) {
if (!merchantList || merchantList.length !== 1) return null if (!merchantList || merchantList.length !== 1) return null
const staff = buildSystemStaffFallback(staffList) const staff = buildSystemStaffFallback(staffList)
...@@ -97,6 +227,12 @@ export function buildSalesSingleMerchantDefault(merchantList, staffList) { ...@@ -97,6 +227,12 @@ export function buildSalesSingleMerchantDefault(merchantList, staffList) {
return buildOrderPatch(STAFF_MODE.SALES, merchant, selectedStaff) return buildOrderPatch(STAFF_MODE.SALES, merchant, selectedStaff)
} }
/**
* 将选中门店/员工写入 orderObj 字段名
* @param {StaffMode} mode
* @param {MerchantItem} merchant
* @param {StaffItem} staff
*/
export function buildOrderPatch(mode, merchant, staff) { export function buildOrderPatch(mode, merchant, staff) {
const config = getModeConfig(mode) const config = getModeConfig(mode)
return { return {
...@@ -107,22 +243,36 @@ export function buildOrderPatch(mode, merchant, staff) { ...@@ -107,22 +243,36 @@ export function buildOrderPatch(mode, merchant, staff) {
} }
} }
/** @param {MerchantItem[]} merchantList */
export function getSelectedMerchant(merchantList) { export function getSelectedMerchant(merchantList) {
return ( return (
(merchantList || []).find(item => item.active) || merchantList?.[0] || null (merchantList || []).find(item => item.active) || merchantList?.[0] || null
) )
} }
/** @param {StaffItem[]} staffList */
export function getSelectedStaff(staffList) { export function getSelectedStaff(staffList) {
return (staffList || []).find(item => item.active) || null return (staffList || []).find(item => item.active) || null
} }
/**
* 销售顾问与交付专员不能为同一人
* @param {StaffMode} mode
* @param {Object} orderObj
* @param {string|number} staffId
*/
export function hasStaffConflict(mode, orderObj, staffId) { export function hasStaffConflict(mode, orderObj, staffId) {
const config = getModeConfig(mode) const config = getModeConfig(mode)
if (!config.conflictField || staffId == null || staffId === '') return false if (!config.conflictField || staffId == null || staffId === '') return false
return orderObj[config.conflictField] == staffId return orderObj[config.conflictField] == staffId
} }
/**
* 从订单回显或默认第一项解析当前门店
* @param {StaffMode} mode
* @param {MerchantItem[]} merchants
* @param {Object} orderObj
*/
export function resolveSelectedMerchant(mode, merchants, orderObj) { export function resolveSelectedMerchant(mode, merchants, orderObj) {
const config = getModeConfig(mode) const config = getModeConfig(mode)
const compareId = orderObj[config.merchantIdField] || '' const compareId = orderObj[config.merchantIdField] || ''
...@@ -144,6 +294,7 @@ export function resolveSelectedMerchant(mode, merchants, orderObj) { ...@@ -144,6 +294,7 @@ export function resolveSelectedMerchant(mode, merchants, orderObj) {
return { selectedMerchantId: '', selectedMerchantName: '' } return { selectedMerchantId: '', selectedMerchantName: '' }
} }
/** @param {MerchantItem[]} merchantList @param {string|number} merchantId */
export function updateMerchantSelection(merchantList, merchantId) { export function updateMerchantSelection(merchantList, merchantId) {
return (merchantList || []).map(item => ({ return (merchantList || []).map(item => ({
...item, ...item,
...@@ -151,6 +302,7 @@ export function updateMerchantSelection(merchantList, merchantId) { ...@@ -151,6 +302,7 @@ export function updateMerchantSelection(merchantList, merchantId) {
})) }))
} }
/** @param {StaffItem[]} staffList @param {string|number} staffId */
export function updateStaffSelection(staffList, staffId) { export function updateStaffSelection(staffList, staffId) {
return (staffList || []).map(item => ({ return (staffList || []).map(item => ({
...item, ...item,
......
/**
* @file createOrder 员工选择 — API 与数据组装层
*
* 职责:请求门店/员工列表、组装 picker 数据、onLoad 预填。
* 边界:不调用 setData、不通过 getPageInstance 改页面;副作用由 createOrder.js 编排。
*
* @see merchantStaffSelection.helpers.js 字段映射与「系统」兜底
*/
import api from '~/api/api' import api from '~/api/api'
import { import {
STAFF_MODE, STAFF_MODE,
applySystemStaffFallbackIfNeeded,
buildOrderPatch, buildOrderPatch,
buildSalesSingleMerchantDefault, buildSalesSingleMerchantDefault,
getModeConfig, getModeConfig,
...@@ -11,12 +21,16 @@ import { ...@@ -11,12 +21,16 @@ import {
markMerchantActive, markMerchantActive,
markStaffActive, markStaffActive,
resolveSelectedMerchant, resolveSelectedMerchant,
shouldEchoSystemStaff,
shouldUseSystemStaffFallback,
isSystemStaff,
updateMerchantSelection, updateMerchantSelection,
updateStaffSelection updateStaffSelection
} from './merchantStaffSelection.helpers' } from './merchantStaffSelection.helpers'
export { export {
STAFF_MODE, STAFF_MODE,
applySystemStaffFallbackIfNeeded,
buildOrderPatch, buildOrderPatch,
buildSalesSingleMerchantDefault, buildSalesSingleMerchantDefault,
getModeConfig, getModeConfig,
...@@ -24,13 +38,21 @@ export { ...@@ -24,13 +38,21 @@ export {
getSelectedMerchant, getSelectedMerchant,
getSelectedStaff, getSelectedStaff,
hasStaffConflict, hasStaffConflict,
isSystemStaff,
resolveSelectedMerchant, resolveSelectedMerchant,
shouldEchoSystemStaff,
shouldUseSystemStaffFallback,
updateMerchantSelection, updateMerchantSelection,
updateStaffSelection updateStaffSelection
} }
/** 精品场景 scene 固定为 1 */
const SCENE = 1 const SCENE = 1
/**
* @param {import('./merchantStaffSelection.helpers').StaffMode} mode
* @param {import('./merchantStaffSelection.helpers').PickerContext} context
*/
async function fetchMerchantList(mode, context) { async function fetchMerchantList(mode, context) {
const { orderObj = {}, userInfo = {} } = context const { orderObj = {}, userInfo = {} } = context
const config = getModeConfig(mode) const config = getModeConfig(mode)
...@@ -62,6 +84,7 @@ async function fetchMerchantList(mode, context) { ...@@ -62,6 +84,7 @@ async function fetchMerchantList(mode, context) {
return data return data
} }
/** 销售顾问:优先订单回显,否则上一单同店,再否则列表首项 */
async function resolveSalesMerchantSelection(merchants, orderObj, userInfo) { async function resolveSalesMerchantSelection(merchants, orderObj, userInfo) {
const config = getModeConfig(STAFF_MODE.SALES) const config = getModeConfig(STAFF_MODE.SALES)
let selectedMerchantId = orderObj[config.merchantIdField] || '' let selectedMerchantId = orderObj[config.merchantIdField] || ''
...@@ -91,14 +114,32 @@ async function resolveSalesMerchantSelection(merchants, orderObj, userInfo) { ...@@ -91,14 +114,32 @@ async function resolveSalesMerchantSelection(merchants, orderObj, userInfo) {
return { selectedMerchantId, selectedMerchantName } return { selectedMerchantId, selectedMerchantName }
} }
/**
* 按门店拉在职员工列表,并在销售模式下处理「系统」兜底
* @param {import('./merchantStaffSelection.helpers').StaffMode} mode
* @param {string|number} merchantId
* @param {import('./merchantStaffSelection.helpers').PickerContext} [context]
* @returns {Promise<{
* staffList: import('./merchantStaffSelection.helpers').StaffItem[],
* selectedStaffId: string|number,
* selectedStaffName: string,
* useSystemStaffFallback: boolean
* }>}
* useSystemStaffFallback 为 true 时,页面应自动 confirm(对齐旧版 defaultChecked)
*/
export async function fetchStaff(mode, merchantId, context = {}) { export async function fetchStaff(mode, merchantId, context = {}) {
const { orderObj = {}, keyWord = '' } = context const { orderObj = {}, keyWord = '', merchantList = [] } = 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
if (!merchantId) { if (!merchantId) {
return { staffList: [], selectedStaffId: '', selectedStaffName: '' } return {
staffList: [],
selectedStaffId: '',
selectedStaffName: '',
useSystemStaffFallback: false
}
} }
const res = await api.getEmployeeList({ const res = await api.getEmployeeList({
...@@ -112,28 +153,62 @@ export async function fetchStaff(mode, merchantId, context = {}) { ...@@ -112,28 +153,62 @@ export async function fetchStaff(mode, merchantId, context = {}) {
} }
const staffListRaw = res.data || [] const staffListRaw = res.data || []
const fallbackContext = { ...context, merchantList, orderObj, keyWord }
const staffListAfterFallback = applySystemStaffFallbackIfNeeded(
mode,
staffListRaw,
fallbackContext
)
const useSystemStaffFallback =
mode === STAFF_MODE.SALES &&
!keyWord &&
staffListRaw.length === 0 &&
staffListAfterFallback.length > 0 &&
shouldUseSystemStaffFallback(mode, fallbackContext)
let selectedStaffId = orderObj[config.staffIdField] || '' let selectedStaffId = orderObj[config.staffIdField] || ''
let selectedStaffName = orderObj[config.staffNameField] || '' let selectedStaffName = orderObj[config.staffNameField] || ''
const compareMerchantId = orderObj[config.merchantIdField] const compareMerchantId = orderObj[config.merchantIdField]
if (compareMerchantId && compareMerchantId == merchantId && selectedStaffId) { if (
const matched = staffListRaw.find(item => item.uuid == selectedStaffId) shouldEchoSystemStaff(mode, orderObj) &&
staffListAfterFallback.some(item => item.uuid == -1)
) {
selectedStaffId = -1
selectedStaffName = '系统'
} else if (
compareMerchantId &&
compareMerchantId == merchantId &&
selectedStaffId !== '' &&
selectedStaffId != null
) {
const matched = staffListAfterFallback.find(
item => item.uuid == selectedStaffId
)
if (matched) { if (matched) {
selectedStaffId = matched.uuid selectedStaffId = matched.uuid
selectedStaffName = matched.staffName selectedStaffName = matched.staffName
} }
} else if (staffListRaw[0]) { } else if (useSystemStaffFallback) {
selectedStaffId = staffListRaw[0].uuid selectedStaffId = -1
selectedStaffName = staffListRaw[0].staffName selectedStaffName = '系统'
} else if (staffListAfterFallback[0]) {
selectedStaffId = staffListAfterFallback[0].uuid
selectedStaffName = staffListAfterFallback[0].staffName
} }
return { return {
staffList: markStaffActive(staffListRaw, selectedStaffId), staffList: markStaffActive(staffListAfterFallback, selectedStaffId),
selectedStaffId, selectedStaffId,
selectedStaffName selectedStaffName,
useSystemStaffFallback
} }
} }
/**
* @param {import('./merchantStaffSelection.helpers').StaffMode} mode
* @param {import('./merchantStaffSelection.helpers').PickerContext} [context]
*/
export async function fetchMerchants(mode, context = {}) { export async function fetchMerchants(mode, context = {}) {
const { orderObj = {}, userInfo = {} } = context const { orderObj = {}, userInfo = {} } = context
const merchantsRaw = await fetchMerchantList(mode, context) const merchantsRaw = await fetchMerchantList(mode, context)
...@@ -167,10 +242,16 @@ export async function fetchMerchants(mode, context = {}) { ...@@ -167,10 +242,16 @@ export async function fetchMerchants(mode, context = {}) {
} }
} }
/**
* 打开员工选择弹窗时一次性加载门店 + 员工
* @param {import('./merchantStaffSelection.helpers').StaffMode} mode
* @param {import('./merchantStaffSelection.helpers').PickerContext} [context]
*/
export async function loadStaffPicker(mode, context = {}) { export async function loadStaffPicker(mode, context = {}) {
const merchantResult = await fetchMerchants(mode, context) const merchantResult = await fetchMerchants(mode, context)
const staffResult = await fetchStaff(mode, merchantResult.selectedMerchantId, { const staffResult = await fetchStaff(mode, merchantResult.selectedMerchantId, {
...context, ...context,
merchantList: merchantResult.merchantList,
orderObj: { orderObj: {
...context.orderObj, ...context.orderObj,
[getModeConfig(mode).merchantIdField]: merchantResult.selectedMerchantId, [getModeConfig(mode).merchantIdField]: merchantResult.selectedMerchantId,
...@@ -185,6 +266,11 @@ export async function loadStaffPicker(mode, context = {}) { ...@@ -185,6 +266,11 @@ export async function loadStaffPicker(mode, context = {}) {
} }
} }
/**
* onLoad 预填销售顾问:上一单同店优先,否则单门店「系统」兜底
* @param {import('./merchantStaffSelection.helpers').PickerContext} [context]
* @returns {Promise<Object|null>} 写入 orderObj 的字段补丁,无预填则 null
*/
export async function resolveDefaultSelection(context = {}) { export async function resolveDefaultSelection(context = {}) {
const { orderObj = {}, userInfo = {}, orderCreateType } = context const { orderObj = {}, userInfo = {}, orderCreateType } = context
if (orderObj.userId) return null if (orderObj.userId) return null
......
/**
* @file createOrder 礼券联动副作用
*
* 以下场景必须清空 orderObj 上的礼券字段(门店/销售变更后礼券可能失效):
* - 确认变更销售顾问(sales 模式)— @see createOrder.onStaffPickerConfirm
* - 车主手机号输入变为合法号码 — @see createOrder.input
* - 补录导航后重置订单 — @see createOrder.navigator
*
* 手机号变更时还需重置 `#coupon` 组件 UI 选中态。
* 交付专员变更不清礼券。
*/
/** orderObj 上与精品礼券相关的字段 */
export const COUPON_ORDER_FIELDS = [
'couponName',
'customerCouponCode',
'customerCouponId',
'merchantCouponId'
]
/**
* 清空 orderObj 上的礼券字段(原地 mutate)
* @param {Object} orderObj
* @returns {Object} orderObj
*/
export function clearOrderCouponFields(orderObj) {
if (!orderObj) return orderObj
COUPON_ORDER_FIELDS.forEach(key => {
if (orderObj[key] !== undefined) {
delete orderObj[key]
}
})
return orderObj
}
/**
* 重置 Coupon 组件列表选中态(页面需已挂载 id="coupon")
* @param {WechatMiniprogram.Page.TrivialInstance} page
*/
export function resetCouponComponent(page) {
page?.selectComponent?.('#coupon')?.resetSelection?.()
}
...@@ -5,10 +5,13 @@ import { createRequire } from 'node:module' ...@@ -5,10 +5,13 @@ import { createRequire } from 'node:module'
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const { const {
STAFF_MODE, STAFF_MODE,
applySystemStaffFallbackIfNeeded,
buildOrderPatch, buildOrderPatch,
buildSalesSingleMerchantDefault, buildSalesSingleMerchantDefault,
getPickerLabels, getPickerLabels,
hasStaffConflict, hasStaffConflict,
shouldEchoSystemStaff,
shouldUseSystemStaffFallback,
updateMerchantSelection, updateMerchantSelection,
updateStaffSelection updateStaffSelection
} = require('../services/merchantStaffSelection.helpers.js') } = require('../services/merchantStaffSelection.helpers.js')
...@@ -88,4 +91,75 @@ describe('merchantStaffSelection', () => { ...@@ -88,4 +91,75 @@ describe('merchantStaffSelection', () => {
assert.equal(list[0].active, false) assert.equal(list[0].active, false)
assert.equal(list[1].active, true) assert.equal(list[1].active, true)
}) })
it('shouldUseSystemStaffFallback requires single merchant and empty order merchant', () => {
const context = {
orderObj: {},
orderCreateType: 'createdOrder',
merchantList: [{ merchantId: 'm1' }]
}
assert.equal(shouldUseSystemStaffFallback(STAFF_MODE.SALES, context), true)
assert.equal(
shouldUseSystemStaffFallback(STAFF_MODE.SALES, {
...context,
merchantList: [{ merchantId: 'm1' }, { merchantId: 'm2' }]
}),
false
)
assert.equal(
shouldUseSystemStaffFallback(STAFF_MODE.SALES, {
...context,
orderObj: { merchantId: 'm1' }
}),
false
)
assert.equal(
shouldUseSystemStaffFallback(STAFF_MODE.SALES, {
...context,
orderCreateType: 'additionRecordOrder'
}),
false
)
})
it('applySystemStaffFallbackIfNeeded injects system for empty staff list', () => {
const result = applySystemStaffFallbackIfNeeded(STAFF_MODE.SALES, [], {
orderObj: {},
orderCreateType: 'createdOrder',
merchantList: [{ merchantId: 'm1' }]
})
assert.equal(result.length, 1)
assert.equal(result[0].uuid, -1)
assert.equal(result[0].staffName, '系统')
})
it('applySystemStaffFallbackIfNeeded does not inject system during search', () => {
const result = applySystemStaffFallbackIfNeeded(STAFF_MODE.SALES, [], {
orderObj: {},
orderCreateType: 'createdOrder',
merchantList: [{ merchantId: 'm1' }],
keyWord: '张三'
})
assert.deepEqual(result, [])
})
it('shouldEchoSystemStaff detects userId -1', () => {
assert.equal(
shouldEchoSystemStaff(STAFF_MODE.SALES, { userId: -1 }),
true
)
assert.equal(
shouldEchoSystemStaff(STAFF_MODE.SALES, { userId: 'u1' }),
false
)
})
it('applySystemStaffFallbackIfNeeded echoes system staff for userId -1', () => {
const result = applySystemStaffFallbackIfNeeded(STAFF_MODE.SALES, [], {
orderObj: { userId: -1, merchantId: 'm1' },
orderCreateType: 'createdOrder',
merchantList: [{ merchantId: 'm1' }, { merchantId: 'm2' }]
})
assert.equal(result[0].staffName, '系统')
})
}) })
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const {
COUPON_ORDER_FIELDS,
clearOrderCouponFields,
resetCouponComponent
} = require('../services/orderCouponEffects.js')
describe('orderCouponEffects', () => {
it('COUPON_ORDER_FIELDS lists all coupon keys', () => {
assert.deepEqual(COUPON_ORDER_FIELDS, [
'couponName',
'customerCouponCode',
'customerCouponId',
'merchantCouponId'
])
})
it('clearOrderCouponFields removes coupon fields in place', () => {
const orderObj = {
couponName: '测试券',
customerCouponCode: 'ABC',
customerCouponId: 'id1',
merchantCouponId: 'm1',
merchantId: 'shop1'
}
const result = clearOrderCouponFields(orderObj)
assert.strictEqual(result, orderObj)
assert.equal(orderObj.merchantId, 'shop1')
assert.equal(orderObj.couponName, undefined)
assert.equal(orderObj.customerCouponCode, undefined)
assert.equal(orderObj.customerCouponId, undefined)
assert.equal(orderObj.merchantCouponId, undefined)
})
it('clearOrderCouponFields handles null/empty orderObj', () => {
assert.equal(clearOrderCouponFields(null), null)
assert.deepEqual(clearOrderCouponFields({}), {})
})
it('resetCouponComponent calls coupon resetSelection', () => {
const calls = []
const page = {
selectComponent: () => ({
resetSelection: () => calls.push('reset')
})
}
resetCouponComponent(page)
assert.deepEqual(calls, ['reset'])
})
it('resetCouponComponent is safe when coupon missing', () => {
assert.doesNotThrow(() => resetCouponComponent({}))
assert.doesNotThrow(() => resetCouponComponent(null))
})
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!