Commit 433f6635 by 张立顺

feat 功能自测

1 parent 9ddc0cb6
# Low Price Pending Order Edit Echo Implementation Plan
> **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:** 修复列表到创建页的路由契约,而不重写回显逻辑。`jump` 仅在目标是 `createOrder` 时追加 `page: 'edit'`,使创建页命中现有 `EditOrderStrategy`,其他目标保持原参数。
**Tech Stack:** 微信小程序 JavaScript、Node.js `node:test`、Babel/VM 页面行为测试。
## Global Constraints
- 只修改 `regional-assistant` 项目。
- 待跟进记录仍跳转 `tabWorkOrder.createOrder`。
- 编辑参数必须保留列表 `item` 的全部字段,并追加 `page: 'edit'`。
- 不修改 `EditOrderStrategy`、`setOrderObj` 或其他状态的路由行为。
- 不覆盖当前工作区的其他未提交修改。
---
### Task 1: 补齐待跟进编辑路由参数
**Files:**
- Modify: `tests/work-order-migration/work-order-list-page.test.mjs:192`
- Modify: `pages/tabWorkOrder/pages/index/index.js:229`
**Interfaces:**
- Consumes: `jump(e)` 的 `e.currentTarget.dataset.name` 与 `item`。
- Produces: `wx.$router.go('tabWorkOrder.createOrder', { ...item, page: 'edit' })`。
- [ ] **Step 1: Write the failing test**
将待跟进用例的 `item` 扩充为包含客户、商品和支付摘要的字面量,调用 `jump`,并断言最终参数深等于:
```js
{
...item,
page: 'edit'
}
```
该断言会在 `jump` 少传 `page` 或丢失任一原订单字段时失败。
- [ ] **Step 2: Run test to verify it fails**
Run: `node --test tests/work-order-migration/work-order-list-page.test.mjs`
Expected: FAIL,实际参数缺少 `page: 'edit'`。
- [ ] **Step 3: Write minimal implementation**
在 `jump` 中构造目标参数:
```js
const params =
name === 'createOrder'
? { ...item, page: 'edit' }
: item
wx.$router.go('tabWorkOrder.' + name, params)
```
- [ ] **Step 4: Run focused tests**
Run: `node --test tests/work-order-migration/work-order-list-page.test.mjs tabWorkOrder/pages/createOrder/tests/routeMatch.helpers.test.mjs`
Expected: PASS;列表路由携带编辑标识,且 `orderCode + page` 仍匹配 `EditOrderStrategy`。
### Task 2: 完整回归与补丁复核
**Files:**
- Verify: `pages/tabWorkOrder/pages/index/index.js`
- Verify: `tests/work-order-migration/work-order-list-page.test.mjs`
**Interfaces:**
- Consumes: Task 1 的路由参数修复。
- Produces: 创建页、工单列表及静态闭包的回归证据。
- [ ] **Step 1: Run create-order tests**
Run: `npm run test:createOrder`
Expected: PASS。
- [ ] **Step 2: Run work-order tests**
Run: `npm run test:workOrder`
Expected: PASS,且闭包检查输出 `status: ok`。
- [ ] **Step 3: Check patch formatting and scope**
Run: `git diff --check`
Expected: 退出码 0。
Run: `git diff -- pages/tabWorkOrder/pages/index/index.js tests/work-order-migration/work-order-list-page.test.mjs`
Expected: 本次新增差异只是创建页编辑标识及对应行为测试,不清理这两个文件中的既有用户改动。
# Low Price Tab Status Filter Implementation Plan
> **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:** 页签到审批状态单值的映射继续由 `lowPriceOrder.helpers.js` 集中管理。列表页在每次请求前删除订单状态字段 `statusList` 和旧数组字段 `goodsOrderApplyStatusList`,并仅在非“全部”页签写入 `goodsOrderApplyStatus`。测试同时覆盖纯映射和页面到 API 的最终请求边界。
**Tech Stack:** 微信小程序 JavaScript、Node.js `node:test`、项目 ESM loader/mocks。
## Global Constraints
- 只修改 `regional-assistant` 项目。
- `statusList` 只用于订单状态,不得承载审批状态。
- “全部”页签不传 `statusList`、`goodsOrderApplyStatusList` 和 `goodsOrderApplyStatus`。
- 待审批、已通过、已驳回分别传 `goodsOrderApplyStatus=2`、`3`、`4`。
- 不改动已有搜索、筛选、统计和列表展示逻辑。
- 不覆盖工作区中其他未提交修改。
---
### Task 1: 锁定页签到请求状态的契约
**Files:**
- Modify: `tests/work-order-migration/low-price-order-flow.test.mjs`
- Modify: `tests/work-order-migration/shims/mock-api.mjs`
**Interfaces:**
- Consumes: `resolveApprovalStatusFilter(index)` 和页面 `getWorkList()`。
- Produces: 四个页签的期望单值,以及捕获 `getWorkPackageGoodsList(payload)` 最终入参的 mock。
- [ ] **Step 1: Write the failing tests**
将页签映射断言改为 `[undefined, 2, 3, 4]`,并调用页面 `getWorkList()` 断言四个页签的最终请求都不存在 `statusList` 和 `goodsOrderApplyStatusList`。“全部”不存在 `goodsOrderApplyStatus`,其他三个页签分别携带 `2`、`3`、`4`。
- [ ] **Step 2: Run test to verify it fails**
Run: `node --test tests/work-order-migration/low-price-order-flow.test.mjs`
Expected: “全部”实际映射为 `[1,2,3,4]`,且页面实际请求使用 `statusList`,测试失败。
### Task 2: 恢复审批状态字段
**Files:**
- Modify: `pages/tabWorkOrder/services/lowPriceOrder.helpers.js`
- Modify: `pages/tabWorkOrder/pages/index/index.js`
**Interfaces:**
- Consumes: `resolveApprovalStatusFilter(index)` 返回 `number | undefined`。
- Produces: `getWorkPackageGoodsList({ ..., goodsOrderApplyStatus? })` 请求,不包含 `statusList` 和 `goodsOrderApplyStatusList`。
- [ ] **Step 1: Write minimal implementation**
使用 `[undefined, 2, 3, 4]` 映射。`getWorkList()` 在构造最终请求时先删除 `obj.statusList`、`obj.goodsOrderApplyStatusList` 和旧的 `obj.goodsOrderApplyStatus`,当映射存在时重新赋值单值 `obj.goodsOrderApplyStatus`。
- [ ] **Step 2: Run focused test to verify it passes**
Run: `node --test tests/work-order-migration/low-price-order-flow.test.mjs`
Expected: PASS。
### Task 3: 回归验证
**Files:**
- Verify: `pages/tabWorkOrder/pages/index/index.js`
- Verify: `pages/tabWorkOrder/services/lowPriceOrder.helpers.js`
- Verify: `tests/work-order-migration/low-price-order-flow.test.mjs`
**Interfaces:**
- Consumes: Task 1 和 Task 2 的完整修改。
- Produces: 可交付的回归证据。
- [ ] **Step 1: Run work-order regression tests**
Run: `npm run test:workOrder`
Expected: PASS。
- [ ] **Step 2: Run create-order regression tests**
Run: `npm run test:createOrder`
Expected: PASS。
- [ ] **Step 3: Check patch formatting**
Run: `git diff --check`
Expected: 无输出,退出码为 0。
- [ ] **Step 4: Review final diff without committing unrelated changes**
Run: `git diff -- pages/tabWorkOrder/services/lowPriceOrder.helpers.js pages/tabWorkOrder/pages/index/index.js tests/work-order-migration/low-price-order-flow.test.mjs tests/work-order-migration/shims/mock-api.mjs`
Expected: 仅包含本次状态契约修复及其测试,不自动提交工作区中的其他改动。
......@@ -4,22 +4,22 @@
`pages/tabWorkOrder/pages/index/index` 的页签表达的是低价单审批状态,但 `statusList` 在开发环境 Swagger 中明确定义为“订单状态列表”。将审批通过值 `3` 写入 `statusList[0]` 会查询订单状态 3,而不是 `goodsOrderApplyStatus=3`,因此已通过页签可能返回空数据。
Swagger 当前漏掉了列表接口的审批状态筛选入参,但返回类型 `GoodsOrderDTO` 明确包含 `goodsOrderApplyStatus`,而项目历史低价单实现与接口清单均使用 `goodsOrderApplyStatusList` 作为审批状态查询字段。
列表接口的审批状态筛选字段为单值 `goodsOrderApplyStatus`,状态值 `2`、`3`、`4` 分别表示待审批、审核通过和驳回。
## 设计
- 保留现有四个页签及审批状态值语义。
- `resolveApprovalStatusFilter(index)` 返回审批状态数组:
- `resolveApprovalStatusFilter(index)` 返回审批状态单值:
- 全部:`undefined`
- 待审批:`[1, 2]`
- 已通过:`[3]`
- 已驳回:`[4]`
- `getWorkList()` 先删除 `statusList`,避免将审批值误作订单状态。
- 待审批、已通过和已驳回将映射结果写入 `goodsOrderApplyStatusList`。
- “全部”不传 `statusList` 也不传 `goodsOrderApplyStatusList`,保证待跟进等订单不被订单状态误过滤。
- 待审批:`2`
- 已通过:`3`
- 已驳回:`4`
- `getWorkList()` 先删除 `statusList` 和旧数组字段 `goodsOrderApplyStatusList`,避免历史筛选残留。
- 待审批、已通过和已驳回将映射结果写入 `goodsOrderApplyStatus`。
- “全部”不传任何状态筛选字段,保证待跟进等订单不会被误过滤。
## 验证
- 单元测试覆盖四个页签的审批状态映射。
- 页面请求边界测试捕获 `getWorkPackageGoodsList` 的最终入参,断言四个页签均不携带 `statusList`,且“全部”不携带审批状态字段。
- 页面请求边界测试捕获 `getWorkPackageGoodsList` 的最终入参,断言四个页签均不携带 `statusList` 和旧数组字段,且“全部”不携带审批状态字段。
- 运行低价单专项测试和工单迁移回归测试。
......@@ -108,9 +108,9 @@
| Tab | 列表查询追加审批条件 | 统计含义 |
| ------ | -------------------- | -------- |
| 全部 | 不追加 | 全部低价单 |
| 待审批 | `goodsOrderApplyStatusList=[1,2]` | 待审批 |
| 已通过 | `goodsOrderApplyStatusList=[3]` | 已通过 |
| 已驳回 | `goodsOrderApplyStatusList=[4]` | 已驳回 |
| 待审批 | `goodsOrderApplyStatus=2` | 待审批 |
| 已通过 | `goodsOrderApplyStatus=3` | 已通过 |
| 已驳回 | `goodsOrderApplyStatus=4` | 已驳回 |
#### Swagger 响应契约(2026-08-07)
......
......@@ -185,6 +185,7 @@ Page({
let { searchObj } = this.data
delete searchObj.statusList
delete searchObj.goodsOrderApplyStatusList
delete searchObj.goodsOrderApplyStatus
this.setData({
tabIndex: e.detail,
activeIndex: e.detail,
......@@ -226,59 +227,10 @@ Page({
wx.hideTabBar()
},
async jump(e) {
// 订单状态 1 待跟进, 2 不升级, 3 待支付,4 已支付,6 已评价 ,9 已撤销 , 10 已关闭 , 11 已失效
// constructionFlag 施工标识(Y:已施工;N||null:未施工)
// failureFlag 订单失效状态(Y:已失效,N:未失效)
// console.log(e.currentTarget.dataset)
// return
let { item, name } = e.currentTarget.dataset
// console.log(item, name)
let {
userInfo,
isMake,
userInfo: { userType }
} = this.data
// console.log(status)
// console.log(item.constructionFlag)
// if (name == 'createOrder' || name == 'premiumUpgrade') {
if (name == 'createOrder' || name == 'premiumUpgrade') {
if (userInfo.merchantType && !wx.$hasPermission?.isSuper?.(userInfo) && isMake) {
// 校验是否填写昨日日报
let staffCheck = await checkDailyReport()
if (staffCheck) return false
// 校验学习中心开单限制
let staffStudyTask = await checkStudyTask()
if (staffStudyTask) return false
let lockCheck = await checkOrderLockGate()
if (lockCheck) return false
if (
name == 'createOrder' &&
(await wx.$globalDataFunction.inspectionOfProhibitionBill())
)
return /**禁止提单 */
// 是微信支付直接跳转确认页面
if (userType == 2 && item?.selectPayType == 1) {
wx.$router.go('tabWorkOrder.confirmOrder', item)
} else if (userType == 2) {
item
? this.showSelectType({
item
})
: wx.$router.go('tabWorkOrder.' + name, item)
} else {
wx.$util.showNoAccess()
}
} else {
wx.$util.showNoAccess()
}
// 已支付加已施工 全部子订单都已施工才能确认施工详情跳转
} else if (item.allConstructionFlag && item.status != 10) {
wx.$router.go('tabWorkOrder.orderDetail', item)
} else {
wx.$router.go('tabWorkOrder.' + name, item)
}
jump(e) {
const { item, name } = e.currentTarget.dataset
const params = name === 'createOrder' ? { ...item, page: 'edit' } : item
wx.$router.go('tabWorkOrder.' + name, params)
},
// 查看全部商品
showAllGoodsList(e) {
......@@ -566,11 +518,12 @@ Page({
...searchObj
}
const approvalStatusList = resolveApprovalStatusFilter(tabIndex)
if (approvalStatusList) {
obj.goodsOrderApplyStatusList = approvalStatusList
} else {
delete obj.goodsOrderApplyStatusList
const approvalStatus = resolveApprovalStatusFilter(tabIndex)
delete obj.statusList
delete obj.goodsOrderApplyStatusList
delete obj.goodsOrderApplyStatus
if (approvalStatus !== undefined) {
obj.goodsOrderApplyStatus = approvalStatus
}
api.getWorkPackageGoodsList(obj).then(res => {
wx.$util.hideLoading()
......
......@@ -19,7 +19,7 @@
<block wx:for="{{ list }}" wx:key="index">
<block wx:for="{{ item }}" wx:for-item="li" wx:for-index="ind" wx:key="ind">
<view style="{{ li.txtStyle }}" class="touch-item {{ li.isTouchMove ? 'touch-move-active' : '' }}" data-ind="{{ ind }}" data-index="{{ index }}">
<view class="item content low-price-card" catchtap="jump" data-ind="{{ ind }}" data-index="{{ index }}" bindtouchstart="touchstart" bindtouchmove="touchmove" bindtouchend="touchE" data-name="orderDetail" data-item="{{ li }}">
<view class="item content low-price-card" catchtap="jump" data-ind="{{ ind }}" data-index="{{ index }}" bindtouchstart="touchstart" bindtouchmove="touchmove" bindtouchend="touchE" data-name="{{ li.status == 3 ? 'confirmOrder' : li.status == 1 ? 'createOrder' : 'orderDetail' }}" data-item="{{ li }}">
<view class="low-price-card-header">
<view class="low-price-customer-name text-hide">{{ (li.customer && li.customer.customerName) || '--' }}</view>
<view class="low-price-card-status" style="color:{{ li.statuscolor }};background-color:{{ li.statusbackground }};">{{ li.goodsOrderApplyStatusText || li.statusText || '--' }}</view>
......@@ -47,7 +47,7 @@
</view>
</view>
<view class="low-price-card-footer">
<view class="low-price-view" catchtap="jump" data-name="orderDetail" data-item="{{ li }}">查看</view>
<view class="low-price-view" catchtap="jump" data-name="{{ li.status == 3 ? 'confirmOrder' : li.status == 1 ? 'createOrder' : 'orderDetail' }}" data-item="{{ li }}">查看</view>
</view>
</view>
<block wx:if="{{ isMake }}">
......
export const APPROVAL_STATUS_TABS = ['全部', '待审批', '已通过', '已驳回']
const APPROVAL_STATUS_FILTERS = [undefined, [1, 2], [3], [4]]
const APPROVAL_STATUS_FILTERS = [undefined, 2, 3, 4]
export function resolveApprovalStatusFilter(index) {
const filter = APPROVAL_STATUS_FILTERS[Number(index)]
return filter ? [...filter] : undefined
return APPROVAL_STATUS_FILTERS[Number(index)]
}
function numberValue(data, keys) {
......@@ -18,9 +17,10 @@ function numberValue(data, keys) {
}
export function buildApprovalStatusCounts(data = {}) {
const pendingFallback =
numberValue(data, ['status1Count', 'applyStatus1Count']) +
numberValue(data, ['status2Count', 'applyStatus2Count'])
const pendingFallback = numberValue(data, [
'status2Count',
'applyStatus2Count'
])
return [
numberValue(data, ['totalCount', 'allCount', 'count']),
numberValue(data, [
......@@ -48,4 +48,3 @@ export function buildApprovalStatusCounts(data = {}) {
])
]
}
......@@ -22,16 +22,20 @@ Component({
type: Boolean,
value: false,
observer(n) {
if (n) {
this.setData({ keyWord: '' })
this.loadPickerData()
if (!n) {
this._loadedPickerMode = ''
return
}
this.openPickerOnce()
}
},
/** sales | conversion | delivery */
mode: {
type: String,
value: ''
value: '',
observer() {
if (this.properties.show) this.openPickerOnce()
}
},
orderObj: {
type: Object,
......@@ -63,6 +67,15 @@ Component({
},
methods: {
/** 同一次打开只初始化一次;兼容 show/mode 属性分开发生 observer。 */
openPickerOnce() {
const mode = this.properties.mode
if (!mode || this._loadedPickerMode === mode) return
this._loadedPickerMode = mode
this.setData({ keyWord: '' })
this.loadPickerData()
},
/**
* show=true 时加载门店与员工;失败 toast 并通知页面关闭
*/
......
......@@ -1671,14 +1671,16 @@ Page({
checkRequired(save, obj) {
// 导入动态校验字段
let { requiredList } = this.data
const orderRequiredList = requiredList.filter(
key => !['baseSceneCode', 'baseSceneName'].includes(key)
)
// let target = save ? ['userId', 'merchantId', 'employeeName', ...requiredList, 'customerName', 'customerPhone', 'sellerUserId', 'sellerName', 'sellerMerchantId']
// : ['userId', 'merchantId', 'employeeName', ...requiredList, 'customerName', 'customerPhone', 'sellerUserId', 'sellerName', 'sellerMerchantId', 'customerCouponCode']
let target = [
'userId',
'baseSceneCode',
'merchantId',
'employeeName',
...requiredList,
...orderRequiredList,
'customerName',
'salesType',
'sellerUserId',
......@@ -1701,9 +1703,11 @@ Page({
this.showToast('备注不能为空')
return true
}
// Customer-profile fields only fill customer validation values. They must
// never shadow order-level selections such as merchant, staff, or scene.
obj = {
...obj,
...obj.customer
...(obj.customer || {}),
...obj
}
if (
shouldValidateCustomerPhone(requiredList, obj.customer.customerPhone) &&
......
/**
* @file 低价单提交成功后的列表目标状态。
*/
export function isLowPriceSubmit(orderObj = {}) {
return Number(orderObj?.lowPriceFlag) === 1
}
export function isLowPriceListPage(pageInstance) {
const route = pageInstance?.route || pageInstance?.__route__ || ''
return route === 'pages/tabWorkOrder/pages/index/index'
}
export function buildPendingLowPriceListPatch() {
return {
activeIndex: 1,
tabIndex: 1,
keyword: '',
searchObj: {}
}
}
......@@ -21,8 +21,32 @@ export const SUBMIT_ROOT_PROPERTIES_TO_DELETE = [
export const SUBMIT_CUSTOMER_PROPERTIES_TO_DELETE = [
'buyTime',
'createdDate',
'createdBy',
'updatedBy',
'updatedDate',
'deletedFlag',
'baseSceneCode',
'sceneType',
'businessType',
'qwGroupId',
'qwGroupName',
'wxId',
'wxName',
'deliveryDate',
'inviteDate',
'keyword',
'buyTimeStr',
'totalCustomer',
'merchantIds',
'yqMerchantIds',
'sellerUserIds',
'goodsOrder',
'sceneTypes',
'customerPhoneList',
'staffUuid',
'merchantId',
'orderDate',
'orderCodes',
'actualDeliveryDate'
]
......
......@@ -5,10 +5,9 @@ import { prepareSubmitPayload } from './services/submitPayload.helpers.js'
import { buildMinPriceApprovalList } from './services/minPriceApproval.js'
import { shouldUseMinPriceApprovalFlow } from './services/orderMerchantConfig.js'
import {
buildPendingLowPriceListPatch,
isLowPriceListPage,
isLowPriceSubmit
} from './services/lowPriceSubmitNavigation.helpers.js'
LOW_PRICE_DEFAULT_SCENE,
applyLowPriceDefaultScene
} from './services/lowPriceOrderContext.helpers.js'
// ----------------------------------------------------------------------
// 辅助构造函数:校验结果
......@@ -190,11 +189,32 @@ function SubmitContext(page) {
this.page = page
}
SubmitContext.prototype.isLowPriceOrder = function () {
if (typeof this.page.isLowPriceOrder === 'function') {
return this.page.isLowPriceOrder()
}
return Number(this.page.data.orderObj?.lowPriceFlag) === 1
}
SubmitContext.prototype.ensureLowPriceOrderScene = function () {
if (!this.isLowPriceOrder()) return
const orderObj = applyLowPriceDefaultScene({
...(this.page.data.orderObj || {}),
lowPriceFlag: 1
})
this.page.setData({ orderObj })
}
SubmitContext.prototype.execute = async function (event) {
const dataset = event.currentTarget.dataset
const save = dataset.save
const context = { save }
// 低价单页面的订单对象可能被路由/档案回显整对象替换;校验前恢复页面固定标识,
// 并仅在场景不完整时补默认值,完整的真实场景保持不变。
this.ensureLowPriceOrderScene()
// 手机号默认值属于页面配置,保留在订单数据校验之前处理。
this.page.checkPhoneUseConfig()
......@@ -238,6 +258,8 @@ SubmitContext.prototype.execute = async function (event) {
* @param {{ save?: boolean }} options
*/
SubmitContext.prototype.executeAfterApproval = async function (options = {}) {
// 审批弹层期间页面状态仍可能变化,真正发请求前再次保证低价单场景完整。
this.ensureLowPriceOrderScene()
await this.finishSubmit(options.save, true)
}
......@@ -273,7 +295,16 @@ SubmitContext.prototype.finishSubmit = async function (
SubmitContext.prototype.prepareSubmitData = function (save) {
const data = this.page.data
return prepareSubmitPayload(data.orderObj, {
// 低价单接口当前固定要求精品升级场景。请求体在最后一步重新写入,
// 不依赖页面场景接口、客户档案回显或审批弹层期间的状态。
const orderObj = this.isLowPriceOrder()
? {
...(data.orderObj || {}),
lowPriceFlag: 1,
...LOW_PRICE_DEFAULT_SCENE
}
: data.orderObj
return prepareSubmitPayload(orderObj, {
save,
isErrorOrder: data.isErrorOrder,
orderCreateType: data.orderCreateType,
......@@ -330,20 +361,7 @@ SubmitContext.prototype.doSubmit = async function (submitObj, apiName, save) {
// 状态更新 需刷新工单列表和预约管理列表
wx.$util.refreshPageData()
if (isErrorOrder) resData.isErrorOrder = true
if (isLowPriceSubmit(data.orderObj)) {
const listPatch = buildPendingLowPriceListPatch()
const previousPage = wx.$router.getPageInstance?.(2)
if (isLowPriceListPage(previousPage) && previousPage?.setData) {
previousPage.setData(listPatch)
wx.$router.back()
} else {
wx.$router.go(
'/pages/tabWorkOrder/pages/index/index?activeIndex=1'
)
}
} else {
wx.$router.redirectTo('confirmOrder', resData)
}
wx.$router.redirectTo('confirmOrder', resData)
}
} else {
wx.showModal({
......
......@@ -136,10 +136,10 @@ test('the dedicated create page normalizes every route to a low-price order', as
])
})
test('low-price required-field validation requires the scene stored on the page', () => {
test('low-price required-field validation does not block on scene fields', () => {
const page = createPage()
page._isLowPriceCreateOrder = true
page.data.requiredList = []
page.data.requiredList = ['baseSceneCode', 'baseSceneName']
const orderObj = {
userId: 1,
baseSceneCode: '',
......@@ -157,10 +157,32 @@ test('low-price required-field validation requires the scene stored on the page'
}
}
assert.equal(
pageConfig.checkRequired.call(page, false, orderObj),
'baseSceneCode'
)
assert.equal(pageConfig.checkRequired.call(page, false, orderObj), false)
})
test('customer profile fields cannot override selected order merchant during validation', () => {
const page = createPage()
page.data.requiredList = []
const orderObj = {
userId: '14b46ce8a57c47328d7552b8a3dd5950',
merchantId: 44210895,
employeeName: 'selected sales advisor',
sellerUserId: 2,
sellerName: 'conversion staff',
sellerMerchantId: 100,
payeeType: 1,
selectPayType: 1,
customer: {
merchantId: '',
baseSceneCode: '',
baseSceneName: '',
customerName: 'selected customer',
customerPhone: '13800000000',
salesType: 0
}
}
assert.equal(pageConfig.checkRequired.call(page, false, orderObj), false)
})
test('empty recent and store scene responses keep the fixed page fallback', async () => {
......@@ -451,7 +473,7 @@ test('non-staff order echo cannot overwrite a manually selected sales advisor',
assert.equal(page.data.orderObj.merchantName, '波波的单店门店')
})
test('ordinary required-field validation still requires a scene', () => {
test('create-order required-field validation does not block on scene fields', () => {
const page = createPage()
page._isLowPriceCreateOrder = false
page.data.requiredList = []
......@@ -472,10 +494,7 @@ test('ordinary required-field validation still requires a scene', () => {
}
}
assert.equal(
pageConfig.checkRequired.call(page, false, orderObj),
'baseSceneCode'
)
assert.equal(pageConfig.checkRequired.call(page, false, orderObj), false)
})
test('direct low-price entry waits for the selected store scene name before finishing initialization', async () => {
......@@ -649,6 +668,40 @@ test('low-price submit uses the page fallback while scene initialization is pend
assert.equal(page.data.minPriceApprovalSheet.show, true)
})
test('direct submit restores the dedicated low-price page scene before required-field validation', async () => {
let orderSeenByRequiredValidation
let requiredErrorKey
const page = createPage()
page._isLowPriceCreateOrder = true
page.data.orderObj = {
...page.data.orderObj,
lowPriceFlag: undefined,
baseSceneCode: '',
baseSceneName: '',
sceneType: '',
customer: {}
}
page.checkPhoneUseConfig = () => {}
page.checkGoods = () => undefined
page.checkRequired = (_save, orderObj) => {
orderSeenByRequiredValidation = structuredClone(orderObj)
return orderObj.baseSceneCode ? 'customerName' : 'baseSceneCode'
}
page.handleRequiredError = key => {
requiredErrorKey = key
}
await pageConfig.submit.call(page, {
currentTarget: { dataset: { save: false } }
})
assert.equal(orderSeenByRequiredValidation.lowPriceFlag, 1)
assert.equal(orderSeenByRequiredValidation.baseSceneCode, '100101')
assert.equal(orderSeenByRequiredValidation.baseSceneName, '精品升级')
assert.equal(orderSeenByRequiredValidation.sceneType, 1)
assert.equal(requiredErrorKey, 'customerName')
})
test('submit preserves a real low-price scene before required-field validation', async () => {
let orderSeenByRequiredValidation
const page = createPage()
......@@ -678,7 +731,7 @@ test('submit preserves a real low-price scene before required-field validation',
assert.equal(orderSeenByRequiredValidation.sceneType, 7)
})
test('approval confirmation submits the real scene without replacing it', async () => {
test('approval confirmation submits the fixed low-price scene', async () => {
let submittedPayload
globalThis.__WORK_ORDER_MOCK_API__ = {
createWithPay(payload) {
......@@ -712,9 +765,48 @@ test('approval confirmation submits the real scene without replacing it', async
await pageConfig.onConfirmMinPriceApprovalSubmit.call(page)
assert.equal(submittedPayload.lowPriceFlag, 1)
assert.equal(submittedPayload.baseSceneCode, 'SCENE-REAL')
assert.equal(submittedPayload.baseSceneName, '接口返回场景')
assert.equal(submittedPayload.sceneType, 7)
assert.equal(submittedPayload.baseSceneCode, '100101')
assert.equal(submittedPayload.baseSceneName, '精品升级')
assert.equal(submittedPayload.sceneType, 1)
})
test('approval confirmation restores a missing dedicated low-price scene before the request', async () => {
let submittedPayload
globalThis.__WORK_ORDER_MOCK_API__ = {
createWithPay(payload) {
submittedPayload = payload
return { code: 0, data: { orderCode: 'LOW-PRICE-DEFAULT' } }
}
}
wx.disableAlertBeforeUnload = () => {}
wx.hideLoading = () => {}
wx.$util.refreshPageData = () => {}
wx.$router = {
getPageInstance: () => null,
go() {},
redirectTo() {}
}
const page = createPage()
page._isLowPriceCreateOrder = true
page.data.orderObj = {
lowPriceFlag: undefined,
baseSceneCode: '',
baseSceneName: '',
sceneType: '',
selectPayType: 1,
customer: {},
subOrderList: []
}
page.data.goodsList = []
page.data._pendingSubmitSave = false
await pageConfig.onConfirmMinPriceApprovalSubmit.call(page)
assert.equal(submittedPayload.lowPriceFlag, 1)
assert.equal(submittedPayload.baseSceneCode, '100101')
assert.equal(submittedPayload.baseSceneName, '精品升级')
assert.equal(submittedPayload.sceneType, 1)
})
test('ordinary create-order submission keeps its original scene', async () => {
......
......@@ -12,6 +12,38 @@ const mockApi = await import(
)
const { SubmitContext } = await import(`../submitStrategy.js?flow=${Date.now()}`)
const CUSTOMER_SUBMIT_FIELDS_TO_STRIP = [
'buyTime',
'createdDate',
'createdBy',
'updatedBy',
'updatedDate',
'deletedFlag',
'baseSceneCode',
'sceneType',
'businessType',
'qwGroupId',
'qwGroupName',
'wxId',
'wxName',
'deliveryDate',
'inviteDate',
'keyword',
'buyTimeStr',
'totalCustomer',
'merchantIds',
'yqMerchantIds',
'sellerUserIds',
'goodsOrder',
'sceneTypes',
'customerPhoneList',
'staffUuid',
'merchantId',
'orderDate',
'orderCodes',
'actualDeliveryDate'
]
function createPage(options = {}) {
const approvalItems = []
const patches = []
......@@ -94,45 +126,64 @@ describe('low-price approval submit flow', () => {
assert.equal(approvalItems[0].name, '测试商品')
})
it('submits once after approval and returns the source list to pending', async () => {
it('redirects a low-price order to confirmOrder after approval', async () => {
let apiCalls = 0
let submittedPayload
let redirectTarget = ''
let redirectData
let backCalls = 0
let sourcePatch
globalThis.__WORK_ORDER_MOCK_API__.createWithPay = payload => {
apiCalls += 1
submittedPayload = payload
return { code: 0, data: { orderCode: 'LP-1' } }
}
wx.$router.redirectTo = route => {
wx.$router.redirectTo = (route, data) => {
redirectTarget = route
redirectData = data
}
wx.$router.back = () => {
backCalls += 1
}
wx.$router.getPageInstance = () => ({
__route__: 'pages/tabWorkOrder/pages/index/index',
setData(patch) {
sourcePatch = patch
}
})
const { page } = createPage()
await new SubmitContext(page).executeAfterApproval({ save: false })
assert.equal(apiCalls, 1)
assert.equal(submittedPayload.baseSceneCode, 'SCENE-LOW')
assert.equal(submittedPayload.baseSceneName, '低价单默认场景')
assert.equal(submittedPayload.baseSceneCode, '100101')
assert.equal(submittedPayload.baseSceneName, '精品升级')
assert.equal(submittedPayload.sceneType, 1)
assert.equal(redirectTarget, '')
assert.equal(backCalls, 1)
assert.deepEqual(sourcePatch, {
activeIndex: 1,
tabIndex: 1,
keyword: '',
searchObj: {}
assert.equal(redirectTarget, 'confirmOrder')
assert.deepEqual(redirectData, { orderCode: 'LP-1' })
assert.equal(backCalls, 0)
})
it('strips customer metadata from the actual order API request', async () => {
let submittedPayload
globalThis.__WORK_ORDER_MOCK_API__.createWithPay = payload => {
submittedPayload = payload
return { code: 0, data: { orderCode: 'LP-CUSTOMER-CLEANUP' } }
}
const { page } = createPage()
page.data.orderObj.customer = {
...Object.fromEntries(
CUSTOMER_SUBMIT_FIELDS_TO_STRIP.map(field => [
field,
`remove-${field}`
])
),
customerName: 'retained customer'
}
await new SubmitContext(page).executeAfterApproval({ save: false })
CUSTOMER_SUBMIT_FIELDS_TO_STRIP.forEach(field => {
assert.equal(
Object.prototype.hasOwnProperty.call(submittedPayload.customer, field),
false,
field
)
})
assert.equal(submittedPayload.customer.customerName, 'retained customer')
})
it('keeps ordinary order success on confirmOrder', async () => {
......@@ -158,31 +209,4 @@ describe('low-price approval submit flow', () => {
assert.equal(redirectTarget, 'confirmOrder')
})
it('falls back to the pending-list route when the source list is unavailable', async () => {
let fallbackRoute = ''
let backCalls = 0
globalThis.__WORK_ORDER_MOCK_API__.createWithPay = () => ({
code: 0,
data: { orderCode: 'LP-FALLBACK' }
})
wx.$router.getPageInstance = () => ({
__route__: 'pages/tab/workspace/workspace',
setData() {}
})
wx.$router.back = () => {
backCalls += 1
}
wx.$router.go = route => {
fallbackRoute = route
}
const { page } = createPage()
await new SubmitContext(page).executeAfterApproval({ save: false })
assert.equal(
fallbackRoute,
'/pages/tabWorkOrder/pages/index/index?activeIndex=1'
)
assert.equal(backCalls, 0)
})
})
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import {
buildPendingLowPriceListPatch,
isLowPriceListPage,
isLowPriceSubmit
} from '../services/lowPriceSubmitNavigation.helpers.js'
describe('low-price submit navigation', () => {
it('builds the pending-tab list state after a low-price submit', () => {
assert.deepEqual(buildPendingLowPriceListPatch(), {
activeIndex: 1,
tabIndex: 1,
keyword: '',
searchObj: {}
})
})
it('branches only for explicit low-price orders', () => {
assert.equal(isLowPriceSubmit({ lowPriceFlag: 1 }), true)
assert.equal(isLowPriceSubmit({ lowPriceFlag: '1' }), true)
assert.equal(isLowPriceSubmit({ lowPriceFlag: 0 }), false)
})
it('recognizes only the low-price order list as a safe back target', () => {
assert.equal(
isLowPriceListPage({ __route__: 'pages/tabWorkOrder/pages/index/index' }),
true
)
assert.equal(
isLowPriceListPage({ route: 'pages/tabWorkOrder/pages/index/index' }),
true
)
assert.equal(isLowPriceListPage({ __route__: 'pages/tab/workspace/workspace' }), false)
assert.equal(isLowPriceListPage(undefined), false)
})
})
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
)
function createComponentInstance(componentConfig, properties) {
const instance = {
properties: { ...properties },
data: structuredClone(componentConfig.data),
setData(patch) {
Object.assign(this.data, patch)
},
triggerEvent() {}
}
Object.entries(componentConfig.methods).forEach(([name, method]) => {
instance[name] = method.bind(instance)
})
return instance
}
test('同一次打开重复同步 show=true 时只加载一次人员数据', async () => {
let componentConfig
let employeeRequestCount = 0
globalThis.Component = config => {
componentConfig = config
}
globalThis.wx = {
$util: {
showToast() {}
}
}
globalThis.__WORK_ORDER_MOCK_API__ = {
getEmployeeList() {
employeeRequestCount += 1
return {
code: 0,
data: [{ userId: 'staff-1', name: '销售顾问一' }]
}
}
}
try {
await import(
`../components/merchant-staff-picker/merchant-staff-picker.js?single-open=${Date.now()}`
)
const instance = createComponentInstance(componentConfig, {
show: true,
mode: 'sales',
orderObj: {
lowPriceFlag: 1,
merchantId: 44210895,
merchantName: '当前下单门店'
},
userContext: {},
pointsMultiRole: 'Y',
orderCreateType: 'createdOrder'
})
const showObserver = componentConfig.properties.show.observer
showObserver.call(instance, true, false)
showObserver.call(instance, true, true)
await new Promise(resolve => setImmediate(resolve))
assert.equal(employeeRequestCount, 1)
assert.equal(instance.data.staffList[0].staffName, '销售顾问一')
instance.properties.show = false
showObserver.call(instance, false, true)
instance.properties.show = true
showObserver.call(instance, true, false)
await new Promise(resolve => setImmediate(resolve))
assert.equal(employeeRequestCount, 2)
} finally {
delete globalThis.__WORK_ORDER_MOCK_API__
delete globalThis.Component
}
})
......@@ -131,9 +131,9 @@ describe('低价单审批列表适配', () => {
it('使用全部、待审批、已通过、已驳回页签', () => {
assert.deepEqual(APPROVAL_STATUS_TABS, ['全部', '待审批', '已通过', '已驳回'])
assert.equal(resolveApprovalStatusFilter(0), undefined)
assert.deepEqual(resolveApprovalStatusFilter(1), [1, 2])
assert.deepEqual(resolveApprovalStatusFilter(2), [3])
assert.deepEqual(resolveApprovalStatusFilter(3), [4])
assert.equal(resolveApprovalStatusFilter(1), 2)
assert.equal(resolveApprovalStatusFilter(2), 3)
assert.equal(resolveApprovalStatusFilter(3), 4)
})
it('兼容统计接口的新旧字段命名', () => {
......@@ -155,6 +155,16 @@ describe('低价单审批列表适配', () => {
}),
[9, 2, 6, 1]
)
assert.deepEqual(
buildApprovalStatusCounts({
totalCount: 11,
status1Count: 9,
status2Count: 2,
status3Count: 0,
status4Count: 0
}),
[11, 2, 0, 0]
)
})
it('兜底路由在页面加载时应用待审批页签参数', async () => {
......@@ -185,8 +195,71 @@ describe('低价单审批列表适配', () => {
assert.equal(page.data.tabIndex, 1)
assert.equal(page.data.keyword, '')
assert.equal(page.data.searchObj.merchantId, '')
assert.equal(page.data.searchObj.goodsOrderApplyStatus, undefined)
assert.equal(page.data.searchObj.goodsOrderApplyStatusList, undefined)
})
it('切换页签时使用审批状态参数且全部不绑定状态', async () => {
let pageConfig
globalThis.Page = config => {
pageConfig = config
}
globalThis.wx = {
$util: {
getUserInfo: () => ({ merchantAccountList: [] }),
hideLoading() {}
}
}
await import(
`../../pages/tabWorkOrder/pages/index/index.js?status-filter=${Date.now()}`
)
const expectedApprovalStatuses = [undefined, 2, 3, 4]
const capturedPayloads = []
globalThis.__WORK_ORDER_MOCK_API__ = {
getWorkPackageGoodsList(payload) {
capturedPayloads.push(payload)
return { code: 0, data: { list: [], total: 0 } }
}
}
for (const [
tabIndex,
expectedApprovalStatus
] of expectedApprovalStatuses.entries()) {
const page = {
...pageConfig,
data: {
...pageConfig.data,
tabIndex,
searchObj: {
statusList: [99],
goodsOrderApplyStatusList: [99],
goodsOrderApplyStatus: 99
},
userInfo: {},
status: {}
},
setData(patch) {
Object.assign(this.data, patch)
}
}
page.getWorkList()
await new Promise(resolve => setTimeout(resolve, 0))
const payload = capturedPayloads[tabIndex]
assert.equal('statusList' in payload, false)
assert.equal('goodsOrderApplyStatusList' in payload, false)
if (expectedApprovalStatus !== undefined) {
assert.equal(payload.goodsOrderApplyStatus, expectedApprovalStatus)
} else {
assert.equal('goodsOrderApplyStatus' in payload, false)
}
}
delete globalThis.__WORK_ORDER_MOCK_API__
})
})
describe('创建页低价单上下文', () => {
......
......@@ -49,6 +49,12 @@ export default {
data: []
})
},
getWorkPackageGoodsList(data) {
return configuredResponse('getWorkPackageGoodsList', data, {
code: 0,
data: { list: [], total: 0 }
})
},
getLastUserOrderInfo(data) {
return configuredResponse('getLastUserOrderInfo', data, {
code: 0,
......
......@@ -18,6 +18,7 @@ async function loadListPage() {
let pageConfig
const navigateBackCalls = []
const showTabBarCalls = []
const routerCalls = []
runInNewContext(generate(ast).code, {
Page(config) {
......@@ -28,14 +29,19 @@ async function loadListPage() {
},
wx: {
navigateBack: options => navigateBackCalls.push(options),
showTabBar: options => showTabBarCalls.push(options)
showTabBar: options => showTabBarCalls.push(options),
$router: {
go(name, params) {
routerCalls.push({ name, params })
}
}
},
console,
setTimeout,
clearTimeout
})
return { pageConfig, navigateBackCalls, showTabBarCalls }
return { pageConfig, navigateBackCalls, showTabBarCalls, routerCalls }
}
function createPageContext(pageConfig, initialData) {
......@@ -182,4 +188,46 @@ describe('工单列表页面行为', () => {
assert.match(style, /\.low-price-card\b/)
assert.match(style, /\.low-price-view\b/)
})
it('routes list cards directly by order status without permission gates', async () => {
const { pageConfig, routerCalls } = await loadListPage()
const template = await readFile(
'pages/tabWorkOrder/pages/index/index.wxml',
'utf8'
)
const item = {
status: 1,
orderCode: 'FOLLOW-1',
lowPriceFlag: 1,
merchantId: 'SHOP-1',
customer: { customerName: '张三', vin: 'VIN-001' },
subOrderList: [{ merchantGoodsId: 'GOODS-1', finalPrice: 99 }],
selectPayType: 3
}
const context = createPageContext(pageConfig, {})
const routeBindings =
template.match(
/data-name="\{\{\s*li\.status\s*==\s*3\s*\?\s*'confirmOrder'\s*:\s*li\.status\s*==\s*1\s*\?\s*'createOrder'\s*:\s*'orderDetail'\s*\}\}"/g
) || []
assert.equal(
routeBindings.length,
2,
'card body and footer must use the same status target'
)
pageConfig.jump.call(context, {
currentTarget: { dataset: { name: 'createOrder', item } }
})
assert.equal(routerCalls.length, 1)
assert.equal(routerCalls[0].name, 'tabWorkOrder.createOrder')
assert.deepEqual(
JSON.parse(JSON.stringify(routerCalls[0].params)),
{
...item,
page: 'edit'
}
)
})
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!