Compare commits
10 Commits
69c272d260
...
4c2cfe1793
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c2cfe1793 | ||
|
|
20b017c1b6 | ||
|
|
f219902cda | ||
|
|
75680d9451 | ||
|
|
dbca49c3fa | ||
|
|
44b8b09e0e | ||
|
|
b7010921c9 | ||
|
|
e080bcbb76 | ||
|
|
d4128c4eee | ||
|
|
61309c430f |
@ -1255,3 +1255,44 @@ WMS 侧待发布(打印层兼容 + 菜鸟 printinfo 回拼 + 本次 key 兜底
|
||||
取号 → 查 `wms_order_express.printinfo/encryptprintinfo` 长度(约 3.4–3.8KB / 172)→ 打印验证。
|
||||
|
||||
wms/
|
||||
|
||||
---
|
||||
|
||||
## OMS 侧:发货确认回传序列号(SN)留存与反查(2026-11-13)
|
||||
|
||||
WMS 回传 `deliveryorder.confirm` 时,明细行可能带上序列号列表:
|
||||
|
||||
```json
|
||||
{
|
||||
"request": {
|
||||
"deliveryOrder": { "deliveryOrderCode": "FH_123", "status": "DELIVERED" },
|
||||
"packages": { "package": [ { "expressCode": "YT123", "packageCode": "PK-1", "items": [ { "itemCode": "SKU-A", "snList": [ "SN3" ] } ] } ] },
|
||||
"orderLines": [ { "orderLineNo": "1", "itemCode": "SKU-A", "snList": [ "SN1", "SN2" ] } ]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
OMS 侧处理:
|
||||
|
||||
| 项 | 说明 |
|
||||
|---|---|
|
||||
| 落库表 | `order_sn_codes`(一行一个 SN;`order_id` = `order_index.id`,订单在状态表间流转时 ID 不变,故转表不搬 SN) |
|
||||
| 解析字段 | 行级 `orderLines[].snList` / `snCodes` / `snCode`(兼容逗号分隔、`[{ snCode }]` 对象数组),包裹级 `packages.package[].items[].snList` |
|
||||
| 附加字段 | 行号 / 商品编码 / 商品ID / 商品名称 / 包裹号 / 运单号 / 仓库ID(来自 app_key) |
|
||||
| 幂等 | 同一订单重复回传同一 SN 不新增(先按订单查已存在 SN,唯一键 `uk_osc_order_sn` 兜底) |
|
||||
| 实现 | `backend/app/lib/orderSnCodes.js`(`extractSnEntries` / `saveOrderSnCodes`),由 `orderCallback.confirmDelivery` 调用;老表发货单(`order_deliveries`)不回写 |
|
||||
|
||||
订单查询按 SN 反查(支持多个,逗号 / 换行分隔,最多 200 个,精确匹配):
|
||||
|
||||
```
|
||||
GET /api/order-status/list?status=delivery&sn_codes=SN1,SN2
|
||||
```
|
||||
|
||||
- 后端先按 `(principal_id, sn_code)` 从 `order_sn_codes` 取命中的订单ID,再回状态表过滤;
|
||||
- 订单导出的筛选条件同样支持「序列号」(`sn_codes`);
|
||||
- 订单导出支持两个维度(提交参数):
|
||||
- 范围:`ids`(导出选中,订单ID 逗号分隔,最多 500 个)/ 不传(按筛选条件全部);
|
||||
- 内容:`export_mode=order`(默认,一行一个订单,**不含明细**)/ `export_mode=item`(一行一个商品明细,订单字段重复填充);
|
||||
- 两种内容都带「序列号数量」「序列号列表」列:订单行取该订单全部回传 SN,含明细取该行 SN(按行号匹配,行号为空的回传记录按商品编码兜底);
|
||||
- 订单详情(`GET /api/order-status/:id`)返回 `order.sn_codes`;页面详情抽屉在「商品明细」每行提供「SN码(N)」按钮,点击展开该行的序列号列表(含运单号 / 回传时间)。
|
||||
|
||||
|
||||
@ -2504,6 +2504,21 @@ module.exports = {
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
archived_at: { type: 'string', description: '归档时间(仅历史表)' },
|
||||
transferred_at: { type: 'string', description: '转入历史时间(仅历史表)' },
|
||||
sn_codes: { type: 'array', itemType: 'orderStatusSnCode', description: '序列号(SN)列表(仅详情返回;WMS 发货确认回传的 snList)' },
|
||||
},
|
||||
/** 订单序列号(SN)行(order_sn_codes) */
|
||||
orderStatusSnCode: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
order_id: { type: 'integer', description: '订单ID(= order_index.id)' },
|
||||
order_line_no: { type: 'string', description: '回传明细行号(orderLineNo)' },
|
||||
item_id: { type: 'integer', description: '商品ID(itemId)' },
|
||||
item_code: { type: 'string', description: '商品编码(itemCode)' },
|
||||
item_name: { type: 'string', description: '商品名称(itemName)' },
|
||||
package_code: { type: 'string', description: '包裹号(packageCode)' },
|
||||
express_code: { type: 'string', description: '运单号(expressCode)' },
|
||||
sn_code: { type: 'string', description: '序列号(SN)' },
|
||||
source: { type: 'string', description: '来源:wms=仓库回传' },
|
||||
created_at: { type: 'string', description: '回传留存时间' },
|
||||
},
|
||||
orderStatusPage: {
|
||||
...buildPage('orderStatusItem', '订单列表'),
|
||||
@ -2624,7 +2639,7 @@ module.exports = {
|
||||
id: { type: 'integer', description: '明细ID' },
|
||||
order_id: { type: 'integer', description: '订单ID(= order_index.id)' },
|
||||
order_line_no: { type: 'string', description: '行号(缺省按行序号)' },
|
||||
item_id: { type: 'integer', description: 'WMS 内部商品ID' },
|
||||
item_id: { type: 'integer', description: 'WMS 内部商品ID(历史手工单曾存系统商品ID,写库时会按商品编码核对后迁到 product_id)' },
|
||||
item_code: { type: 'string', description: '商品编码' },
|
||||
item_name: { type: 'string', description: '商品名称' },
|
||||
plan_qty: { type: 'number', description: '计划数量(必须大于 0)' },
|
||||
@ -2636,7 +2651,7 @@ module.exports = {
|
||||
sub_source_order_code: { type: 'string', description: '子来源订单编码' },
|
||||
stock_id: { type: 'integer', description: 'WMS 仓库库存ID' },
|
||||
extend_props: { type: 'object', description: '扩展属性' },
|
||||
product_id: { type: 'integer', description: '系统商品ID' },
|
||||
product_id: { type: 'integer', description: '系统商品ID(手工单选中的系统商品;平台订单为绑定店铺商品后的系统商品ID)' },
|
||||
sku_code: { type: 'string', description: '商家编码' },
|
||||
spec: { type: 'string', description: '规格' },
|
||||
image: { type: 'string', description: '图片' },
|
||||
|
||||
@ -51,7 +51,8 @@ class OrderStatusController extends Controller {
|
||||
* @summary 订单列表
|
||||
* @description 按 status 定位状态表分页查询(pending 待审核 / queued 待推送 / exception 异常 /
|
||||
* outsourcing 委外中 / delivery 配送 / void 已作废 / canceled 已取消 / history 历史)。
|
||||
* 支持订单号、来源订单号、店铺、收货人、收货地址、备注(异常原因)、关键词与创建时间区间过滤;
|
||||
* 支持订单号、来源订单号、店铺、收货人、收货地址、备注(异常原因)、关键词、平台单号、
|
||||
* 序列号(SN)与创建时间区间过滤;
|
||||
* 历史视图另支持归档时间区间。返回行附状态中文、店铺名称与商品明细摘要。
|
||||
* @router get /api/order-status/list
|
||||
* @apikey
|
||||
@ -63,6 +64,7 @@ class OrderStatusController extends Controller {
|
||||
* @request query integer shop_id 店铺ID
|
||||
* @request query string platform_codes 电商平台编码,多选用逗号分隔(PDD / DYXD / SPH…,见系统预设平台编码)
|
||||
* @request query string platform_order_nos 平台单号,多个精确匹配用逗号分隔(最多 200 个)
|
||||
* @request query string sn_codes 序列号(SN),多个精确匹配用逗号分隔(最多 200 个;WMS 发货确认回传的 snList)
|
||||
* @request query string receiver 收货人,模糊匹配
|
||||
* @request query string address 收货地址,模糊匹配
|
||||
* @request query string remark 备注 / 异常原因,模糊匹配
|
||||
|
||||
@ -38,7 +38,7 @@ class ShopProductController extends Controller {
|
||||
/**
|
||||
* @summary 店铺商品列表
|
||||
* @description 分页查询店铺商品,支持按店铺(多选)、平台类型(多选)、商家编码(多个精确匹配)、
|
||||
* 平台商品ID / 平台规格ID(多个精确匹配)、绑定状态、关键词(标题/商家编码/平台商品ID)过滤;
|
||||
* 平台商品ID / 平台规格ID(多个精确匹配)、绑定状态、关键词(标题/商家编码/平台商品ID/规格ID/规格)过滤;
|
||||
* has_unbound_order=1 时只返回「有订单但未绑定系统商品」的店铺商品
|
||||
* @router get /api/shop-products
|
||||
* @apikey
|
||||
@ -53,7 +53,7 @@ class ShopProductController extends Controller {
|
||||
* @request query string outer_sku_ids 平台规格ID,多个用英文逗号分隔(精确匹配)
|
||||
* @request query integer bind_type 绑定类型:0未绑定 1系统商品 2组合商品
|
||||
* @request query integer status 状态:1在售 0下架
|
||||
* @request query string keyword 关键词,匹配标题、商家编码或平台商品ID
|
||||
* @request query string keyword 关键词,匹配标题、商家编码、平台商品ID、平台规格ID 或规格
|
||||
* @request query integer has_unbound_order 传 1 时只返回有订单且未绑定的商品(待处理订单的商品)
|
||||
* @response 200 shopProductListResponse success
|
||||
*/
|
||||
@ -106,8 +106,9 @@ class ShopProductController extends Controller {
|
||||
{ title: { [Op.like]: `%${keyword}%` } },
|
||||
{ outer_code: { [Op.like]: `%${keyword}%` } },
|
||||
{ outer_item_id: { [Op.like]: `%${keyword}%` } },
|
||||
// 与导出/关键词口径一致:规格ID 也能模糊搜
|
||||
// 与导出/关键词口径一致:规格ID、平台规格文字 也能模糊搜
|
||||
{ outer_sku_id: { [Op.like]: `%${keyword}%` } },
|
||||
{ spec: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@ -91,7 +91,8 @@ function buildReplay(row) {
|
||||
* 处理已存在的幂等记录
|
||||
*
|
||||
* 只有「已成功」的记录才回放:失败结果不缓存,允许调用方用同一 request_id 重新处理
|
||||
* (取号类接口的重复保护靠业务侧幂等,如订单已有运单号直接复用,而不是锁死请求)。
|
||||
* (deliveryorder.getwaybill 的逐单重复保护由 waybill_fetch_idempotencies 按订单、
|
||||
* 快递编码和包裹序号完成)。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} row 幂等记录
|
||||
* @param {Object} params 参数
|
||||
|
||||
@ -4,6 +4,7 @@ const completeInbound = require('../utils/completeInbound');
|
||||
const { applyStockChange } = require('../utils/stockRecord');
|
||||
const { deductDeliveryStock } = require('../utils/deliveryStock');
|
||||
const { ORDER_STATUS, orderModelName, orderStatusLabel } = require('./orderStatus');
|
||||
const { saveOrderSnCodes } = require('./orderSnCodes');
|
||||
|
||||
/**
|
||||
* 外部回调(对外通用回调接口 /openapi)驱动 OMS 单据的共用处理逻辑。
|
||||
@ -827,6 +828,7 @@ function buildExpressOverride(order, express) {
|
||||
* 处理内容:① 回写运单号 express_code 与物流公司(缺失或变化时)② 状态「已推送(3)」→「已完成(4)」
|
||||
* ③ 若审核时已锁定库存(order_deliveries.stock_locked=1)则扣减库存(总数量与锁定同减)
|
||||
* 并写 order_deduct 流水;历史单据(stock_locked=0)不扣减,避免凭空减少总数量
|
||||
* ④ 明细行 / 包裹商品的 `snList` 落到 order_sn_codes(订单查询可按 SN 反查,见 lib/orderSnCodes.js)
|
||||
* 幂等:已完成(4) 的单据再次收到(可能多次)相同报文时只做缺失字段补写并直接回成功
|
||||
* (不重复改状态、不重复扣减库存、不重复写推送结果);状态非 3/4 时返回失败,交由调用方告警/重试。
|
||||
* @param {Object} ctx egg context
|
||||
@ -864,6 +866,21 @@ async function confirmDelivery(ctx, { principalId, warehouseId, data }) {
|
||||
{ express: expressResult.first }
|
||||
);
|
||||
|
||||
// 明细行 snList → order_sn_codes(订单查询可按 SN 反查);老表发货单没有索引表 ID,不做关联
|
||||
// 仅对「委外中 / 已配送」的订单留存(其余状态本次确认会被拒绝,避免留下不该有的 SN)
|
||||
const recordSn = resolved.isNewModel
|
||||
&& [ ORDER_STATUS.OUTSOURCING, ORDER_STATUS.DELIVERY ].includes(resolved.index.current_status);
|
||||
const snResult = recordSn
|
||||
? await saveOrderSnCodes(ctx, {
|
||||
principalId,
|
||||
orderId: Number(resolved.index.id),
|
||||
orderNo: resolved.index.order_no,
|
||||
warehouseId,
|
||||
lines,
|
||||
packages,
|
||||
})
|
||||
: { inserted: 0, total: 0 };
|
||||
|
||||
// 新表(order_index + 状态表):委外中 → 配送(扣减锁定库存),已配送幂等回执
|
||||
if (resolved.isNewModel) {
|
||||
const result = await confirmOrderStatusDelivery(ctx, { resolved, payload, packages, lines, pkgInfo });
|
||||
@ -872,6 +889,7 @@ async function confirmDelivery(ctx, { principalId, warehouseId, data }) {
|
||||
orderNo: resolved.order.parent_order_no || resolved.index.order_no,
|
||||
});
|
||||
}
|
||||
if (result.data) result.data.sn_codes_added = snResult.inserted;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
82
backend/app/lib/orderPushItems.js
Normal file
82
backend/app/lib/orderPushItems.js
Normal file
@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单推送前的明细校验:明细能否落到「系统商品」。
|
||||
*
|
||||
* 背景:平台拉单的明细在绑定店铺商品前保留的是平台原样数据(平台商品ID / 平台编码 / 快照),
|
||||
* 这类明细直接推给仓库会建出脏商品或报错,必须先在「店铺商品」绑定系统商品/组合商品;
|
||||
* 手工建单 / 接口建单的明细则直接来自系统商品,没有店铺商品绑定,不能按绑定状态拦。
|
||||
*
|
||||
* 因此判断口径是「能否解析到系统商品」而不是「有没有 product_id」:
|
||||
* ① 有 combo_product_id(组合拆分子行)→ 可推送
|
||||
* ② product_id 命中系统商品 → 可推送
|
||||
* ③ 历史手工单口径:item_id 存的是系统商品ID,且与行上的 item_code 一致 → 可推送
|
||||
* ④ 没有平台溯源信息(shop_product_id / platform_snapshot / outer_item_id 都为空)时,
|
||||
* item_code 命中系统商品编码 → 可推送
|
||||
* 其余一律视为未转换(平台编码不能下发仓库)。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 明细是否带平台溯源信息(平台拉单行的标记)
|
||||
* @param {Object} item 明细行
|
||||
* @return {Boolean} 是否来自平台
|
||||
*/
|
||||
function hasPlatformTrace(item) {
|
||||
if (!item || typeof item !== 'object') return false;
|
||||
return Boolean(item.shop_product_id || item.platform_snapshot || item.outer_item_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 找出无法落到系统商品的明细
|
||||
* @param {Array<Object>} items 订单明细(order_status_items 行)
|
||||
* @param {Array<Object>} products 本主体下的系统商品(按 id / item_code 命中即可,{ id, item_code })
|
||||
* @return {Array<Object>} 无法解析的明细行(全部可推送时返回空数组)
|
||||
*/
|
||||
function findUnconvertibleItems(items, products) {
|
||||
const productCodeById = new Map();
|
||||
const productCodes = new Set();
|
||||
for (const row of products || []) {
|
||||
const id = Number(row && row.id);
|
||||
const code = String(row && row.item_code == null ? '' : row.item_code).trim();
|
||||
if (Number.isInteger(id) && id > 0) productCodeById.set(id, code);
|
||||
if (code) productCodes.add(code);
|
||||
}
|
||||
|
||||
return (Array.isArray(items) ? items : []).filter(item => {
|
||||
if (!item || typeof item !== 'object') return false;
|
||||
if (Number(item.combo_product_id) > 0) return false;
|
||||
|
||||
const productId = Number(item.product_id);
|
||||
if (Number.isInteger(productId) && productId > 0 && productCodeById.has(productId)) return false;
|
||||
|
||||
const code = String(item.item_code == null ? '' : item.item_code).trim();
|
||||
// 历史手工单:item_id 误存了系统商品ID(编码一致才认,避免把真正的 WMS 商品ID误判)
|
||||
const legacyId = Number(item.item_id);
|
||||
if (Number.isInteger(legacyId) && legacyId > 0 && code && productCodeById.get(legacyId) === code) return false;
|
||||
|
||||
if (code && productCodes.has(code) && !hasPlatformTrace(item)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成「未转换明细」的推送中止提示(最多列出 5 行)
|
||||
* @param {Array<Object>} items 无法解析的明细行
|
||||
* @return {String} 提示文案
|
||||
*/
|
||||
function unconvertibleMessage(items) {
|
||||
const list = Array.isArray(items) ? items : [];
|
||||
const detail = list
|
||||
.slice(0, 5)
|
||||
.map(item => `第 ${(item && item.order_line_no) || '?'} 行 ${(item && item.item_code) || '(无编码)'}`)
|
||||
.join('、');
|
||||
return `明细商品未绑定系统商品(${detail}${list.length > 5 ? ` 等 ${list.length} 行` : ''}),无法推送:` +
|
||||
'平台订单请先在「店铺商品」把对应商品绑定到系统商品/组合商品(重新绑定会自动重建订单明细);' +
|
||||
'手工单请选择系统商品(明细商品编码需与系统商品编码一致)';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
hasPlatformTrace,
|
||||
findUnconvertibleItems,
|
||||
unconvertibleMessage,
|
||||
};
|
||||
265
backend/app/lib/orderSnCodes.js
Normal file
265
backend/app/lib/orderSnCodes.js
Normal file
@ -0,0 +1,265 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单序列号(SN)关联表的解析与写入
|
||||
*
|
||||
* 背景:WMS 回传发货确认(deliveryorder.confirm)时,明细行可能带 `snList`:
|
||||
* { request: { orderLines: [ { orderLineNo: '1', itemCode: 'SKU-A', snList: [ 'SN1', 'SN2' ] } ],
|
||||
* packages: { package: [ { expressCode, packageCode, items: [ { itemCode, snList } ] } ] } } }
|
||||
* 这些 SN 原先只留在 `wms_push_result.confirm` 的 JSON 摘要里,无法反查订单;
|
||||
* 现在统一落 `order_sn_codes`(一行一个 SN,`order_id` = order_index.id),
|
||||
* 订单列表即可按「主体 + SN(支持多个)」反查出订单。
|
||||
*
|
||||
* 幂等:同一订单重复回传同一报文时不新增行(先查已存在的 SN,再由唯一键 `uk_osc_order_sn` 兜底)。
|
||||
*/
|
||||
|
||||
/** SN 列宽(order_sn_codes.sn_code),超长截断避免异常报文撑爆索引 */
|
||||
const SN_MAX_LEN = 255;
|
||||
/** 单次回传最多留存的 SN 条数,防止异常报文写入过多数据 */
|
||||
const SN_MAX_COUNT = 2000;
|
||||
|
||||
/**
|
||||
* 字段取值并截断(去空白;空值返回 '')
|
||||
* @param {Object} obj 源对象
|
||||
* @param {Array<String>} keys 候选字段名
|
||||
* @param {Number} max 最大长度
|
||||
* @return {String} 值
|
||||
*/
|
||||
function pickText(obj, keys, max) {
|
||||
if (!obj || typeof obj !== 'object') return '';
|
||||
for (const key of keys) {
|
||||
const value = obj[key];
|
||||
if (value === undefined || value === null) continue;
|
||||
if (typeof value === 'object') continue;
|
||||
const text = String(value).trim();
|
||||
if (text) return text.slice(0, max);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 数字ID归一化(非正整数返回 null)
|
||||
* @param {*} value 原值
|
||||
* @return {Number|null} 数值
|
||||
*/
|
||||
function toId(value) {
|
||||
const num = Number(value);
|
||||
return Number.isInteger(num) && num > 0 ? num : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从明细行的 SN 字段取 SN 列表(兼容数组 / 逗号分隔字符串 / 对象数组)
|
||||
* 支持字段:snList / sn_list / snCodes / sn_codes / snCode / sn_code / sn
|
||||
* @param {Object} obj 明细行或包裹内商品
|
||||
* @return {Array<String>} SN 列表(原值去空白,未去重)
|
||||
*/
|
||||
function extractSnValues(obj) {
|
||||
if (!obj || typeof obj !== 'object') return [];
|
||||
const values = [];
|
||||
const push = raw => {
|
||||
if (raw === undefined || raw === null) return;
|
||||
if (Array.isArray(raw)) {
|
||||
raw.forEach(push);
|
||||
return;
|
||||
}
|
||||
if (typeof raw === 'object') {
|
||||
// 兼容 [{ snCode: 'xxx' }, { sn: 'xxx' }, { code: 'xxx' }]
|
||||
push(raw.snCode ?? raw.sn_code ?? raw.sn ?? raw.code ?? raw.value);
|
||||
return;
|
||||
}
|
||||
const text = String(raw).trim();
|
||||
if (!text) return;
|
||||
// 一个字段里塞了多个 SN("SN1,SN2" / 换行分隔)时拆开
|
||||
if (/[,,;;\r\n]/.test(text)) {
|
||||
text.split(/[,,;;\r\n]+/).forEach(item => push(item));
|
||||
return;
|
||||
}
|
||||
values.push(text.slice(0, SN_MAX_LEN));
|
||||
};
|
||||
for (const key of [ 'snList', 'sn_list', 'snCodes', 'sn_codes', 'snCode', 'sn_code', 'sn' ]) {
|
||||
if (obj[key] !== undefined && obj[key] !== null) push(obj[key]);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* 包裹内商品数组归一化(兼容 items 数组 / items.item 数组)
|
||||
* @param {Object} pkg 包裹
|
||||
* @return {Array<Object>} 商品数组
|
||||
*/
|
||||
function packageItems(pkg) {
|
||||
const raw = pkg && pkg.items;
|
||||
if (Array.isArray(raw)) return raw.filter(item => item && typeof item === 'object');
|
||||
if (raw && Array.isArray(raw.item)) return raw.item.filter(item => item && typeof item === 'object');
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从发货确认报文的明细行 / 包裹中解析 SN 条目
|
||||
*
|
||||
* 行级 SN 与包裹内商品 SN 都收:行级带 orderLineNo/itemCode,包裹级额外带 packageCode/expressCode;
|
||||
* 同一 SN 只保留首次出现的条目(MySQL 比较不区分大小写,这里也按小写去重)。
|
||||
* @param {Object} p 参数
|
||||
* @param {Array<Object>} [p.lines] 明细行数组(request.orderLines)
|
||||
* @param {Array<Object>} [p.packages] 包裹数组(request.packages.package)
|
||||
* @return {Array<Object>} SN 条目:{ sn_code, order_line_no, item_id, item_code, item_name, package_code, express_code }
|
||||
*/
|
||||
function extractSnEntries({ lines = [], packages = [] } = {}) {
|
||||
const entries = [];
|
||||
const seen = new Set();
|
||||
|
||||
const add = (sn, meta) => {
|
||||
const text = String(sn == null ? '' : sn).trim().slice(0, SN_MAX_LEN);
|
||||
if (!text) return false;
|
||||
const key = text.toLowerCase();
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
entries.push({
|
||||
sn_code: text,
|
||||
order_line_no: meta.order_line_no || null,
|
||||
item_id: meta.item_id || null,
|
||||
item_code: meta.item_code || null,
|
||||
item_name: meta.item_name || null,
|
||||
package_code: meta.package_code || null,
|
||||
express_code: meta.express_code || null,
|
||||
});
|
||||
return entries.length >= SN_MAX_COUNT;
|
||||
};
|
||||
|
||||
for (const line of Array.isArray(lines) ? lines : []) {
|
||||
if (!line || typeof line !== 'object') continue;
|
||||
const meta = {
|
||||
order_line_no: pickText(line, [ 'orderLineNo', 'order_line_no' ], 20),
|
||||
item_id: toId(line.itemId ?? line.item_id),
|
||||
item_code: pickText(line, [ 'itemCode', 'item_code' ], 100),
|
||||
item_name: pickText(line, [ 'itemName', 'item_name' ], 255),
|
||||
};
|
||||
for (const sn of extractSnValues(line)) {
|
||||
if (add(sn, meta)) return entries;
|
||||
}
|
||||
}
|
||||
|
||||
for (const pkg of Array.isArray(packages) ? packages : []) {
|
||||
if (!pkg || typeof pkg !== 'object') continue;
|
||||
const packageCode = pickText(pkg, [ 'packageCode', 'package_code' ], 50);
|
||||
const expressCode = pickText(pkg, [ 'expressCode', 'express_code' ], 50);
|
||||
for (const item of packageItems(pkg)) {
|
||||
const meta = {
|
||||
order_line_no: pickText(item, [ 'orderLineNo', 'order_line_no' ], 20),
|
||||
item_id: toId(item.itemId ?? item.item_id),
|
||||
item_code: pickText(item, [ 'itemCode', 'item_code' ], 100),
|
||||
item_name: pickText(item, [ 'itemName', 'item_name' ], 255),
|
||||
package_code: packageCode,
|
||||
express_code: expressCode,
|
||||
};
|
||||
for (const sn of extractSnValues(item)) {
|
||||
if (add(sn, meta)) return entries;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把回传报文里的 SN 落到 order_sn_codes(幂等:已存在的 SN 跳过)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} p 参数
|
||||
* @param {Number} p.principalId 主体ID
|
||||
* @param {Number} p.orderId 订单ID(order_index.id)
|
||||
* @param {String} [p.orderNo] 订单号(冗余留痕)
|
||||
* @param {Number} [p.warehouseId] 仓库ID(app_key 定位到的仓库)
|
||||
* @param {Array<Object>} [p.lines] 明细行数组
|
||||
* @param {Array<Object>} [p.packages] 包裹数组
|
||||
* @param {Object} [p.transaction] 事务(传入时随调用方事务写入)
|
||||
* @return {Promise<{inserted: Number, total: Number}>} inserted 新增条数 / total 报文里的 SN 条数
|
||||
*/
|
||||
async function saveOrderSnCodes(ctx, { principalId, orderId, orderNo, warehouseId, lines, packages, transaction } = {}) {
|
||||
const entries = extractSnEntries({ lines, packages });
|
||||
if (!entries.length) return { inserted: 0, total: 0 };
|
||||
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const existing = await ctx.model.OrderSnCode.findAll({
|
||||
where: {
|
||||
principal_id: principalId,
|
||||
order_id: orderId,
|
||||
sn_code: { [Op.in]: entries.map(entry => entry.sn_code) },
|
||||
},
|
||||
attributes: [ 'sn_code' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const stored = new Set(existing.map(row => String(row.sn_code || '').trim().toLowerCase()));
|
||||
const rows = entries
|
||||
.filter(entry => !stored.has(entry.sn_code.toLowerCase()))
|
||||
.map(entry => ({
|
||||
principal_id: principalId,
|
||||
order_id: orderId,
|
||||
order_no: orderNo || null,
|
||||
warehouse_id: warehouseId || null,
|
||||
order_line_no: entry.order_line_no,
|
||||
item_id: entry.item_id,
|
||||
item_code: entry.item_code,
|
||||
item_name: entry.item_name,
|
||||
package_code: entry.package_code,
|
||||
express_code: entry.express_code,
|
||||
sn_code: entry.sn_code,
|
||||
source: 'wms',
|
||||
}));
|
||||
|
||||
if (rows.length) {
|
||||
// ignoreDuplicates:并发/重推时由唯一键 uk_osc_order_sn 兜底,不报错
|
||||
await ctx.model.OrderSnCode.bulkCreate(rows, { ignoreDuplicates: true, transaction });
|
||||
ctx.logger.info(
|
||||
`[order-sn] 订单 ${orderNo || orderId} 留存序列号 ${rows.length} 个(报文共 ${entries.length} 个)`
|
||||
);
|
||||
}
|
||||
return { inserted: rows.length, total: entries.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单的 SN 列表(详情展示用,按行号 / 自增ID排序)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} p 参数
|
||||
* @param {Number} p.principalId 主体ID
|
||||
* @param {Number} p.orderId 订单ID(order_index.id)
|
||||
* @return {Promise<Array<Object>>} SN 行
|
||||
*/
|
||||
async function listOrderSnCodes(ctx, { principalId, orderId } = {}) {
|
||||
if (!orderId) return [];
|
||||
const rows = await ctx.model.OrderSnCode.findAll({
|
||||
where: { principal_id: principalId, order_id: orderId },
|
||||
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 SN 反查订单ID(订单列表筛选用)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} p 参数
|
||||
* @param {Number} p.principalId 主体ID
|
||||
* @param {Array<String>} p.snCodes SN 列表(精确匹配,最多 200 个由调用方限制)
|
||||
* @return {Promise<Array<Number>>} 命中的订单ID(去重)
|
||||
*/
|
||||
async function findOrderIdsBySnCodes(ctx, { principalId, snCodes } = {}) {
|
||||
const list = Array.isArray(snCodes) ? snCodes : [];
|
||||
if (!list.length) return [];
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const rows = await ctx.model.OrderSnCode.findAll({
|
||||
where: { principal_id: principalId, sn_code: { [Op.in]: list } },
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
return [ ...new Set(rows.map(row => Number(row.order_id)).filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SN_MAX_LEN,
|
||||
SN_MAX_COUNT,
|
||||
extractSnEntries,
|
||||
saveOrderSnCodes,
|
||||
listOrderSnCodes,
|
||||
findOrderIdsBySnCodes,
|
||||
};
|
||||
@ -78,6 +78,9 @@ const ORDER_INDEX_TABLE = 'order_index';
|
||||
/** 订单明细表表名(各状态表共用) */
|
||||
const ORDER_ITEM_TABLE = 'order_status_items';
|
||||
|
||||
/** 订单序列号(SN)关联表表名:WMS 回传的 snList 落这里,订单查询按 SN 反查 */
|
||||
const ORDER_SN_TABLE = 'order_sn_codes';
|
||||
|
||||
/** 订单明细表模型名 */
|
||||
const ORDER_ITEM_MODEL = 'OrderStatusItem';
|
||||
|
||||
@ -176,6 +179,7 @@ module.exports = {
|
||||
ORDER_INDEX_TABLE,
|
||||
ORDER_ITEM_TABLE,
|
||||
ORDER_ITEM_MODEL,
|
||||
ORDER_SN_TABLE,
|
||||
ORDER_TABLE_BY_STATUS,
|
||||
ORDER_MODEL_BY_STATUS,
|
||||
ORDER_STATUS_LIST,
|
||||
|
||||
@ -56,6 +56,12 @@ const BUSINESS_KEY_PATHS = [
|
||||
|
||||
/** 单次批量上限(避免一次回调过大、平台侧限流) */
|
||||
const MAX_BATCH = 100;
|
||||
const ITEM_STATUS = {
|
||||
PROCESSING: 0,
|
||||
SUCCESS: 1,
|
||||
UNCERTAIN: 2,
|
||||
};
|
||||
const ITEM_PROCESSING_STALE_MS = 30 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 并发处理数(平台取号是网络请求,适度并发缩短总耗时)
|
||||
@ -438,6 +444,7 @@ async function saveRecord(ctx, meta, result, extra = {}) {
|
||||
request_id: meta.requestId || '',
|
||||
delivery_order_code: meta.code,
|
||||
express_code: meta.expressCode || '',
|
||||
package_index: meta.packageIndex,
|
||||
platform_code: meta.platformCode || '',
|
||||
account_id: meta.accountId || null,
|
||||
template_id: meta.templateId || '',
|
||||
@ -445,6 +452,7 @@ async function saveRecord(ctx, meta, result, extra = {}) {
|
||||
waybill_source: (result && result.waybill_source) || '',
|
||||
waybill_code: (result && result.waybill_code) || '',
|
||||
waybill_codes: result && result.waybill_codes ? JSON.stringify(result.waybill_codes) : '',
|
||||
result_data: result ? JSON.stringify(result) : '',
|
||||
printinfo: extra.printinfo || '',
|
||||
signature: extra.signature || '',
|
||||
print_history_ids: Array.isArray(extra.print_history_ids) ? JSON.stringify(extra.print_history_ids) : '',
|
||||
@ -460,6 +468,129 @@ async function saveRecord(ctx, meta, result, extra = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按订单、快递和包裹序号占用一个取号幂等键。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} key 幂等键字段
|
||||
* @param {Object} meta 留痕上下文
|
||||
* @return {Promise<{entry: Object, owner: boolean}>} 记录和是否成功占用
|
||||
*/
|
||||
async function claimItem(ctx, key, meta) {
|
||||
const Model = ctx.model.WaybillFetchIdempotency;
|
||||
const existing = await Model.findOne({ where: key });
|
||||
if (existing) return { entry: existing, owner: false };
|
||||
|
||||
try {
|
||||
const entry = await Model.create({
|
||||
...key,
|
||||
request_id: meta.requestId || '',
|
||||
status: ITEM_STATUS.PROCESSING,
|
||||
});
|
||||
return { entry, owner: true };
|
||||
} catch (err) {
|
||||
// 并发请求由数据库唯一索引仲裁;只有确认存在竞争记录时才将其视为重复请求
|
||||
const raced = await Model.findOne({ where: key });
|
||||
if (!raced) throw err;
|
||||
return { entry: raced, owner: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析幂等记录中保存的逐单返回结果。
|
||||
* @param {Object} entry 幂等记录
|
||||
* @return {Object} 已保存结果
|
||||
*/
|
||||
function parseSavedResult(entry) {
|
||||
const result = JSON.parse(entry.result_data || '');
|
||||
if (!result || !result.success || !result.waybill_code) {
|
||||
throw new Error('保存的取号结果不完整');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 兼容幂等表上线前已成功的默认包裹记录。
|
||||
* 历史记录没有 package_index 时,仅在单号本身没有子包裹序号且请求序号为 0 时复用。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} params 查询条件
|
||||
* @param {number} params.principalId 主体ID
|
||||
* @param {number} params.warehouseId 仓库ID
|
||||
* @param {string} params.code 发货单号
|
||||
* @param {string} params.expressCode 快递编码
|
||||
* @param {number} params.packageIndex 包裹序号
|
||||
* @return {Promise<Object|null>} 已有成功记录
|
||||
*/
|
||||
async function findLegacyRecord(ctx, { principalId, warehouseId, code, expressCode, packageIndex }) {
|
||||
const where = {
|
||||
principal_id: principalId,
|
||||
warehouse_id: warehouseId,
|
||||
delivery_order_code: code,
|
||||
express_code: expressCode,
|
||||
status: 1,
|
||||
};
|
||||
if (packageIndex === 0 && resolvePackageIndex(code) === 0) {
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
where[Op.or] = [{ package_index: 0 }, { package_index: null }];
|
||||
} else {
|
||||
where.package_index = packageIndex;
|
||||
}
|
||||
return await ctx.model.WaybillFetchRecord.findOne({
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从旧取号记录组装可回给 WMS 的结果。
|
||||
* @param {Object} row 历史取号记录
|
||||
* @param {Object} params 当前订单参数
|
||||
* @param {string} params.code 发货单号
|
||||
* @param {string} params.expressCode 快递编码
|
||||
* @param {number} params.packageIndex 包裹序号
|
||||
* @return {Object} 取号结果
|
||||
*/
|
||||
function resultFromLegacyRecord(row, { code, expressCode, packageIndex }) {
|
||||
if (row.result_data) {
|
||||
return parseSavedResult({ result_data: row.result_data });
|
||||
}
|
||||
const waybillCodes = parseRecordArray(row.waybill_codes, 'waybill_codes');
|
||||
const printHistoryIds = parseRecordArray(row.print_history_ids, 'print_history_ids');
|
||||
const waybillCode = String(row.waybill_code || waybillCodes[0] || '').trim();
|
||||
if (!waybillCode) throw new Error('历史取号记录没有运单号');
|
||||
return {
|
||||
delivery_order_code: code,
|
||||
success: true,
|
||||
message: '已复用数据库中的取号结果',
|
||||
waybill_source: row.waybill_source || 'express_print',
|
||||
express_code: expressCode,
|
||||
platform_code: row.platform_code || '',
|
||||
waybill_code: waybillCode,
|
||||
waybill_codes: waybillCodes.length ? waybillCodes : [ waybillCode ],
|
||||
package_index: packageIndex,
|
||||
cai_niao_auth_info_id: row.cai_niao_auth_info_id == null ? null : Number(row.cai_niao_auth_info_id),
|
||||
printinfo: row.printinfo || '',
|
||||
signature: row.signature || '',
|
||||
print_history_ids: printHistoryIds,
|
||||
print_history_id: printHistoryIds[0] ? String(printHistoryIds[0].id || '') : '',
|
||||
encryptprintinfo: '',
|
||||
key: '',
|
||||
ver: '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析历史记录中的 JSON 数组字段。
|
||||
* @param {string} value JSON 文本
|
||||
* @param {string} field 字段名
|
||||
* @return {Array} 数组
|
||||
*/
|
||||
function parseRecordArray(value, field) {
|
||||
if (!value) return [];
|
||||
const parsed = JSON.parse(value);
|
||||
if (!Array.isArray(parsed)) throw new Error(`历史取号记录 ${field} 不是数组`);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理单个订单取号
|
||||
* @param {Object} ctx egg context
|
||||
@ -468,40 +599,178 @@ async function saveRecord(ctx, meta, result, extra = {}) {
|
||||
* @param {number} params.warehouseId app_key 定位到的仓库ID
|
||||
* @param {Object} params.item 订单项(含单号与快递编码)
|
||||
* @param {Map} params.memo 批内缓存(账号实例等)
|
||||
* @param {Map} params.itemMemo 批内订单级幂等缓存
|
||||
* @param {string} [params.requestId] 调用方 request_id(留痕用)
|
||||
* @return {Promise<Object>} 结果项
|
||||
*/
|
||||
async function processItem(ctx, { principalId, warehouseId, item, memo, requestId }) {
|
||||
async function processItem(ctx, { principalId, warehouseId, item, memo, itemMemo, requestId }) {
|
||||
const code = orderCallback.pickFirst(item || {}, CODE_PATHS);
|
||||
if (!code) return fail('', '缺少发货单号(deliveryOrderCode / outBizCode)');
|
||||
|
||||
// 快递编码必须由 WMS 传入;订单上的 logistics_code 不参与取号
|
||||
const expressCode = pickExpressCode(item);
|
||||
const expressCode = String(pickExpressCode(item) || '').trim();
|
||||
if (!expressCode) return fail(code, '缺少快递编码(expressCode)');
|
||||
|
||||
const explicitIndex = pickPackageIndex(item);
|
||||
const packageIndex = explicitIndex === null ? resolvePackageIndex(code) : explicitIndex;
|
||||
const itemKey = JSON.stringify([ principalId, warehouseId, code, expressCode, packageIndex ]);
|
||||
if (itemMemo.has(itemKey)) return await itemMemo.get(itemKey);
|
||||
|
||||
const promise = processItemWithIdempotency(ctx, {
|
||||
principalId,
|
||||
warehouseId,
|
||||
memo,
|
||||
requestId,
|
||||
code,
|
||||
expressCode,
|
||||
packageIndex,
|
||||
});
|
||||
itemMemo.set(itemKey, promise);
|
||||
try {
|
||||
return await promise;
|
||||
} catch (err) {
|
||||
itemMemo.delete(itemKey);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 占用订单级幂等键后执行平台取号。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} params 订单取号参数
|
||||
* @param {number} params.principalId 主体ID
|
||||
* @param {number} params.warehouseId 仓库ID
|
||||
* @param {Map} params.memo 批内账号缓存
|
||||
* @param {string} params.requestId 调用方 request_id
|
||||
* @param {string} params.code 发货单号
|
||||
* @param {string} params.expressCode 快递编码
|
||||
* @param {number} params.packageIndex 包裹序号
|
||||
* @return {Promise<Object>} 逐单结果
|
||||
*/
|
||||
async function processItemWithIdempotency(ctx, {
|
||||
principalId, warehouseId, memo, requestId, code, expressCode, packageIndex,
|
||||
}) {
|
||||
const key = {
|
||||
principal_id: principalId,
|
||||
warehouse_id: warehouseId,
|
||||
delivery_order_code: code,
|
||||
express_code: expressCode,
|
||||
package_index: packageIndex,
|
||||
};
|
||||
const { entry, owner } = await claimItem(ctx, key, { requestId });
|
||||
if (!owner) {
|
||||
if (Number(entry.status) === ITEM_STATUS.SUCCESS) {
|
||||
try {
|
||||
return parseSavedResult(entry);
|
||||
} catch (err) {
|
||||
ctx.logger.error('[waybill.get] 读取幂等结果失败 %s:%s', code, err.message);
|
||||
await entry.update({ status: ITEM_STATUS.UNCERTAIN, error_message: err.message });
|
||||
return fail(code, '数据库中的取号结果无法安全读取,请核实运单后再处理');
|
||||
}
|
||||
}
|
||||
if (Number(entry.status) === ITEM_STATUS.PROCESSING) {
|
||||
const updatedAt = new Date(entry.updated_at || entry.created_at || 0).getTime();
|
||||
if (updatedAt && Date.now() - updatedAt >= ITEM_PROCESSING_STALE_MS) {
|
||||
const errorMessage = '取号任务超过 30 分钟仍未完成,平台侧结果需要人工核实';
|
||||
await entry.update({ status: ITEM_STATUS.UNCERTAIN, error_message: errorMessage });
|
||||
return fail(code, errorMessage);
|
||||
}
|
||||
}
|
||||
const message = Number(entry.status) === ITEM_STATUS.UNCERTAIN
|
||||
? '上次取号结果待核实,已阻止重复取号'
|
||||
: '相同订单、快递编码和包裹序号的取号正在处理中,请稍后重试';
|
||||
return fail(code, entry.error_message ? `${message}:${entry.error_message}` : message);
|
||||
}
|
||||
|
||||
const replayParams = { code, expressCode, packageIndex };
|
||||
let legacyRecord;
|
||||
try {
|
||||
legacyRecord = await findLegacyRecord(ctx, {
|
||||
principalId,
|
||||
warehouseId,
|
||||
...replayParams,
|
||||
});
|
||||
} catch (err) {
|
||||
await entry.destroy();
|
||||
throw err;
|
||||
}
|
||||
if (legacyRecord) {
|
||||
try {
|
||||
const result = resultFromLegacyRecord(legacyRecord, replayParams);
|
||||
await entry.update({
|
||||
status: ITEM_STATUS.SUCCESS,
|
||||
result_data: JSON.stringify(result),
|
||||
error_message: '',
|
||||
});
|
||||
return result;
|
||||
} catch (err) {
|
||||
ctx.logger.error('[waybill.get] 读取历史取号记录失败 %s:%s', code, err.message);
|
||||
await entry.update({ status: ITEM_STATUS.UNCERTAIN, error_message: err.message });
|
||||
return fail(code, '历史取号记录无法安全重放,请核实运单后再处理');
|
||||
}
|
||||
}
|
||||
|
||||
// 留痕上下文:处理过程中逐步补齐(平台编码 / 打单账号 / 模板)
|
||||
const meta = { principalId, warehouseId, requestId, code, expressCode, platformCode: '', accountId: null, templateId: null };
|
||||
const meta = {
|
||||
principalId,
|
||||
warehouseId,
|
||||
requestId,
|
||||
code,
|
||||
expressCode,
|
||||
packageIndex,
|
||||
platformCode: '',
|
||||
accountId: null,
|
||||
templateId: null,
|
||||
};
|
||||
const detail = { raw: null, printinfo: '', signature: '', encryptprintinfo: '', key: '', ver: '', print_history_ids: [] };
|
||||
const result = await callPlatform(ctx, { principalId, warehouseId, code, expressCode, item, memo, meta, detail });
|
||||
const result = await callPlatform(ctx, {
|
||||
principalId,
|
||||
warehouseId,
|
||||
code,
|
||||
expressCode,
|
||||
memo,
|
||||
meta,
|
||||
detail,
|
||||
packageIndex,
|
||||
});
|
||||
await saveRecord(ctx, meta, result, detail);
|
||||
|
||||
if (result.success) {
|
||||
try {
|
||||
await entry.update({
|
||||
status: ITEM_STATUS.SUCCESS,
|
||||
result_data: JSON.stringify(result),
|
||||
error_message: '',
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.error('[waybill.get] 保存订单级幂等结果失败 %s:%s', code, err.message);
|
||||
throw new Error(`订单 ${code} 已取号,但幂等结果保存失败;已阻止重复取号,请核实运单`);
|
||||
}
|
||||
} else if (meta.platformCallUncertain) {
|
||||
const errorMessage = `平台取号结果暂不确定:${result.message}`;
|
||||
await entry.update({ status: ITEM_STATUS.UNCERTAIN, error_message: errorMessage });
|
||||
return fail(code, errorMessage);
|
||||
} else {
|
||||
await entry.destroy();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单订单取号主流程(结果由 processItem 统一留痕)
|
||||
* 单订单取号主流程(结果由 processItemWithIdempotency 统一留痕)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} params 参数
|
||||
* @param {number} params.principalId 主体ID
|
||||
* @param {number} params.warehouseId 仓库ID
|
||||
* @param {string} params.code 发货单号
|
||||
* @param {string} params.expressCode 快递编码
|
||||
* @param {Object} params.item 订单项(可带 packageIndex 指定包裹序号)
|
||||
* @param {Map} params.memo 批内缓存
|
||||
* @param {Object} params.meta 留痕上下文(会被补齐)
|
||||
* @param {Object} params.detail 平台返回数据(raw / printinfo / signature)
|
||||
* @param {number} params.packageIndex 包裹序号
|
||||
* @return {Promise<Object>} 结果项
|
||||
*/
|
||||
async function callPlatform(ctx, { principalId, warehouseId, code, expressCode, item, memo, meta, detail }) {
|
||||
async function callPlatform(ctx, { principalId, warehouseId, code, expressCode, memo, meta, detail, packageIndex }) {
|
||||
try {
|
||||
const resolved = await orderCallback.resolveDeliveryBill(ctx, { code, principalId });
|
||||
const order = resolved.order;
|
||||
@ -571,17 +840,25 @@ async function callPlatform(ctx, { principalId, warehouseId, code, expressCode,
|
||||
// 1688 分销单被换算成抖音小店/淘宝后,取号域名仍要按原始平台(否则回读订单行查错域名)
|
||||
const extendProps = orderPlain.extend_props && typeof orderPlain.extend_props === 'object' ? orderPlain.extend_props : {};
|
||||
// 包裹序号:报文显式指定优先(拆单场景),否则按单号尾部 `_N` 推导
|
||||
const explicitIndex = pickPackageIndex(item);
|
||||
const packageIndex = explicitIndex === null ? resolvePackageIndex(code) : explicitIndex;
|
||||
const fetched = await platformService.fetchWaybillNo(orderPlain, {
|
||||
template: template.get ? template.get({ plain: true }) : template,
|
||||
expressCode,
|
||||
platformCode,
|
||||
originalPlatformCode: extendProps.original_platform_code || '',
|
||||
packageIndex,
|
||||
});
|
||||
let fetched;
|
||||
try {
|
||||
fetched = await platformService.fetchWaybillNo(orderPlain, {
|
||||
template: template.get ? template.get({ plain: true }) : template,
|
||||
expressCode,
|
||||
platformCode,
|
||||
originalPlatformCode: extendProps.original_platform_code || '',
|
||||
packageIndex,
|
||||
});
|
||||
} catch (err) {
|
||||
// 收到平台明确响应时允许重试;网络异常可能发生在平台已出号后,必须先核实避免重复消耗面单
|
||||
meta.platformCallUncertain = !err.rawResponse;
|
||||
throw err;
|
||||
}
|
||||
const waybill = normalizeWaybill(fetched);
|
||||
if (!waybill.waybill_code) return fail(code, '平台未返回运单号');
|
||||
if (!waybill.waybill_code) {
|
||||
meta.platformCallUncertain = true;
|
||||
return fail(code, '平台响应中未解析到运单号');
|
||||
}
|
||||
|
||||
// 面单打印数据原样保留:既要透传给 WMS,也要落取号记录备查
|
||||
detail.raw = fetched && fetched.raw ? fetched.raw : null;
|
||||
@ -673,22 +950,22 @@ async function getWaybills(ctx, { principalId, warehouseId, data, requestId }) {
|
||||
return { ok: false, message: `单次最多取号 ${MAX_BATCH} 单` };
|
||||
}
|
||||
|
||||
// 同一批内按账号缓存完整账号实例(含 cookie/token,供平台客户端直接使用),
|
||||
// 一次批量回调通常只涉及 1 个打单账号,避免逐单重复查库
|
||||
// 同一批内缓存打单账号与相同订单级幂等键的结果,避免重复查库或重复消耗面单
|
||||
const memo = new Map();
|
||||
const itemMemo = new Map();
|
||||
const results = await mapLimit(items, CONCURRENCY, item => processItem(ctx, {
|
||||
principalId,
|
||||
warehouseId,
|
||||
item,
|
||||
memo,
|
||||
itemMemo,
|
||||
requestId,
|
||||
}));
|
||||
const success = results.filter(row => row.success).length;
|
||||
return {
|
||||
ok: true,
|
||||
message: 'ok',
|
||||
// 有订单没取到号时不锁定 request_id:调用方用同一 request_id 重试会整批重跑,
|
||||
// 已取到号的单会复用打单平台订单上的运单号(不重复消耗面单),只补真正失败的单
|
||||
// 有订单没取到号时不锁定 request_id:订单级幂等记录负责复用已取到的单,只重试失败单
|
||||
replayable: success === results.length,
|
||||
data: {
|
||||
total: results.length,
|
||||
|
||||
@ -647,7 +647,12 @@ class QimenWmsClient {
|
||||
// itemId 优先取明细自带的 WMS 商品ID,其次按商品编码/OMS 商品ID 回查 warehouse_products.wms_item_id
|
||||
const mappedItemId = (i.item_code && wmsItemIdByItemCode[i.item_code])
|
||||
|| (productId != null ? wmsItemIdByProduct[productId] : undefined);
|
||||
const itemId = i.item_id != null && i.item_id !== '' ? Number(i.item_id) : mappedItemId;
|
||||
// itemId 优先用仓库映射(warehouse_products.wms_item_id),再看明细自带值;
|
||||
// 历史手工单曾把「系统商品ID」误存进 item_id,若该 ID 能在系统商品表里查到(productById),
|
||||
// 就不能当 WMS 商品ID 下发,否则 WMS 可能按 itemId 命中其它商品(仍会下发 itemCode 供降级匹配)
|
||||
const storedItemId = i.item_id != null && i.item_id !== '' ? Number(i.item_id) : null;
|
||||
const storedIsProductId = storedItemId != null && productById[storedItemId] != null;
|
||||
const itemId = mappedItemId != null ? Number(mappedItemId) : (storedIsProductId ? null : storedItemId);
|
||||
|
||||
const line = {
|
||||
orderLineNo: String(i.order_line_no == null || i.order_line_no === '' ? idx + 1 : i.order_line_no),
|
||||
|
||||
45
backend/app/model/orderSnCode.js
Normal file
45
backend/app/model/orderSnCode.js
Normal file
@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
const { ORDER_SN_TABLE } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 订单序列号(SN)关联表模型(order_sn_codes)
|
||||
*
|
||||
* WMS 回传发货确认(deliveryorder.confirm)时明细行可能带 `snList`,由
|
||||
* app/lib/orderSnCodes.js 解析后落到本表:一行一个 SN,`order_id` 指向 order_index.id
|
||||
* (订单在状态表之间流转时 ID 不变,故转表无需搬 SN)。订单查询按 SN 反查订单时
|
||||
* 走 `idx_osc_principal_sn`(principal_id + sn_code)。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderSnCode model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const OrderSnCode = app.model.define('order_sn_code', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' },
|
||||
order_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '订单ID(order_index.id,全局唯一)' },
|
||||
order_no: { type: STRING(50), comment: '订单号(冗余,便于排查 / 导出)' },
|
||||
order_line_no: { type: STRING(20), comment: '回传明细行号(orderLineNo)' },
|
||||
item_id: { type: BIGINT.UNSIGNED, comment: '商品ID(itemId)' },
|
||||
item_code: { type: STRING(100), comment: '商品编码(itemCode)' },
|
||||
item_name: { type: STRING(255), comment: '商品名称(itemName)' },
|
||||
package_code: { type: STRING(50), comment: '包裹号(packageCode)' },
|
||||
express_code: { type: STRING(50), comment: '运单号(expressCode)' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, comment: '仓库ID(app_key 定位到的仓库)' },
|
||||
sn_code: { type: STRING(255), allowNull: false, comment: '序列号(SN 原值,去空白;反查订单用)' },
|
||||
source: { type: STRING(20), allowNull: false, defaultValue: 'wms', comment: '来源:wms=仓库回传(预留手工补录)' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: ORDER_SN_TABLE,
|
||||
comment: '订单序列号(SN)关联表(WMS 发货确认回传的 snList)',
|
||||
});
|
||||
|
||||
OrderSnCode.associate = () => {
|
||||
app.model.OrderSnCode.belongsTo(app.model.OrderIndex, { foreignKey: 'order_id', as: 'order' });
|
||||
app.model.OrderSnCode.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return OrderSnCode;
|
||||
};
|
||||
30
backend/app/model/waybillFetchIdempotency.js
Normal file
30
backend/app/model/waybillFetchIdempotency.js
Normal file
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 按订单、快递编码和包裹序号保护取号结果,避免不同批次重试重复消耗面单。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} waybillFetchIdempotency model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, TINYINT, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const WaybillFetchIdempotency = app.model.define('waybill_fetch_idempotency', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体ID' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '仓库ID' },
|
||||
delivery_order_code: { type: STRING(100), allowNull: false, comment: 'OMS 发货单号' },
|
||||
express_code: { type: STRING(50), allowNull: false, comment: 'WMS 传入的快递编码' },
|
||||
package_index: { type: INTEGER.UNSIGNED, allowNull: false, comment: '包裹序号(0 基)' },
|
||||
request_id: { type: STRING(100), comment: '首次取号的 request_id' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '状态:0处理中 1成功 2结果待核实' },
|
||||
result_data: { type: TEXT('medium'), comment: '成功时完整的逐单返回结果(JSON)' },
|
||||
error_message: { type: TEXT, comment: '结果待核实时的原因' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: 'waybill_fetch_idempotencies',
|
||||
comment: '取号订单级幂等记录',
|
||||
});
|
||||
|
||||
return WaybillFetchIdempotency;
|
||||
};
|
||||
@ -3,14 +3,14 @@
|
||||
/**
|
||||
* 取号明细记录模型,对应 waybill_fetch_records。
|
||||
*
|
||||
* 每次 `deliveryorder.getwaybill` 逐单取号(成功/复用/失败)都写一条,保存打单平台的原始返回,
|
||||
* 以及需要透传给 WMS 的 `printinfo / signature`。
|
||||
* 每次实际调用平台取号都写一条,保存打单平台原始返回、完整结果及包裹序号。
|
||||
* 已有运单号的幂等重放不新增平台取号记录。
|
||||
* 仅做留痕,不参与业务状态流转(取号与订单表暂不关联)。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} waybillFetchRecord model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, TEXT, DATE } = app.Sequelize;
|
||||
const { BIGINT, STRING, INTEGER, TINYINT, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const WaybillFetchRecord = app.model.define('waybill_fetch_record', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
@ -19,6 +19,7 @@ module.exports = app => {
|
||||
request_id: { type: STRING(100), comment: '调用方 request_id' },
|
||||
delivery_order_code: { type: STRING(100), allowNull: false, comment: 'OMS 发货单号' },
|
||||
express_code: { type: STRING(50), comment: '本次取号的快递编码' },
|
||||
package_index: { type: INTEGER.UNSIGNED, comment: '包裹序号(0 基);历史记录可能为空' },
|
||||
platform_code: { type: STRING(50), comment: '订单来源平台编码' },
|
||||
account_id: { type: BIGINT.UNSIGNED, comment: '外部打单账号ID' },
|
||||
template_id: { type: STRING(100), comment: '面单模板ID' },
|
||||
@ -26,6 +27,7 @@ module.exports = app => {
|
||||
waybill_source: { type: STRING(20), comment: '运单号来源:express_print / platform_last' },
|
||||
waybill_code: { type: STRING(100), comment: '主运单号' },
|
||||
waybill_codes: { type: TEXT, comment: '全部运单号(JSON 数组)' },
|
||||
result_data: { type: TEXT('medium'), comment: '完整的逐单返回结果(JSON)' },
|
||||
printinfo: { type: TEXT('medium'), comment: '面单打印数据(平台原样返回)' },
|
||||
signature: { type: TEXT('medium'), comment: '面单签名(平台原样返回)' },
|
||||
print_history_ids: {
|
||||
|
||||
@ -4,7 +4,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { Service } = require('egg');
|
||||
const ExcelJS = require('exceljs');
|
||||
const { buildExportSql, STATUS_LABELS, TYPE_LABELS, formatDate } = require('../utils/exportDefs');
|
||||
const { buildExportSql, STATUS_LABELS, TYPE_LABELS, formatDate, EXPORT_TYPES } = require('../utils/exportDefs');
|
||||
|
||||
/** 任务状态:0待处理 1处理中 2已完成 3失败 */
|
||||
const STATUS = { PENDING: 0, PROCESSING: 1, COMPLETED: 2, FAILED: 3 };
|
||||
@ -164,6 +164,11 @@ class ExportTaskService extends Service {
|
||||
replacements,
|
||||
type: QueryTypes.SELECT,
|
||||
});
|
||||
// 类型自定义的补充列(如订单的序列号数量/列表):按当前 chunk 批量补齐,避免跨库方言差异
|
||||
const typeDef = EXPORT_TYPES[task.type];
|
||||
if (typeDef && typeof typeDef.decorateRows === 'function' && rows.length) {
|
||||
await typeDef.decorateRows(ctx, rows, { principalId: task.principal_id, filters });
|
||||
}
|
||||
for (const row of rows) {
|
||||
const vals = {};
|
||||
for (const c of columns) {
|
||||
|
||||
@ -20,6 +20,8 @@ const { resolveAccountName } = require('../lib/accountProfile');
|
||||
const { PLATFORM_PRESETS, platformNameOf, resolvePlatform } = require('../lib/platformCode');
|
||||
const { validateReceiver } = require('../lib/orderReceiver');
|
||||
const { validateItems } = require('../lib/orderDeliveryItems');
|
||||
const { findOrderIdsBySnCodes, listOrderSnCodes } = require('../lib/orderSnCodes');
|
||||
const { hasPlatformTrace } = require('../lib/orderPushItems');
|
||||
|
||||
/** 外部发货同步状态文案(与 service/externalSendSync.js 的 SEND_STATUS 对齐) */
|
||||
const EXTERNAL_SEND_STATUS_LABELS = {
|
||||
@ -402,6 +404,14 @@ class OrderStatusService extends Service {
|
||||
const platformOrderNos = parseFilterValues(p.platform_order_nos, 200).map(no => no.slice(0, 50));
|
||||
if (platformOrderNos.length) where.oaid_order_source_code = { [Op.in]: platformOrderNos };
|
||||
|
||||
// 序列号(SN)反查:WMS 回传时落到 order_sn_codes,多个精确匹配(逗号 / 换行分隔);
|
||||
// 先取命中的订单ID再回到状态表过滤,避免拼接超长 IN 子句,也便于走 idx_osc_principal_sn
|
||||
const snCodes = parseFilterValues(p.sn_codes, 200).map(code => code.slice(0, 255));
|
||||
if (snCodes.length) {
|
||||
const snOrderIds = await findOrderIdsBySnCodes(ctx, { principalId, snCodes });
|
||||
where.id = { [Op.in]: snOrderIds.length ? snOrderIds : [ -1 ] };
|
||||
}
|
||||
|
||||
// 所在公司权限:仅列出自己所属公司(货主)的订单
|
||||
const access = await this._scopeAccess(principalId);
|
||||
if (!access.isGroup) {
|
||||
@ -867,8 +877,8 @@ class OrderStatusService extends Service {
|
||||
async _assertItemsOwner(items, subsidiaryId, principalId) {
|
||||
const { ctx } = this;
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
// 明细既有新建订单的 item_id,也有历史排单口径的 product_id,两者都按商品校验
|
||||
const pickProductId = it => Number(it && (it.item_id != null && it.item_id !== '' ? it.item_id : it.product_id));
|
||||
// 明细既有新建订单(product_id)的口径,也有历史排单口径;优先按系统商品ID 校验
|
||||
const pickProductId = it => Number(it && (it.product_id != null && it.product_id !== '' ? it.product_id : it.item_id));
|
||||
const productIds = [ ...new Set(items.map(pickProductId).filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
const comboIds = [ ...new Set(items.map(it => Number(it && it.combo_product_id)).filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
if (!productIds.length && !comboIds.length) return;
|
||||
@ -979,9 +989,86 @@ class OrderStatusService extends Service {
|
||||
if (!Number(row.parse_status)) row.parse_status = Number(source.parse_status) || 0;
|
||||
return row;
|
||||
});
|
||||
await this._normalizeItemProductLinks(rows, principalId, transaction);
|
||||
return ctx.model.OrderStatusItem.bulkCreate(rows, { transaction });
|
||||
}
|
||||
|
||||
/**
|
||||
* 写库前补齐明细的「系统商品」关联(手工单 / 接口建单口径)
|
||||
*
|
||||
* 历史手工建单把**系统商品ID**存进了 item_id(该列本义是 WMS 商品ID),导致推送仓前校验
|
||||
* 与报文构造都要额外兼容。这里在写库时统一纠正:
|
||||
* - item_id 命中系统商品、且与行上的 item_code 一致 → 迁到 product_id,item_id 置空
|
||||
* - 无平台溯源信息(shop_product_id / platform_snapshot / outer_item_id 均为空)的明细,
|
||||
* item_code 唯一命中系统商品 → 补 product_id
|
||||
* - 补齐后补 item_type=1 / parse_status=1(视为已解析的系统商品)
|
||||
* 平台明细(带平台溯源)不做按编码兜底,避免绕过「店铺商品绑定」。
|
||||
* @param {Array<Object>} rows 待写入的明细行(原地修改)
|
||||
* @param {Number} principalId 主体ID
|
||||
* @param {Object} [transaction] 事务
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async _normalizeItemProductLinks(rows, principalId, transaction) {
|
||||
const { ctx } = this;
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
const pending = list.filter(row => !(Number(row.product_id) > 0) && !(Number(row.combo_product_id) > 0));
|
||||
const stray = list.filter(row => Number(row.item_id) > 0);
|
||||
if (!pending.length && !stray.length) return;
|
||||
|
||||
const ids = [ ...new Set(stray.map(row => Number(row.item_id)).filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
const codes = [ ...new Set(list.map(row => String(row.item_code == null ? '' : row.item_code).trim()).filter(Boolean)) ];
|
||||
if (!ids.length && !codes.length) return;
|
||||
|
||||
const or = [];
|
||||
if (ids.length) or.push({ id: { [Op.in]: ids } });
|
||||
if (codes.length) or.push({ item_code: { [Op.in]: codes } });
|
||||
const products = await ctx.model.Product.findAll({
|
||||
where: { principal_id: principalId, [Op.or]: or },
|
||||
attributes: [ 'id', 'item_code' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
if (!products.length) return;
|
||||
|
||||
const codeById = new Map();
|
||||
const productsByCode = new Map();
|
||||
for (const product of products) {
|
||||
const id = Number(product.id);
|
||||
const code = String(product.item_code == null ? '' : product.item_code).trim();
|
||||
if (Number.isInteger(id) && id > 0) codeById.set(id, code);
|
||||
if (!code) continue;
|
||||
if (!productsByCode.has(code)) productsByCode.set(code, []);
|
||||
productsByCode.get(code).push(id);
|
||||
}
|
||||
|
||||
const isLegacyProductId = row => {
|
||||
const legacyId = Number(row.item_id);
|
||||
const code = String(row.item_code == null ? '' : row.item_code).trim();
|
||||
return Number.isInteger(legacyId) && legacyId > 0 && code && codeById.get(legacyId) === code;
|
||||
};
|
||||
|
||||
for (const row of pending) {
|
||||
const code = String(row.item_code == null ? '' : row.item_code).trim();
|
||||
if (isLegacyProductId(row)) {
|
||||
row.product_id = Number(row.item_id);
|
||||
row.item_id = null;
|
||||
} else if (code && !hasPlatformTrace(row)) {
|
||||
const matched = productsByCode.get(code) || [];
|
||||
if (matched.length === 1) row.product_id = matched[0];
|
||||
}
|
||||
if (Number(row.product_id) > 0) {
|
||||
if (!Number(row.item_type)) row.item_type = 1;
|
||||
if (!Number(row.parse_status)) row.parse_status = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 已绑定系统商品的明细:item_id 若是历史误存的系统商品ID(与商品编码一致),置空避免当 WMS 商品ID 下发
|
||||
for (const row of list) {
|
||||
if (Number(row.product_id) > 0 && isLegacyProductId(row)) row.item_id = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装明细行(字段口径对齐 order_status_items:发货单明细 + 平台明细的超集)
|
||||
* @param {Object} raw 明细原始数据
|
||||
@ -1549,7 +1636,8 @@ class OrderStatusService extends Service {
|
||||
}
|
||||
}
|
||||
const items = await this.listItems({ order_id: row.id });
|
||||
return { order: plain, items: items.list };
|
||||
const snCodes = await listOrderSnCodes(ctx, { principalId, orderId: Number(row.id) });
|
||||
return { order: { ...plain, sn_codes: snCodes }, items: items.list };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -5,6 +5,7 @@ const QimenWmsClient = require('../lib/wms/qimenClient');
|
||||
const { ORDER_STATUS } = require('../lib/orderStatus');
|
||||
const { releaseOrderStock } = require('../utils/orderStock');
|
||||
const { getShopBasic, getAccountWithPlatform } = require('../lib/externalPrintConfig');
|
||||
const { findUnconvertibleItems, unconvertibleMessage } = require('../lib/orderPushItems');
|
||||
|
||||
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
|
||||
const PUSH_MAX_ATTEMPTS = 3;
|
||||
@ -98,24 +99,40 @@ class OrderWmsService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送前校验明细是否已完成「店铺商品 → 系统商品」转换
|
||||
* 推送前校验明细是否已落到「系统商品」
|
||||
*
|
||||
* 外部打单订单的明细在拉单时可能是未绑定状态(保留了平台商品编码),
|
||||
* 这类明细不能推给仓库:平台编码在 WMS 侧不存在,会建出脏商品或报错。
|
||||
* 判据不是「有没有 product_id」而是「能否解析到系统商品」(见 app/lib/orderPushItems.js):
|
||||
* - 平台拉单的明细必须完成「店铺商品 → 系统商品」绑定,否则推给仓库的会是平台编码;
|
||||
* - 手工单 / 接口建单的明细则直接选系统商品(历史数据把系统商品ID 存在 item_id),
|
||||
* 按主体商品库核对 ID / 编码即可,不能因为缺少店铺商品绑定而拦下。
|
||||
* @param {Object} order 订单(需含 principal_id)
|
||||
* @param {Array} items 明细(order_status_items,已展开为最小单位)
|
||||
* @return {string} 不通过原因,全部通过返回空串
|
||||
* @return {Promise<{ok: Boolean, message: String}>} 校验结果(不通过时 message 为原因)
|
||||
*/
|
||||
validateConvertedItems(items) {
|
||||
async validateConvertedItems(order, items) {
|
||||
const list = Array.isArray(items) ? items : [];
|
||||
if (!list.length) return '';
|
||||
const invalid = list.filter(item => !(Number(item.product_id) > 0) && !(Number(item.combo_product_id) > 0));
|
||||
if (!invalid.length) return '';
|
||||
const detail = invalid
|
||||
.slice(0, 5)
|
||||
.map(item => `第 ${item.order_line_no || '?'} 行 ${item.item_code || '(无编码)'}`)
|
||||
.join('、');
|
||||
return `明细商品未绑定系统商品(${detail}${invalid.length > 5 ? ` 等 ${invalid.length} 行` : ''}),无法推送:` +
|
||||
'请先在「店铺商品」把对应商品绑定到系统商品/组合商品(重新绑定会自动重建订单明细)';
|
||||
if (!list.length) return { ok: true, message: '' };
|
||||
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const ids = [ ...new Set(
|
||||
[ ...list.map(item => Number(item.product_id)), ...list.map(item => Number(item.item_id)) ]
|
||||
.filter(id => Number.isInteger(id) && id > 0)
|
||||
) ];
|
||||
const codes = [ ...new Set(list.map(item => String(item.item_code == null ? '' : item.item_code).trim()).filter(Boolean)) ];
|
||||
const or = [];
|
||||
if (ids.length) or.push({ id: { [Op.in]: ids } });
|
||||
if (codes.length) or.push({ item_code: { [Op.in]: codes } });
|
||||
|
||||
const products = or.length
|
||||
? await this.ctx.model.Product.findAll({
|
||||
where: { principal_id: order.principal_id, [Op.or]: or },
|
||||
attributes: [ 'id', 'item_code' ],
|
||||
raw: true,
|
||||
})
|
||||
: [];
|
||||
|
||||
const invalid = findUnconvertibleItems(list, products);
|
||||
return invalid.length ? { ok: false, message: unconvertibleMessage(invalid) } : { ok: true, message: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
@ -310,14 +327,14 @@ class OrderWmsService extends Service {
|
||||
const client = new QimenWmsClient(api, this.app);
|
||||
const items = itemRows.map(item => item.get({ plain: true }));
|
||||
|
||||
// 明细必须已完成「店铺商品 → 系统商品」转换,否则推给仓库的会是平台商品编码
|
||||
const unconverted = this.validateConvertedItems(items);
|
||||
if (unconverted) {
|
||||
// 明细必须能落到系统商品(平台订单需先绑定店铺商品;手工单按商品库核对),否则推给仓库的会是平台编码
|
||||
const itemCheck = await this.validateConvertedItems(order, items);
|
||||
if (!itemCheck.ok) {
|
||||
await order.update({
|
||||
wms_push_result: { ...base, success: false, failureKind: 'unbound_items', message: unconverted },
|
||||
wms_push_result: { ...base, success: false, failureKind: 'unbound_items', message: itemCheck.message },
|
||||
});
|
||||
ctx.logger.warn(`[order-wms] ${order.order_no} 推送中止:${unconverted}`);
|
||||
return { ok: false, retry: false, fatal: true, message: unconverted, attempts };
|
||||
ctx.logger.warn(`[order-wms] ${order.order_no} 推送中止:${itemCheck.message}`);
|
||||
return { ok: false, retry: false, fatal: true, message: itemCheck.message, attempts };
|
||||
}
|
||||
|
||||
const wmsItemIds = await this.resolveWmsItemIds(order, items);
|
||||
|
||||
@ -178,6 +178,27 @@ function jsonText(value) {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列号列表 → 可读文本(兼容数组 / JSON 字符串 / 逗号分隔字符串)
|
||||
* @param {*} value 原值
|
||||
* @return {string} 用「、」连接后的文本
|
||||
*/
|
||||
function snListText(value) {
|
||||
if (blank(value)) return '';
|
||||
let list = value;
|
||||
if (typeof list === 'string') {
|
||||
const text = list.trim();
|
||||
if (!text) return '';
|
||||
if (text.startsWith('[')) {
|
||||
try { list = JSON.parse(text); } catch { list = text.split(','); }
|
||||
} else {
|
||||
list = text.split(',');
|
||||
}
|
||||
}
|
||||
if (Array.isArray(list)) return list.map(item => String(item == null ? '' : item).trim()).filter(Boolean).join('、');
|
||||
return String(list);
|
||||
}
|
||||
|
||||
/* 日期边界:只写到天(YYYY-MM-DD)时补 00:00:00 / 23:59:59 */
|
||||
function dateBound(value, isEnd) {
|
||||
const text = String(value).trim();
|
||||
@ -257,13 +278,16 @@ function applyBillOwnerScope(wh, ctx, column) {
|
||||
* @param {Object} options 组装参数
|
||||
* @param {string} options.from FROM 子句
|
||||
* @param {Object} options.wh makeWhere() 结果
|
||||
* @param {Array} options.columns 列定义
|
||||
* @param {Array} options.columns 导出列定义(含仅由 decorateRows 补值的列)
|
||||
* @param {Array} [options.selectColumns] SQL 实际查询的列(缺省等于 columns)
|
||||
* @param {string} [options.orderBy] 排序(默认 id DESC)
|
||||
* @param {Array} [options.leadRepl] 排在 WHERE 参数之前的参数(如 UNION 各分支的主体ID)
|
||||
* @return {{sql: string, countSql: string, columns: Array, replacements: Array}} 查询语句与列定义
|
||||
*/
|
||||
function buildResult({ from, wh, columns, orderBy = 'id DESC', leadRepl = [] }) {
|
||||
const select = columns.map(c => (c.expr ? `${c.expr} AS ${c.key}` : c.key)).join(', ');
|
||||
function buildResult({ from, wh, columns, selectColumns, orderBy = 'id DESC', leadRepl = [] }) {
|
||||
// selectColumns:SQL 真正查询的列(缺省同 columns);columns 仍是导出列定义(可含仅由 decorateRows 补值的列)
|
||||
const list = selectColumns || columns;
|
||||
const select = list.map(c => (c.expr ? `${c.expr} AS ${c.key}` : c.key)).join(', ');
|
||||
const base = `SELECT ${select} FROM ${from}${wh.sql()}`;
|
||||
return {
|
||||
sql: `${base} ORDER BY ${orderBy}`,
|
||||
@ -293,7 +317,11 @@ const ORDER_COLUMNS = [{ key: 'id', header: 'ID' },
|
||||
{ key: 'shop_id', header: '店铺ID' },
|
||||
{ key: 'shop_nick', header: '店铺名称' },
|
||||
{ key: 'source_platform_name', header: '电商平台' },
|
||||
{ key: 'subsidiary_name', header: '货主' },
|
||||
{
|
||||
key: 'subsidiary_name',
|
||||
header: '货主',
|
||||
expr: '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id)',
|
||||
},
|
||||
{ key: 'warehouse_id', header: '仓库ID' },
|
||||
{ key: 'warehouse_code', header: '仓库编码' },
|
||||
{ key: 'receiver', header: '收货人' },
|
||||
@ -310,6 +338,10 @@ const ORDER_COLUMNS = [{ key: 'id', header: 'ID' },
|
||||
{ key: 'logistics_name', header: '物流公司名称' },
|
||||
{ key: 'express_code', header: '运单号' },
|
||||
{ key: 'express_codes', header: '运单号集合', format: jsonText },
|
||||
// 仓库回传的序列号(order_sn_codes):SQL 不查,由 decorateRows 按 chunk 补值
|
||||
// (MySQL 5.7 在 UNION/派生表里对「嵌套派生表的相关子查询」会报 Unknown column 't.id')
|
||||
{ key: 'sn_count', header: '序列号数量' },
|
||||
{ key: 'sn_codes', header: '序列号列表', format: snListText },
|
||||
{ key: 'wms_status', header: 'WMS状态' },
|
||||
{ key: 'wms_order_no', header: 'WMS单号' },
|
||||
// 回传外部打单平台(配送视图/配送异常视图关注;其它状态表同名字段恒为默认值)
|
||||
@ -323,6 +355,109 @@ const ORDER_COLUMNS = [{ key: 'id', header: 'ID' },
|
||||
{ key: 'remark', header: '备注' },
|
||||
];
|
||||
|
||||
/** 订单级序列号列(导出含明细时改用明细级 SN,避免与明细列重名) */
|
||||
const ORDER_SN_COLUMN_KEYS = [ 'sn_count', 'sn_codes' ];
|
||||
|
||||
/** 订单导出 SQL 真正查询的列(去掉只靠 decorateRows 补值的序列号列) */
|
||||
const ORDER_SELECT_COLUMNS = ORDER_COLUMNS.filter(c => !ORDER_SN_COLUMN_KEYS.includes(c.key));
|
||||
|
||||
/** 明细级序列号列(同样由 decorateRows 补值) */
|
||||
const ITEM_SN_COLUMN_KEYS = [ 'item_sn_count', 'item_sn_codes' ];
|
||||
|
||||
/**
|
||||
* 订单含明细(export_mode=item)的列:订单字段 + 明细字段 + 明细级序列号
|
||||
* 订单字段从内层查询结果(别名 o)按列名取,明细字段取 order_status_items(别名 oi)
|
||||
*/
|
||||
const ORDER_ITEM_COLUMNS = [
|
||||
...ORDER_SELECT_COLUMNS.map(c => ({ ...c, expr: `o.${c.key}` })),
|
||||
{ key: 'order_line_no', header: '行号', expr: 'oi.order_line_no' },
|
||||
{ key: 'item_code', header: '商品编码', expr: 'oi.item_code' },
|
||||
{ key: 'item_name', header: '商品名称', expr: 'oi.item_name' },
|
||||
{ key: 'sku_code', header: '商家编码', expr: 'oi.sku_code' },
|
||||
{ key: 'spec', header: '规格', expr: 'oi.spec' },
|
||||
{ key: 'plan_qty', header: '数量', expr: 'oi.plan_qty' },
|
||||
{ key: 'actual_price', header: '单价', expr: 'oi.actual_price' },
|
||||
{ key: 'line_amount', header: '金额', expr: 'ROUND(IFNULL(oi.plan_qty, 0) * IFNULL(oi.actual_price, 0), 2)' },
|
||||
{ key: 'inventory_type', header: '库存类型', expr: 'oi.inventory_type', format: value => (value === 'CC' ? '残次' : '正品') },
|
||||
{ key: 'outer_item_id', header: '平台商品ID', expr: 'oi.outer_item_id' },
|
||||
{
|
||||
key: 'parse_status',
|
||||
header: '解析状态',
|
||||
expr: 'oi.parse_status',
|
||||
format: labels({ 0: '未解析', 1: '已解析', 2: '解析失败' }),
|
||||
},
|
||||
{ key: 'item_sn_count', header: '序列号数量' },
|
||||
{ key: 'item_sn_codes', header: '序列号列表', format: snListText },
|
||||
];
|
||||
|
||||
/** 订单含明细导出真正查询的列(去掉靠 decorateRows 补值的明细级序列号列) */
|
||||
const ORDER_ITEM_SELECT_COLUMNS = ORDER_ITEM_COLUMNS.filter(c => !ITEM_SN_COLUMN_KEYS.includes(c.key));
|
||||
|
||||
/**
|
||||
* 订单导出补充序列号列(每个 chunk 查询后按订单ID批量取 SN 再回填)
|
||||
*
|
||||
* 不在 SQL 里做聚合的原因是 MySQL 5.7 对「派生表 + 相关子查询 + 嵌套派生表(JSON_ARRAYAGG)」会报
|
||||
* `Unknown column 't.id' in 'where clause'`,且 GROUP_CONCAT 受 group_concat_max_len 截断。
|
||||
* 这里按当前 chunk 的订单ID批量查 order_sn_codes,纯 JS 分组:
|
||||
* - 订单行模式:每行填 sn_count / sn_codes(该订单全部 SN)
|
||||
* - 含明细模式:每行填 item_sn_count / item_sn_codes(按行号匹配,行号为空的回传记录按商品编码兜底)
|
||||
* @param {Object} ctx egg context(需含 model.query)
|
||||
* @param {Array<Object>} rows 当前 chunk 的查询结果(原地补值)
|
||||
* @param {Object} options 参数
|
||||
* @param {Number} options.principalId 主体ID
|
||||
* @param {Object} [options.filters] 导出筛选(含 export_mode)
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function decorateOrderRows(ctx, rows, { principalId, filters } = {}) {
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
if (!list.length) return;
|
||||
const ids = [ ...new Set(list.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
if (!ids.length) return;
|
||||
|
||||
const QueryTypes = ctx.model.QueryTypes || {};
|
||||
const snRows = await ctx.model.query(
|
||||
'SELECT order_id, order_line_no, item_code, sn_code FROM order_sn_codes ' +
|
||||
'WHERE principal_id = ? AND order_id IN (?) ORDER BY order_id, id',
|
||||
{ replacements: [ principalId, ids ], type: QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
const byOrder = new Map();
|
||||
const byLine = new Map();
|
||||
const byCode = new Map();
|
||||
const push = (map, key, value) => {
|
||||
if (!map.has(key)) map.set(key, []);
|
||||
map.get(key).push(value);
|
||||
};
|
||||
for (const row of snRows) {
|
||||
const orderId = Number(row.order_id);
|
||||
const sn = String(row.sn_code == null ? '' : row.sn_code).trim();
|
||||
if (!sn) continue;
|
||||
push(byOrder, orderId, sn);
|
||||
const lineNo = String(row.order_line_no == null ? '' : row.order_line_no).trim();
|
||||
const itemCode = String(row.item_code == null ? '' : row.item_code).trim();
|
||||
if (lineNo) push(byLine, `${orderId}|${lineNo}`, sn);
|
||||
else if (itemCode) push(byCode, `${orderId}|${itemCode}`, sn);
|
||||
}
|
||||
|
||||
const exportMode = String((filters && filters.export_mode) || '').trim() === 'item' ? 'item' : 'order';
|
||||
for (const row of list) {
|
||||
const orderId = Number(row.id);
|
||||
if (exportMode === 'item') {
|
||||
const lineNo = String(row.order_line_no == null ? '' : row.order_line_no).trim();
|
||||
const itemCode = String(row.item_code == null ? '' : row.item_code).trim();
|
||||
const sns = byLine.get(`${orderId}|${lineNo}`)
|
||||
|| (itemCode ? byCode.get(`${orderId}|${itemCode}`) : null)
|
||||
|| [];
|
||||
row.item_sn_count = sns.length;
|
||||
row.item_sn_codes = sns;
|
||||
} else {
|
||||
const sns = byOrder.get(orderId) || [];
|
||||
row.sn_count = sns.length;
|
||||
row.sn_codes = sns;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 入库单列 */
|
||||
const INBOUND_COLUMNS = [
|
||||
{ key: 'id', header: 'ID' },
|
||||
@ -758,6 +893,7 @@ const EXPORT_TYPES = {
|
||||
{ key: 'parent_order_no', label: '来源订单号', type: 'text', placeholder: '支持模糊匹配' },
|
||||
{ key: 'platform_codes', label: '电商平台', type: 'select', options: PLATFORM_TYPE_OPTIONS, multiple: true },
|
||||
{ key: 'platform_order_nos', label: '平台单号', type: 'text', placeholder: '多个用英文逗号分隔(精确匹配)' },
|
||||
{ key: 'sn_codes', label: '序列号', type: 'text', placeholder: '多个用英文逗号分隔(精确匹配,反查订单)' },
|
||||
{ key: 'receiver', label: '收货人', type: 'text' },
|
||||
{ key: 'address', label: '收货地址', type: 'text' },
|
||||
{ key: 'remark', label: '备注', type: 'text' },
|
||||
@ -781,14 +917,25 @@ const EXPORT_TYPES = {
|
||||
{ key: 'archived_from', label: '归档时间起', type: 'date' },
|
||||
{ key: 'archived_to', label: '归档时间止', type: 'date' },
|
||||
{ key: 'exclude_unbound', label: '排除含未绑定商品的订单', type: 'select', options: [{ value: '1', label: '是' }] },
|
||||
{
|
||||
key: 'export_mode',
|
||||
label: '导出内容',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ value: 'order', label: '订单行(不含明细)' },
|
||||
{ value: 'item', label: '订单含明细(每商品一行)' },
|
||||
],
|
||||
placeholder: '默认订单行(不含明细)',
|
||||
},
|
||||
{ key: 'ids', label: '选中订单ID', type: 'text', hidden: true, placeholder: '页面「导出选中」时传入' },
|
||||
],
|
||||
build: (f, ctx) => {
|
||||
// 导出内容:order=一行一个订单(不含明细);item=一行一个商品明细(订单字段重复填充)
|
||||
const exportMode = String(f.export_mode || '').trim() === 'item' ? 'item' : 'order';
|
||||
// 订单按状态分表存储:指定状态时只查对应表,未指定时 UNION ALL 各状态表
|
||||
const stages = ORDER_TABLE_BY_STATUS[f.order_stage] ? [ f.order_stage ] : ORDER_STATUS_ORDER;
|
||||
const select = ORDER_COLUMNS
|
||||
.map(c => (c.key === 'subsidiary_name'
|
||||
? '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id) AS subsidiary_name'
|
||||
: c.key))
|
||||
const select = ORDER_SELECT_COLUMNS
|
||||
.map(c => (c.expr ? `${c.expr} AS ${c.key}` : c.key))
|
||||
.join(', ');
|
||||
// 所在公司权限:只能导出自己所属公司(货主)的订单,条件写进各状态表子查询
|
||||
const ownIds = ctx.access && !ctx.access.isGroup ? (ctx.access.ownCompanyIds || []).map(Number) : null;
|
||||
@ -798,7 +945,11 @@ const EXPORT_TYPES = {
|
||||
const inner = stages.map(stage => {
|
||||
const table = ORDER_TABLE_BY_STATUS[stage];
|
||||
const archived = stage === ORDER_STATUS.HISTORY ? 't.archived_at' : 'NULL AS archived_at';
|
||||
return `SELECT ${select}, ${archived} FROM ${table} t WHERE t.principal_id = ?${scopeSql}`;
|
||||
// 外层筛选/关联要用的列(不在导出表里展示):
|
||||
// - principal_id:含明细模式关联 order_status_items
|
||||
// - source_platform_code:电商平台筛选(选列里只有平台名称,没有编码)
|
||||
const extra = ', t.principal_id AS principal_id, t.source_platform_code AS source_platform_code';
|
||||
return `SELECT ${select}${extra}, ${archived} FROM ${table} t WHERE t.principal_id = ?${scopeSql}`;
|
||||
}).join(' UNION ALL ');
|
||||
const wh = makeWhere();
|
||||
wh.like('order_no', f.order_no)
|
||||
@ -816,6 +967,16 @@ const EXPORT_TYPES = {
|
||||
// 电商平台(多选)与平台单号(多个精确匹配),与列表接口同口径
|
||||
whereIn(wh, 't.source_platform_code', csvValues(f.platform_codes, 50).map(code => code.toUpperCase()));
|
||||
whereIn(wh, 't.oaid_order_source_code', csvValues(f.platform_order_nos, 200));
|
||||
// 序列号(SN)反查:与列表接口同口径,命中 order_sn_codes 的订单才导出
|
||||
const snCodes = csvValues(f.sn_codes, 200);
|
||||
if (snCodes.length) {
|
||||
wh.raw(
|
||||
'EXISTS (SELECT 1 FROM order_sn_codes osc WHERE osc.order_id = t.id AND osc.principal_id = ? ' +
|
||||
`AND osc.sn_code IN (${snCodes.map(() => '?').join(',')}))`,
|
||||
ctx.principalId,
|
||||
...snCodes
|
||||
);
|
||||
}
|
||||
// 外部发货同步状态(配送视图/配送异常视图用:0待同步 1已同步 2待重试 3异常,支持逗号多选)
|
||||
const sendStatuses = csvValues(f.external_send_status, 10)
|
||||
.map(value => Number(value))
|
||||
@ -827,15 +988,41 @@ const EXPORT_TYPES = {
|
||||
`AND oi.principal_id = ${Number(ctx.principalId)} AND oi.parse_status = 2)`
|
||||
);
|
||||
}
|
||||
// 导出选中:页面勾选的行按订单ID(order_index.id)精确过滤,与筛选条件同时生效
|
||||
const selectedIds = csvValues(f.ids, 500)
|
||||
.map(value => Number(value))
|
||||
.filter(id => Number.isInteger(id) && id > 0);
|
||||
if (selectedIds.length) whereIn(wh, 't.id', selectedIds);
|
||||
|
||||
const stageRepl = stages.flatMap(() => (ownIds && ownIds.length
|
||||
? [ ctx.principalId, ...ownIds ]
|
||||
: [ ctx.principalId ]));
|
||||
|
||||
if (exportMode === 'item') {
|
||||
// 含明细:先按条件收敛订单,再 JOIN 明细表;订单级筛选条件留在子查询里,避免列名歧义
|
||||
const orderPart = `(SELECT * FROM (${inner}) AS t${wh.sql()}) AS o`;
|
||||
return buildResult({
|
||||
columns: ORDER_ITEM_COLUMNS,
|
||||
selectColumns: ORDER_ITEM_SELECT_COLUMNS,
|
||||
from: `${orderPart} JOIN order_status_items oi ON oi.order_id = o.id AND oi.principal_id = o.principal_id`,
|
||||
// 条件已在子查询内生效,外层不再追加,但 WHERE 参数需跟在订单参数之后
|
||||
wh: makeWhere(),
|
||||
orderBy: 'o.id DESC, oi.order_line_no ASC, oi.id ASC',
|
||||
leadRepl: [ ...stageRepl, ...wh.replacements ],
|
||||
});
|
||||
}
|
||||
|
||||
return buildResult({
|
||||
columns: ORDER_COLUMNS,
|
||||
// 外层只按列名取值(计算列已在子查询算好);序列号列由 decorateRows 补值,不进 SQL
|
||||
selectColumns: ORDER_SELECT_COLUMNS.map(c => ({ ...c, expr: undefined })),
|
||||
from: `(${inner}) AS t`,
|
||||
wh,
|
||||
leadRepl: stages.flatMap(() => (ownIds && ownIds.length
|
||||
? [ ctx.principalId, ...ownIds ]
|
||||
: [ ctx.principalId ])),
|
||||
leadRepl: stageRepl,
|
||||
});
|
||||
},
|
||||
/** 每个 chunk 查询后补充序列号数量/列表(见 decorateOrderRows) */
|
||||
decorateRows: decorateOrderRows,
|
||||
},
|
||||
|
||||
inbound_order: {
|
||||
@ -1037,7 +1224,7 @@ const EXPORT_TYPES = {
|
||||
{ key: 'bind_type', label: '绑定类型', type: 'select', options: BIND_TYPE_OPTIONS },
|
||||
{ key: 'status', label: '状态', type: 'select', options: ENABLE_OPTIONS },
|
||||
{ key: 'has_unbound_order', label: '只看有订单未绑定', type: 'select', options: [{ value: '1', label: '是' }] },
|
||||
{ key: 'keyword', label: '关键词', type: 'text', placeholder: '标题 / 平台商品ID / 规格ID / 商家编码' },
|
||||
{ key: 'keyword', label: '关键词', type: 'text', placeholder: '标题 / 平台商品ID / 规格ID / 商家编码 / 规格' },
|
||||
],
|
||||
build: (f, ctx) => {
|
||||
const wh = makeWhere();
|
||||
@ -1045,7 +1232,7 @@ const EXPORT_TYPES = {
|
||||
.eq('t.shop_id', f.shop_id)
|
||||
.eq('t.bind_type', f.bind_type)
|
||||
.eq('t.status', f.status)
|
||||
.kw([ 't.title', 't.outer_item_id', 't.outer_sku_id', 't.outer_code' ], f.keyword);
|
||||
.kw([ 't.title', 't.outer_item_id', 't.outer_sku_id', 't.outer_code', 't.spec' ], f.keyword);
|
||||
// 多值筛选:店铺 / 平台类型 / 商家编码(与列表接口同口径)
|
||||
whereIn(wh, 't.shop_id', csvValues(f.shop_ids).map(Number).filter(id => Number.isInteger(id) && id > 0));
|
||||
whereIn(wh, 't.platform_type', csvValues(f.platform_types));
|
||||
@ -1325,4 +1512,6 @@ module.exports = {
|
||||
cleanFilters,
|
||||
listExportTypeSchema,
|
||||
formatDate,
|
||||
snListText,
|
||||
decorateOrderRows,
|
||||
};
|
||||
|
||||
@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单序列号(SN)关联表 order_sn_codes
|
||||
*
|
||||
* 背景:WMS 回传发货确认(deliveryorder.confirm)时,明细行可能带 `snList`(序列号列表)。
|
||||
* OMS 原先把确认报文整体存进订单的 `wms_push_result.confirm`(JSON,无法按 SN 反查),
|
||||
* 现改为**另存关联表**:一行一个 SN,带行号 / 商品 / 包裹 / 运单号,供订单查询按 SN 反查订单。
|
||||
*
|
||||
* 归属口径:
|
||||
* - `order_id` = order_index.id(订单全局唯一 ID;订单在状态表之间流转时不变,因此转表不用搬 SN)
|
||||
* - `principal_id` 冗余主体,查询按「主体 + SN」走索引
|
||||
* - 一条 SN 可能在同一订单里重复回传(WMS 重推),由唯一键 `uk_osc_order_sn` 兜底去重
|
||||
*
|
||||
* 幂等:showAllTables 判断表是否存在。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = tables
|
||||
.map(t => (typeof t === 'string' ? t : (t.tableName || t.TABLE_NAME)))
|
||||
.includes('order_sn_codes');
|
||||
if (exists) return;
|
||||
|
||||
const { BIGINT, STRING, DATE } = Sequelize;
|
||||
await queryInterface.createTable('order_sn_codes', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' },
|
||||
order_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '订单ID(order_index.id,全局唯一;流转状态表不变)' },
|
||||
order_no: { type: STRING(50), allowNull: true, comment: '订单号(冗余,便于排查 / 导出)' },
|
||||
order_line_no: { type: STRING(20), allowNull: true, comment: '回传明细行号(orderLineNo)' },
|
||||
item_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '商品ID(itemId)' },
|
||||
item_code: { type: STRING(100), allowNull: true, comment: '商品编码(itemCode)' },
|
||||
item_name: { type: STRING(255), allowNull: true, comment: '商品名称(itemName)' },
|
||||
package_code: { type: STRING(50), allowNull: true, comment: '包裹号(packages.package.packageCode)' },
|
||||
express_code: { type: STRING(50), allowNull: true, comment: '运单号(packages.package.expressCode)' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '仓库ID(app_key 定位到的仓库)' },
|
||||
sn_code: { type: STRING(255), allowNull: false, comment: '序列号(SN 原值,去空白;反查订单用)' },
|
||||
source: { type: STRING(20), allowNull: false, defaultValue: 'wms', comment: '来源:wms=仓库回传(预留手工补录)' },
|
||||
created_at: { type: DATE, allowNull: true, comment: '创建时间' },
|
||||
updated_at: { type: DATE, allowNull: true, comment: '更新时间' },
|
||||
}, {
|
||||
comment: '订单序列号(SN)关联表(WMS 发货确认回传的 snList)',
|
||||
charset: 'utf8mb4',
|
||||
collate: 'utf8mb4_unicode_ci',
|
||||
});
|
||||
|
||||
// 反查订单:principal_id + sn_code(订单列表按 SN 多值精确匹配)
|
||||
await queryInterface.addIndex('order_sn_codes', [ 'principal_id', 'sn_code' ], {
|
||||
name: 'idx_osc_principal_sn',
|
||||
});
|
||||
await queryInterface.addIndex('order_sn_codes', [ 'order_id' ], {
|
||||
name: 'idx_osc_order',
|
||||
});
|
||||
// 同一订单重复回传同一 SN 时由唯一键兜底去重(代码层已先过滤,这里防并发)
|
||||
await queryInterface.addIndex('order_sn_codes', [ 'principal_id', 'order_id', 'sn_code' ], {
|
||||
name: 'uk_osc_order_sn',
|
||||
unique: true,
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = tables
|
||||
.map(t => (typeof t === 'string' ? t : (t.tableName || t.TABLE_NAME)))
|
||||
.includes('order_sn_codes');
|
||||
if (exists) await queryInterface.dropTable('order_sn_codes');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为取号增加订单级幂等键,并在取号历史中保存包裹序号与完整返回结果。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('waybill_fetch_records', 'package_index', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '包裹序号(0 基);历史记录可能为空',
|
||||
after: 'express_code',
|
||||
});
|
||||
await queryInterface.addColumn('waybill_fetch_records', 'result_data', {
|
||||
type: Sequelize.TEXT('medium'),
|
||||
allowNull: true,
|
||||
comment: '完整的逐单返回结果(JSON)',
|
||||
after: 'waybill_codes',
|
||||
});
|
||||
|
||||
await queryInterface.createTable('waybill_fetch_idempotencies', {
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '主体ID' },
|
||||
warehouse_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '仓库ID' },
|
||||
delivery_order_code: { type: Sequelize.STRING(100), allowNull: false, comment: 'OMS 发货单号' },
|
||||
express_code: { type: Sequelize.STRING(50), allowNull: false, comment: 'WMS 传入的快递编码' },
|
||||
package_index: { type: Sequelize.INTEGER.UNSIGNED, allowNull: false, comment: '包裹序号(0 基)' },
|
||||
request_id: { type: Sequelize.STRING(100), allowNull: true, comment: '首次取号的 request_id' },
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '状态:0处理中 1成功 2结果待核实',
|
||||
},
|
||||
result_data: { type: Sequelize.TEXT('medium'), allowNull: true, comment: '成功时完整的逐单返回结果(JSON)' },
|
||||
error_message: { type: Sequelize.TEXT, allowNull: true, comment: '结果待核实时的原因' },
|
||||
created_at: { type: Sequelize.DATE, allowNull: true, comment: '创建时间' },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: true, comment: '更新时间' },
|
||||
});
|
||||
|
||||
await queryInterface.addIndex('waybill_fetch_idempotencies', [
|
||||
'principal_id',
|
||||
'warehouse_id',
|
||||
'delivery_order_code',
|
||||
'express_code',
|
||||
'package_index',
|
||||
], {
|
||||
unique: true,
|
||||
name: 'uk_waybill_fetch_idempotency',
|
||||
});
|
||||
await queryInterface.addIndex('waybill_fetch_records', [
|
||||
'principal_id',
|
||||
'warehouse_id',
|
||||
'delivery_order_code',
|
||||
'express_code',
|
||||
'package_index',
|
||||
'status',
|
||||
], {
|
||||
name: 'idx_waybill_fetch_idempotency_lookup',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeIndex('waybill_fetch_records', 'idx_waybill_fetch_idempotency_lookup');
|
||||
await queryInterface.dropTable('waybill_fetch_idempotencies');
|
||||
await queryInterface.removeColumn('waybill_fetch_records', 'result_data');
|
||||
await queryInterface.removeColumn('waybill_fetch_records', 'package_index');
|
||||
},
|
||||
};
|
||||
162
backend/test/app/lib/exportDefsOrder.test.js
Normal file
162
backend/test/app/lib/exportDefsOrder.test.js
Normal file
@ -0,0 +1,162 @@
|
||||
'use strict';
|
||||
|
||||
const { assert } = require('egg-mock/bootstrap');
|
||||
const { buildExportSql, cleanFilters } = require('../../../app/utils/exportDefs');
|
||||
|
||||
/** 集团账号(不受货主范围限制) */
|
||||
const GROUP_ACCESS = { isGroup: true, ownCompanyIds: [] };
|
||||
|
||||
describe('test/app/lib/exportDefsOrder.test.js', () => {
|
||||
it('默认导出一行一个订单:不含明细列,带序列号数量/列表(SN 由 decorateRows 补值,不进 SQL)', () => {
|
||||
const { sql, columns } = buildExportSql('order', { order_stage: 'pending' }, 5, 1, GROUP_ACCESS);
|
||||
const headers = columns.map(c => c.header);
|
||||
assert(headers.includes('序列号数量'));
|
||||
assert(headers.includes('序列号列表'));
|
||||
assert(!headers.includes('行号'));
|
||||
assert(!headers.includes('商家编码'));
|
||||
// MySQL 5.7 兼容:不在 SQL 里做 SN 聚合(派生表 + 嵌套派生表的相关子查询会报 Unknown column 't.id')
|
||||
assert(!sql.includes('JSON_ARRAYAGG'));
|
||||
assert(!sql.includes('order_sn_codes'));
|
||||
assert(!sql.includes('JOIN order_status_items'));
|
||||
// 内层固定补齐筛选/关联要用的列,但不输出到导出表
|
||||
assert(sql.includes('t.source_platform_code AS source_platform_code'));
|
||||
});
|
||||
|
||||
it('订单含明细:JOIN 明细表,一行一个商品并带明细级序列号列', () => {
|
||||
const { sql, columns, replacements } = buildExportSql(
|
||||
'order',
|
||||
{ order_stage: 'pending', export_mode: 'item' },
|
||||
5,
|
||||
1,
|
||||
GROUP_ACCESS
|
||||
);
|
||||
const headers = columns.map(c => c.header);
|
||||
assert(headers.includes('行号'));
|
||||
assert(headers.includes('商品编码'));
|
||||
assert(headers.includes('序列号数量'));
|
||||
assert(sql.includes('JOIN order_status_items oi ON oi.order_id = o.id'));
|
||||
assert(sql.includes('oi.order_line_no'));
|
||||
assert(sql.includes('t.principal_id AS principal_id'), '内层需带 principal_id 供关联明细');
|
||||
assert(sql.includes('ORDER BY o.id DESC'));
|
||||
assert(!sql.includes('item_sn_count'), '明细级 SN 由 decorateRows 补值,不进 SQL');
|
||||
assert.deepEqual(replacements, [ 5 ]);
|
||||
});
|
||||
|
||||
it('导出选中:ids 转成订单ID过滤,与筛选条件同时生效', () => {
|
||||
const { sql, replacements } = buildExportSql(
|
||||
'order',
|
||||
{ order_stage: 'delivery', ids: '11, 22,abc' },
|
||||
5,
|
||||
1,
|
||||
GROUP_ACCESS
|
||||
);
|
||||
assert(sql.includes('t.id IN (?,?)'), '非法ID被丢弃,只保留两个有效ID');
|
||||
assert.deepEqual(replacements, [ 5, 11, 22 ]);
|
||||
});
|
||||
|
||||
it('含明细 + 条件:订单条件留在子查询内,参数顺序为订单→条件', () => {
|
||||
const { sql, replacements } = buildExportSql(
|
||||
'order',
|
||||
{ order_stage: 'delivery', export_mode: 'item', order_no: 'A1', ids: '9' },
|
||||
7,
|
||||
1,
|
||||
GROUP_ACCESS
|
||||
);
|
||||
// 条件子查询在内层 `AS t WHERE ...`,外层只做 JOIN;参数按 WHERE 中占位顺序:订单→条件→选中ID
|
||||
assert(sql.includes(') AS t WHERE'));
|
||||
assert(sql.includes(') AS o JOIN order_status_items oi'));
|
||||
assert.deepEqual(replacements, [ 7, '%A1%', 9 ]);
|
||||
});
|
||||
|
||||
it('所在公司权限:内层子查询追加 subsidiary_id 过滤,参数顺序保持一致', () => {
|
||||
const { sql, replacements } = buildExportSql(
|
||||
'order',
|
||||
{ order_stage: 'pending', ids: '3' },
|
||||
5,
|
||||
1,
|
||||
{ isGroup: false, ownCompanyIds: [ 4, 7 ] }
|
||||
);
|
||||
assert(sql.includes('t.subsidiary_id IN (?,?)'));
|
||||
assert.deepEqual(replacements, [ 5, 4, 7, 3 ]);
|
||||
});
|
||||
|
||||
it('订单行 + 平台筛选:内层补齐 source_platform_code,避免外层 WHERE 找不到列', () => {
|
||||
const { sql } = buildExportSql('order', { platform_codes: 'tb,pdd' }, 5, 1, GROUP_ACCESS);
|
||||
assert(sql.includes('t.source_platform_code AS source_platform_code'));
|
||||
assert(sql.includes('t.source_platform_code IN (?,?)'));
|
||||
});
|
||||
|
||||
it('cleanFilters 保留 export_mode / ids,丢弃未声明字段', () => {
|
||||
const filters = cleanFilters('order', { export_mode: 'item', ids: '1,2', unknown: 'x', order_no: '' });
|
||||
assert.deepEqual(filters, { export_mode: 'item', ids: '1,2' });
|
||||
});
|
||||
|
||||
it('ids 标记为 hidden,不进入通用导出表单', () => {
|
||||
const def = require('../../../app/utils/exportDefs').EXPORT_TYPES.order;
|
||||
const idsField = def.filters.find(f => f.key === 'ids');
|
||||
assert(idsField && idsField.hidden === true);
|
||||
});
|
||||
|
||||
describe('decorateRows(序列号回填)', () => {
|
||||
/**
|
||||
* 造一个只返回固定 SN 行的假 ctx
|
||||
* @param {Array<Object>} snRows 让 model.query 返回的 SN 行
|
||||
* @return {Object} 含 calls / model 的假上下文
|
||||
*/
|
||||
function fakeCtx(snRows) {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
model: {
|
||||
QueryTypes: { SELECT: 'SELECT' },
|
||||
query: async (sql, options) => { calls.push({ sql, options }); return snRows; },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it('订单行模式:按订单ID汇总 SN 数量与列表', async () => {
|
||||
const { decorateOrderRows } = require('../../../app/utils/exportDefs');
|
||||
const ctx = fakeCtx([
|
||||
{ order_id: 1, order_line_no: '1', item_code: 'A', sn_code: 'SN1' },
|
||||
{ order_id: 1, order_line_no: '2', item_code: 'B', sn_code: 'SN2' },
|
||||
{ order_id: 2, order_line_no: null, item_code: 'C', sn_code: 'SN3' },
|
||||
]);
|
||||
const rows = [{ id: 1 }, { id: 2 }, { id: 3 }];
|
||||
await decorateOrderRows(ctx, rows, { principalId: 9, filters: { export_mode: 'order' } });
|
||||
|
||||
assert(rows[0].sn_count === 2);
|
||||
assert(rows[0].sn_codes.join(',') === 'SN1,SN2');
|
||||
assert(rows[1].sn_count === 1);
|
||||
assert(rows[2].sn_count === 0, '无 SN 的订单数量为 0');
|
||||
assert.deepEqual(ctx.calls[0].options.replacements, [ 9, [ 1, 2, 3 ]]);
|
||||
});
|
||||
|
||||
it('含明细模式:按行号匹配,行号为空的回传记录按商品编码兜底', async () => {
|
||||
const { decorateOrderRows } = require('../../../app/utils/exportDefs');
|
||||
const ctx = fakeCtx([
|
||||
{ order_id: 1, order_line_no: '1', item_code: 'A', sn_code: 'SN1' },
|
||||
{ order_id: 1, order_line_no: null, item_code: 'B', sn_code: 'SN2' },
|
||||
]);
|
||||
const rows = [
|
||||
{ id: 1, order_line_no: '1', item_code: 'A' },
|
||||
{ id: 1, order_line_no: '2', item_code: 'B' },
|
||||
{ id: 1, order_line_no: '3', item_code: 'C' },
|
||||
];
|
||||
await decorateOrderRows(ctx, rows, { principalId: 9, filters: { export_mode: 'item' } });
|
||||
|
||||
assert(rows[0].item_sn_count === 1);
|
||||
assert(rows[0].item_sn_codes[0] === 'SN1');
|
||||
assert(rows[1].item_sn_count === 1, '行号为空的 SN 按商品编码挂到对应行');
|
||||
assert(rows[1].item_sn_codes[0] === 'SN2');
|
||||
assert(rows[2].item_sn_count === 0);
|
||||
});
|
||||
|
||||
it('空数据 / 无订单ID时不查库', async () => {
|
||||
const { decorateOrderRows } = require('../../../app/utils/exportDefs');
|
||||
const ctx = fakeCtx([]);
|
||||
await decorateOrderRows(ctx, [], { principalId: 9 });
|
||||
await decorateOrderRows(ctx, [{ id: null }], { principalId: 9 });
|
||||
assert(ctx.calls.length === 0);
|
||||
});
|
||||
});
|
||||
});
|
||||
73
backend/test/app/lib/orderPushItems.test.js
Normal file
73
backend/test/app/lib/orderPushItems.test.js
Normal file
@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
const { assert } = require('egg-mock/bootstrap');
|
||||
const { findUnconvertibleItems, unconvertibleMessage, hasPlatformTrace } = require('../../../app/lib/orderPushItems');
|
||||
|
||||
const PRODUCTS = [
|
||||
{ id: 4, item_code: 'P260911231515227608' },
|
||||
{ id: 24, item_code: 'P261105011902808526' },
|
||||
{ id: 30, item_code: 'tbcs111' },
|
||||
];
|
||||
|
||||
describe('test/app/lib/orderPushItems.test.js', () => {
|
||||
it('已绑定系统商品 / 组合拆分子行可推送', () => {
|
||||
const items = [
|
||||
{ order_line_no: '1', product_id: 4, item_code: 'P260911231515227608' },
|
||||
{ order_line_no: '2', product_id: 24, combo_product_id: 9, item_code: 'P261105011902808526' },
|
||||
];
|
||||
assert(findUnconvertibleItems(items, PRODUCTS).length === 0);
|
||||
});
|
||||
|
||||
it('平台未绑定明细(带平台溯源、平台编码)不可推送', () => {
|
||||
const items = [
|
||||
{ order_line_no: '1', shop_product_id: 1466, item_code: 'wf-C05速干定型喷雾420*3+排骨梳*1', parse_status: 2 },
|
||||
];
|
||||
const invalid = findUnconvertibleItems(items, PRODUCTS);
|
||||
assert(invalid.length === 1);
|
||||
const message = unconvertibleMessage(invalid);
|
||||
assert(message.includes('第 1 行'));
|
||||
assert(message.includes('店铺商品'));
|
||||
});
|
||||
|
||||
it('历史手工单:item_id 存系统商品ID 且编码一致 → 可推送', () => {
|
||||
const items = [{ order_line_no: '1', item_id: 24, item_code: 'P261105011902808526' }];
|
||||
assert(findUnconvertibleItems(items, PRODUCTS).length === 0);
|
||||
});
|
||||
|
||||
it('item_id 不能凭商品ID 放行,编码必须命中系统商品', () => {
|
||||
const wrong = [{ order_line_no: '1', item_id: 4, item_code: 'NOT-EXIST' }];
|
||||
assert(findUnconvertibleItems(wrong, PRODUCTS).length === 1);
|
||||
const byCode = [{ order_line_no: '1', item_id: 4, item_code: 'P261105011902808526' }];
|
||||
assert(findUnconvertibleItems(byCode, PRODUCTS).length === 0);
|
||||
});
|
||||
|
||||
it('手工单只有商品编码且命中系统商品 → 可推送', () => {
|
||||
const items = [{ order_line_no: '1', item_code: 'tbcs111' }];
|
||||
assert(findUnconvertibleItems(items, PRODUCTS).length === 0);
|
||||
});
|
||||
|
||||
it('带平台溯源的明细即使编码命中系统商品也不放行(必须先绑定店铺商品)', () => {
|
||||
const items = [
|
||||
{ order_line_no: '1', item_code: 'tbcs111', shop_product_id: 1382 },
|
||||
{ order_line_no: '2', item_code: 'tbcs111', platform_snapshot: { item_code: 'tbcs111' } },
|
||||
{ order_line_no: '3', item_code: 'tbcs111', outer_item_id: '10000202451115' },
|
||||
];
|
||||
const invalid = findUnconvertibleItems(items, PRODUCTS);
|
||||
assert(invalid.length === 3);
|
||||
});
|
||||
|
||||
it('product_id 不属于本主体商品库时按编码兜底(带平台溯源的仍拦下)', () => {
|
||||
const items = [{ order_line_no: '1', product_id: 999, item_code: 'P260911231515227608' }];
|
||||
assert(findUnconvertibleItems(items, PRODUCTS).length === 0);
|
||||
const platform = [{ order_line_no: '1', product_id: 999, item_code: 'P260911231515227608', shop_product_id: 1 }];
|
||||
assert(findUnconvertibleItems(platform, PRODUCTS).length === 1);
|
||||
});
|
||||
|
||||
it('hasPlatformTrace 只看平台溯源字段', () => {
|
||||
assert(hasPlatformTrace({ shop_product_id: 1 }));
|
||||
assert(hasPlatformTrace({ platform_snapshot: {} }));
|
||||
assert(hasPlatformTrace({ outer_item_id: 'x' }));
|
||||
assert(!hasPlatformTrace({ item_code: 'x' }));
|
||||
assert(!hasPlatformTrace(null));
|
||||
});
|
||||
});
|
||||
89
backend/test/app/lib/orderSnCodes.test.js
Normal file
89
backend/test/app/lib/orderSnCodes.test.js
Normal file
@ -0,0 +1,89 @@
|
||||
'use strict';
|
||||
|
||||
const { assert } = require('egg-mock/bootstrap');
|
||||
const { extractSnEntries } = require('../../../app/lib/orderSnCodes');
|
||||
|
||||
describe('test/app/lib/orderSnCodes.test.js', () => {
|
||||
it('解析明细行 snList(字符串数组)并带行号/商品信息', () => {
|
||||
const entries = extractSnEntries({
|
||||
lines: [
|
||||
{
|
||||
orderLineNo: '1',
|
||||
itemCode: 'SKU-SN-001',
|
||||
itemId: '162678',
|
||||
itemName: '序列号商品A',
|
||||
snList: [
|
||||
'HTTPS://SUYUAN.HULIANZAOWU.COM/PRODUCT?Q=YGP9213002516455',
|
||||
'6977752010196',
|
||||
],
|
||||
},
|
||||
{ orderLineNo: '2', itemCode: 'SKU-NORMAL-002', snList: [] },
|
||||
],
|
||||
});
|
||||
|
||||
assert(entries.length === 2);
|
||||
assert(entries[0].sn_code === 'HTTPS://SUYUAN.HULIANZAOWU.COM/PRODUCT?Q=YGP9213002516455');
|
||||
assert(entries[0].order_line_no === '1');
|
||||
assert(entries[0].item_code === 'SKU-SN-001');
|
||||
assert(entries[0].item_id === 162678);
|
||||
assert(entries[1].sn_code === '6977752010196');
|
||||
// 包裹维度字段在行级 SN 上为空
|
||||
assert(entries[0].package_code === null);
|
||||
assert(entries[0].express_code === null);
|
||||
});
|
||||
|
||||
it('解析包裹内商品的 snList,并带包裹号/运单号', () => {
|
||||
const entries = extractSnEntries({
|
||||
packages: [
|
||||
{
|
||||
packageCode: 'PK-20261113-0001',
|
||||
expressCode: 'YT1234567890123',
|
||||
items: [{ itemCode: 'SKU-SN-002', itemId: 162672, snList: [ 'SN-A', 'SN-B' ] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert(entries.length === 2);
|
||||
assert(entries[0].package_code === 'PK-20261113-0001');
|
||||
assert(entries[0].express_code === 'YT1234567890123');
|
||||
assert(entries[0].item_code === 'SKU-SN-002');
|
||||
assert(entries.map(entry => entry.sn_code).join(',') === 'SN-A,SN-B');
|
||||
});
|
||||
|
||||
it('兼容 snCodes 逗号分隔 / 对象数组 / snCode 单值', () => {
|
||||
const entries = extractSnEntries({
|
||||
lines: [
|
||||
{ orderLineNo: '1', snCodes: 'SN1,SN2;SN3' },
|
||||
{ orderLineNo: '2', snList: [{ snCode: 'SN4' }, { sn: 'SN5' }] },
|
||||
{ orderLineNo: '3', snCode: 'SN6' },
|
||||
],
|
||||
});
|
||||
|
||||
assert(entries.map(entry => entry.sn_code).join(',') === 'SN1,SN2,SN3,SN4,SN5,SN6');
|
||||
});
|
||||
|
||||
it('同一 SN 在行级与包裹级重复出现时只留一条(不区分大小写)', () => {
|
||||
const entries = extractSnEntries({
|
||||
lines: [{ orderLineNo: '1', itemCode: 'SKU-A', snList: [ 'sn-x' ] }],
|
||||
packages: [{ packageCode: 'PK-1', items: [{ itemCode: 'SKU-A', snList: [ 'SN-X' ] }] }],
|
||||
});
|
||||
|
||||
assert(entries.length === 1);
|
||||
assert(entries[0].sn_code === 'sn-x');
|
||||
assert(entries[0].package_code === null);
|
||||
});
|
||||
|
||||
it('无 SN / 空报文返回空数组', () => {
|
||||
const blankLine = { snList: [ ' ' ] };
|
||||
assert(extractSnEntries({}).length === 0);
|
||||
assert(extractSnEntries({ lines: [{ orderLineNo: '1', snList: [] }] }).length === 0);
|
||||
assert(extractSnEntries({ lines: [ null, 'x', blankLine ] }).length === 0);
|
||||
});
|
||||
|
||||
it('单次回传条数上限 2000', () => {
|
||||
const snList = Array.from({ length: 2100 }, (_, index) => `SN-${index}`);
|
||||
const entries = extractSnEntries({ lines: [{ orderLineNo: '1', snList }] });
|
||||
assert(entries.length === 2000);
|
||||
assert(entries[1999].sn_code === 'SN-1999');
|
||||
});
|
||||
});
|
||||
53
backend/test/app/lib/qimenDeliveryItemId.test.js
Normal file
53
backend/test/app/lib/qimenDeliveryItemId.test.js
Normal file
@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
const { assert } = require('egg-mock/bootstrap');
|
||||
const QimenWmsClient = require('../../../app/lib/wms/qimenClient');
|
||||
|
||||
/** 构造一个不触网的客户端(只测报文构造) */
|
||||
function buildClient() {
|
||||
return new QimenWmsClient({ base_url: 'http://127.0.0.1:1', app_key: 'k', app_secret: 's' });
|
||||
}
|
||||
|
||||
describe('test/app/lib/qimenDeliveryItemId.test.js', () => {
|
||||
it('历史手工单的 item_id(系统商品ID)不会作为 WMS itemId 下发', () => {
|
||||
const client = buildClient();
|
||||
const payload = client._buildDeliveryOrder(
|
||||
{ delivery_order_code: 'FH_473', order_type: 'JYCK' },
|
||||
[{ order_line_no: '1', item_id: 24, item_code: 'P261105011902808526', plan_qty: 1, actual_price: 1 }],
|
||||
{
|
||||
productById: { 24: { item_code: 'P261105011902808526', item_name: '1' } },
|
||||
wmsItemIdByItemCode: { P261105011902808526: 1001163 },
|
||||
wmsItemIdByProduct: {},
|
||||
}
|
||||
);
|
||||
const line = payload.orderLines.orderLine[0];
|
||||
assert(line.itemCode === 'P261105011902808526');
|
||||
assert(line.itemId === 1001163);
|
||||
});
|
||||
|
||||
it('item_id 是真正的 WMS 商品ID(商品库无此ID)时仍按明细下发', () => {
|
||||
const client = buildClient();
|
||||
const payload = client._buildDeliveryOrder(
|
||||
{ delivery_order_code: 'FH_1', order_type: 'JYCK' },
|
||||
[{ order_line_no: '1', item_id: 777001, item_code: 'P-NO-LINK', plan_qty: 1, actual_price: 1 }],
|
||||
{ productById: {}, wmsItemIdByItemCode: {}, wmsItemIdByProduct: {} }
|
||||
);
|
||||
const line = payload.orderLines.orderLine[0];
|
||||
assert(line.itemId === 777001);
|
||||
});
|
||||
|
||||
it('已绑定系统商品时优先用仓库映射的 WMS 商品ID', () => {
|
||||
const client = buildClient();
|
||||
const payload = client._buildDeliveryOrder(
|
||||
{ delivery_order_code: 'FH_1', order_type: 'JYCK' },
|
||||
[{ order_line_no: '1', product_id: 24, item_id: 999, item_code: 'P261105011902808526', plan_qty: 1, actual_price: 1 }],
|
||||
{
|
||||
productById: { 24: { item_code: 'P261105011902808526', item_name: '1' } },
|
||||
wmsItemIdByItemCode: {},
|
||||
wmsItemIdByProduct: { 24: 1001163 },
|
||||
}
|
||||
);
|
||||
const line = payload.orderLines.orderLine[0];
|
||||
assert(line.itemId === 1001163);
|
||||
});
|
||||
});
|
||||
274
backend/test/app/lib/waybillGet.test.js
Normal file
274
backend/test/app/lib/waybillGet.test.js
Normal file
@ -0,0 +1,274 @@
|
||||
'use strict';
|
||||
|
||||
const { app, assert } = require('egg-mock/bootstrap');
|
||||
const mm = require('egg-mock');
|
||||
const orderCallback = require('../../../app/lib/orderCallback');
|
||||
const waybillGet = require('../../../app/lib/waybillGet');
|
||||
|
||||
const PRINCIPAL_ID = 5;
|
||||
const WAREHOUSE_ID = 8;
|
||||
const DELIVERY_ORDER_CODE = 'dgj-550598429043014280';
|
||||
|
||||
function makeEntry(data) {
|
||||
const entry = {
|
||||
...data,
|
||||
update: async values => Object.assign(entry, values),
|
||||
destroy: async () => {},
|
||||
};
|
||||
return entry;
|
||||
}
|
||||
|
||||
function setupContext({ entries = [], legacyRecord = null, waybillCode = 'WB-NEW', fetchError = null } = {}) {
|
||||
const ctx = app.mockContext();
|
||||
const fetchedKeys = [];
|
||||
const platformRoutes = [];
|
||||
let platformCalls = 0;
|
||||
|
||||
ctx.model.WaybillFetchIdempotency.findOne = async ({ where }) =>
|
||||
entries.find(entry => Object.keys(where).every(key => entry[key] === where[key])) || null;
|
||||
ctx.model.WaybillFetchIdempotency.create = async data => {
|
||||
const duplicate = entries.find(entry =>
|
||||
[ 'principal_id', 'warehouse_id', 'delivery_order_code', 'express_code', 'package_index' ]
|
||||
.every(key => entry[key] === data[key]));
|
||||
if (duplicate) throw new Error('unique key conflict');
|
||||
const entry = makeEntry(data);
|
||||
entries.push(entry);
|
||||
return entry;
|
||||
};
|
||||
ctx.model.WaybillFetchRecord.findOne = async options => {
|
||||
fetchedKeys.push(options.where);
|
||||
return legacyRecord;
|
||||
};
|
||||
ctx.model.WaybillFetchRecord.create = async () => {};
|
||||
ctx.service.cache.getShopBasic = async () => ({
|
||||
id: 10,
|
||||
principal_id: PRINCIPAL_ID,
|
||||
type: 2,
|
||||
external_print_account_id: 12,
|
||||
});
|
||||
ctx.model.Shop.findByPk = async () => ({
|
||||
toJSON: () => ({
|
||||
id: 10,
|
||||
principal_id: PRINCIPAL_ID,
|
||||
type: 2,
|
||||
external_print_account_id: 12,
|
||||
}),
|
||||
});
|
||||
ctx.model.ExternalPrintAccount.findOne = async () => ({
|
||||
id: 12,
|
||||
platform: { code: 'TEST_PLATFORM', name: 'Test platform', fetch_waybill_no: 1 },
|
||||
get: () => ({ id: 12, platform: { code: 'TEST_PLATFORM', name: 'Test platform' } }),
|
||||
});
|
||||
ctx.service.externalPrintExpressInterface.resolveByCode = async () => ({
|
||||
template_id: 'template-1',
|
||||
get: () => ({ template_id: 'template-1' }),
|
||||
});
|
||||
ctx.service.externalPrintOrder.createPlatformService = account => {
|
||||
platformRoutes.push(account.platform.code);
|
||||
return {
|
||||
needFetchWaybillNo: true,
|
||||
fetchWaybillNo: async () => {
|
||||
platformCalls += 1;
|
||||
if (fetchError) throw fetchError;
|
||||
return { waybill_code: waybillCode, printinfo: 'print-data' };
|
||||
},
|
||||
};
|
||||
};
|
||||
mm(orderCallback, 'resolveDeliveryBill', async () => ({
|
||||
isNewModel: false,
|
||||
order: {
|
||||
warehouse_id: WAREHOUSE_ID,
|
||||
status: 1,
|
||||
source_platform_code: 'KS',
|
||||
shop_id: 10,
|
||||
get: () => ({
|
||||
warehouse_id: WAREHOUSE_ID,
|
||||
status: 1,
|
||||
source_platform_code: 'KS',
|
||||
shop_id: 10,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
return { ctx, entries, fetchedKeys, platformRoutes, get platformCalls() { return platformCalls; } };
|
||||
}
|
||||
|
||||
function requestItem(overrides = {}) {
|
||||
return {
|
||||
deliveryOrderCode: DELIVERY_ORDER_CODE,
|
||||
expressCode: 'STO',
|
||||
packageIndex: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function requestBody(item) {
|
||||
return { request: { orders: [ item ], request_id: `request-${Date.now()}` } };
|
||||
}
|
||||
|
||||
describe('lib/waybillGet 订单级幂等', () => {
|
||||
afterEach(() => mm.restore());
|
||||
|
||||
it('同订单、快递和包裹序号直接重放数据库中的完整结果', async () => {
|
||||
const savedResult = {
|
||||
delivery_order_code: DELIVERY_ORDER_CODE,
|
||||
success: true,
|
||||
message: 'ok',
|
||||
express_code: 'STO',
|
||||
package_index: 0,
|
||||
waybill_code: 'WB-SAVED',
|
||||
waybill_codes: [ 'WB-SAVED' ],
|
||||
printinfo: 'saved-print-data',
|
||||
key: 'saved-key',
|
||||
};
|
||||
const entry = makeEntry({
|
||||
principal_id: PRINCIPAL_ID,
|
||||
warehouse_id: WAREHOUSE_ID,
|
||||
delivery_order_code: DELIVERY_ORDER_CODE,
|
||||
express_code: 'STO',
|
||||
package_index: 0,
|
||||
status: 1,
|
||||
result_data: JSON.stringify(savedResult),
|
||||
});
|
||||
const state = setupContext({ entries: [ entry ] });
|
||||
|
||||
const result = await waybillGet.getWaybills(state.ctx, {
|
||||
principalId: PRINCIPAL_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
data: requestBody(requestItem()),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result.data.results[0], savedResult);
|
||||
assert.strictEqual(state.platformRoutes.length, 0);
|
||||
assert.strictEqual(state.fetchedKeys.length, 0);
|
||||
});
|
||||
|
||||
it('同一批里的重复订单项只调用一次平台并复用结果', async () => {
|
||||
const state = setupContext();
|
||||
const item = requestItem();
|
||||
|
||||
const result = await waybillGet.getWaybills(state.ctx, {
|
||||
principalId: PRINCIPAL_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
data: { request: { orders: [ item, { ...item }] } },
|
||||
});
|
||||
|
||||
assert.strictEqual(result.data.success, 2);
|
||||
assert.strictEqual(result.data.results[0].waybill_code, 'WB-NEW');
|
||||
assert.strictEqual(result.data.results[1].waybill_code, 'WB-NEW');
|
||||
assert.strictEqual(state.platformRoutes.length, 1);
|
||||
});
|
||||
|
||||
it('相同订单但快递编码不同会按订单当前平台路由重新取号', async () => {
|
||||
const state = setupContext();
|
||||
|
||||
const result = await waybillGet.getWaybills(state.ctx, {
|
||||
principalId: PRINCIPAL_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
data: requestBody(requestItem({ expressCode: 'ZTO' })),
|
||||
});
|
||||
|
||||
assert.strictEqual(result.data.results[0].waybill_code, 'WB-NEW');
|
||||
assert.strictEqual(state.platformRoutes[0], 'TEST_PLATFORM');
|
||||
assert.strictEqual(state.entries[0].express_code, 'ZTO');
|
||||
});
|
||||
|
||||
it('相同订单和快递但包裹序号不同会独立取号', async () => {
|
||||
const state = setupContext();
|
||||
|
||||
const result = await waybillGet.getWaybills(state.ctx, {
|
||||
principalId: PRINCIPAL_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
data: requestBody(requestItem({ packageIndex: 1 })),
|
||||
});
|
||||
|
||||
assert.strictEqual(result.data.results[0].package_index, 1);
|
||||
assert.strictEqual(state.entries[0].package_index, 1);
|
||||
assert.strictEqual(state.platformRoutes[0], 'TEST_PLATFORM');
|
||||
});
|
||||
|
||||
it('另一请求已有相同订单键正在处理时不重复调用平台', async () => {
|
||||
const state = setupContext({
|
||||
entries: [ makeEntry({
|
||||
principal_id: PRINCIPAL_ID,
|
||||
warehouse_id: WAREHOUSE_ID,
|
||||
delivery_order_code: DELIVERY_ORDER_CODE,
|
||||
express_code: 'STO',
|
||||
package_index: 0,
|
||||
status: 0,
|
||||
}) ],
|
||||
});
|
||||
|
||||
const result = await waybillGet.getWaybills(state.ctx, {
|
||||
principalId: PRINCIPAL_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
data: requestBody(requestItem()),
|
||||
});
|
||||
|
||||
assert.strictEqual(result.data.results[0].success, false);
|
||||
assert.match(result.data.results[0].message, /正在处理中/);
|
||||
assert.strictEqual(state.platformRoutes.length, 0);
|
||||
});
|
||||
|
||||
it('并发的不同 request_id 由数据库唯一键仲裁,只执行一次平台取号', async () => {
|
||||
const state = setupContext();
|
||||
const makePayload = requestId => ({
|
||||
principalId: PRINCIPAL_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
data: { request: { orders: [ requestItem() ], request_id: requestId } },
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
waybillGet.getWaybills(state.ctx, makePayload('request-a')),
|
||||
waybillGet.getWaybills(state.ctx, makePayload('request-b')),
|
||||
]);
|
||||
|
||||
assert.strictEqual(state.platformCalls, 1);
|
||||
assert.strictEqual(state.entries.length, 1);
|
||||
assert.strictEqual(state.entries[0].status, 1);
|
||||
});
|
||||
|
||||
it('平台请求超时后标记结果待核实,后续重试不再次消耗面单', async () => {
|
||||
const state = setupContext({ fetchError: new Error('platform request timeout') });
|
||||
const payload = {
|
||||
principalId: PRINCIPAL_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
data: requestBody(requestItem()),
|
||||
};
|
||||
|
||||
const first = await waybillGet.getWaybills(state.ctx, payload);
|
||||
const second = await waybillGet.getWaybills(state.ctx, payload);
|
||||
|
||||
assert.strictEqual(first.data.results[0].success, false);
|
||||
assert.match(first.data.results[0].message, /结果暂不确定/);
|
||||
assert.strictEqual(second.data.results[0].success, false);
|
||||
assert.match(second.data.results[0].message, /待核实/);
|
||||
assert.strictEqual(state.platformCalls, 1);
|
||||
assert.strictEqual(state.entries[0].status, 2);
|
||||
});
|
||||
|
||||
it('首次命中旧取号记录时回填幂等结果,不再调用平台', async () => {
|
||||
const state = setupContext({
|
||||
legacyRecord: {
|
||||
waybill_code: 'WB-LEGACY',
|
||||
waybill_codes: '["WB-LEGACY"]',
|
||||
waybill_source: 'express_print',
|
||||
printinfo: 'legacy-print-data',
|
||||
signature: 'legacy-signature',
|
||||
print_history_ids: '[]',
|
||||
cai_niao_auth_info_id: 123,
|
||||
platform_code: 'KS',
|
||||
},
|
||||
});
|
||||
|
||||
const result = await waybillGet.getWaybills(state.ctx, {
|
||||
principalId: PRINCIPAL_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
data: requestBody(requestItem()),
|
||||
});
|
||||
|
||||
assert.strictEqual(result.data.results[0].waybill_code, 'WB-LEGACY');
|
||||
assert.strictEqual(result.data.results[0].printinfo, 'legacy-print-data');
|
||||
assert.strictEqual(state.platformRoutes.length, 0);
|
||||
assert.strictEqual(state.entries[0].status, 1);
|
||||
});
|
||||
});
|
||||
@ -33,6 +33,8 @@ export interface ExportFilterDef {
|
||||
placeholder?: string
|
||||
/** 是否多选:多选值提交时按英文逗号拼接(如店铺/平台类型) */
|
||||
multiple?: boolean
|
||||
/** 不在通用「新建导出」表单里展示(如 ids:由列表页「导出选中」自动携带) */
|
||||
hidden?: boolean
|
||||
}
|
||||
|
||||
/** 导出任务状态:0待处理 1处理中 2已完成 3失败 */
|
||||
|
||||
@ -164,6 +164,23 @@ export interface OrderStatusItem {
|
||||
/** 仅历史视图 */
|
||||
archived_at?: string | null
|
||||
transferred_at?: string | null
|
||||
/** 序列号(SN)列表(仅详情返回;WMS 发货确认回传的 snList) */
|
||||
sn_codes?: OrderStatusSnCode[]
|
||||
}
|
||||
|
||||
/** 订单序列号(SN)行(order_sn_codes) */
|
||||
export interface OrderStatusSnCode {
|
||||
id: number
|
||||
order_id: number
|
||||
order_line_no?: string | null
|
||||
item_id?: number | null
|
||||
item_code?: string | null
|
||||
item_name?: string | null
|
||||
package_code?: string | null
|
||||
express_code?: string | null
|
||||
sn_code: string
|
||||
source?: string | null
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface OrderStatusQuery {
|
||||
@ -176,6 +193,8 @@ export interface OrderStatusQuery {
|
||||
receiver?: string
|
||||
address?: string
|
||||
remark?: string
|
||||
/** 序列号(SN):多个精确匹配,逗号分隔 */
|
||||
sn_codes?: string
|
||||
created_from?: string
|
||||
created_to?: string
|
||||
archived_from?: string
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useExportTasks } from '@/composables/useExportTasks'
|
||||
import type { ExportFilters, ExportType } from '@/api/exportTask'
|
||||
|
||||
@ -8,6 +9,10 @@ import type { ExportFilters, ExportType } from '@/api/exportTask'
|
||||
*
|
||||
* 用法:<ExportButton type="product" :filters="exportFilters" />
|
||||
* 点击后按当前页面筛选条件提交导出任务,完成时自动下载(逻辑见 composables/useExportTasks)。
|
||||
*
|
||||
* 订单导出(type="order")额外提供两个维度,提交前弹窗选择:
|
||||
* - 范围:导出选中的 N 条(按订单ID) / 按当前筛选条件导出全部
|
||||
* - 内容:订单行(一行一个订单,不含明细) / 订单含明细(一行一个商品,订单字段重复填充,带每行序列号)
|
||||
*/
|
||||
|
||||
const props = withDefaults(
|
||||
@ -22,20 +27,55 @@ const props = withDefaults(
|
||||
size?: 'large' | 'default' | 'small'
|
||||
/** 是否朴素按钮(列表页次级操作) */
|
||||
plain?: boolean
|
||||
/** 列表当前勾选的记录ID(订单导出「导出选中」用) */
|
||||
selectedIds?: number[]
|
||||
}>(),
|
||||
{
|
||||
filters: () => ({}),
|
||||
label: '导出',
|
||||
size: 'default',
|
||||
plain: false,
|
||||
selectedIds: () => [],
|
||||
},
|
||||
)
|
||||
|
||||
/** 单次导出选中最多条数(与后端 ids 白名单上限一致) */
|
||||
const MAX_SELECTED = 500
|
||||
|
||||
const { submitting, submit } = useExportTasks()
|
||||
const text = computed(() => props.label)
|
||||
|
||||
/** 订单导出走弹窗(区分范围与内容),其它类型点一下直接按条件导出 */
|
||||
const isOrderExport = computed(() => props.type === 'order')
|
||||
const dialogVisible = ref(false)
|
||||
const scope = ref<'selected' | 'filtered'>('filtered')
|
||||
const mode = ref<'order' | 'item'>('order')
|
||||
|
||||
const selectedCount = computed(() => (props.selectedIds || []).length)
|
||||
|
||||
function handleClick() {
|
||||
submit(props.type, props.filters || {})
|
||||
if (!isOrderExport.value) {
|
||||
submit(props.type, props.filters || {})
|
||||
return
|
||||
}
|
||||
// 有勾选时默认导出选中,否则默认按条件全部
|
||||
scope.value = selectedCount.value ? 'selected' : 'filtered'
|
||||
mode.value = 'order'
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
async function confirmOrderExport() {
|
||||
const filters: ExportFilters = { ...(props.filters || {}), export_mode: mode.value }
|
||||
if (scope.value === 'selected') {
|
||||
const ids = (props.selectedIds || []).slice(0, MAX_SELECTED)
|
||||
if (!ids.length) {
|
||||
ElMessage.warning('请先在列表中勾选要导出的订单')
|
||||
return
|
||||
}
|
||||
filters.ids = ids.join(',')
|
||||
}
|
||||
await submit(props.type, filters)
|
||||
dialogVisible.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
@ -44,4 +84,37 @@ function handleClick() {
|
||||
<el-icon><Download /></el-icon>
|
||||
<span>{{ text }}</span>
|
||||
</el-button>
|
||||
|
||||
<el-dialog v-model="dialogVisible" title="导出订单" width="440px" append-to-body>
|
||||
<el-form label-width="76px" size="small">
|
||||
<el-form-item label="导出范围">
|
||||
<el-radio-group v-model="scope">
|
||||
<el-radio value="selected" :disabled="!selectedCount">
|
||||
导出选中({{ selectedCount }} 条)
|
||||
</el-radio>
|
||||
<el-radio value="filtered">按条件全部</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="导出内容">
|
||||
<el-radio-group v-model="mode">
|
||||
<el-radio value="order">订单行(不含明细)</el-radio>
|
||||
<el-radio value="item">订单含明细(每商品一行)</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="selectedCount > MAX_SELECTED && scope === 'selected'" label=" ">
|
||||
<span class="hint">单次最多导出 {{ MAX_SELECTED }} 条选中订单,超出部分请分批导出</span>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="confirmOrderExport">提交导出</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.hint {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@ -70,9 +70,9 @@ async function fetchTypes() {
|
||||
const dialogVisible = ref(false)
|
||||
const { submitting, submit } = useExportTasks()
|
||||
|
||||
/** 当前导出类型可传的筛选字段 */
|
||||
/** 当前导出类型可传的筛选字段(hidden 的字段只由列表页自动携带,不在表单里展示) */
|
||||
const currentFilters = computed(
|
||||
() => typeOptions.value.find(o => o.value === form.type)?.filters || [],
|
||||
() => (typeOptions.value.find(o => o.value === form.type)?.filters || []).filter(fd => !fd.hidden),
|
||||
)
|
||||
|
||||
const form = reactive({
|
||||
|
||||
@ -100,10 +100,11 @@ const rules: FormRules = {
|
||||
logistics_code: [ { required: true, message: '请选择物流公司(推送仓库时随单下发 logisticsCode)', trigger: 'change' } ],
|
||||
}
|
||||
|
||||
/** 明细行默认值 */
|
||||
/** 明细行默认值(product_id 是选中的系统商品;item_id 仅历史手工单数据沿用) */
|
||||
function emptyLine(): OrderItemLine {
|
||||
return {
|
||||
order_line_no: '',
|
||||
product_id: null,
|
||||
item_id: null,
|
||||
item_code: '',
|
||||
item_name: '',
|
||||
@ -127,7 +128,7 @@ function fillItems(items: OrderItemLine[] | undefined) {
|
||||
/** 手工建单可选店铺:排除外部打单平台店铺(type=2,其订单只能由平台拉取) */
|
||||
const selectableShops = computed(() => (props.filters.shops || []).filter(shop => Number(shop.type ?? 1) !== 2))
|
||||
|
||||
/** item_id → 商品所属货主;用于切换店铺后校验已选明细是否同货主 */
|
||||
/** 选中的系统商品ID → 商品所属货主;用于切换店铺后校验已选明细是否同货主 */
|
||||
const itemOwnerMap = ref<Record<number, number | null>>({})
|
||||
|
||||
/** 默认店铺:优先父级入口指定的店铺,否则取可选店铺列表第一个 */
|
||||
@ -413,10 +414,10 @@ watch(shopSubsidiaryId, sid => {
|
||||
// 已选商品若属于其它货主,直接清空(后端同样会拦截,避免提交后才报错)
|
||||
let cleared = 0
|
||||
for (const line of form.items) {
|
||||
if (!line.item_id) continue
|
||||
const owner = itemOwnerMap.value[line.item_id]
|
||||
if (!line.product_id) continue
|
||||
const owner = itemOwnerMap.value[line.product_id]
|
||||
if (owner === undefined || owner === null || Number(owner) === sid) continue
|
||||
line.item_id = null
|
||||
line.product_id = null
|
||||
line.item_code = ''
|
||||
line.item_name = ''
|
||||
cleared += 1
|
||||
@ -438,7 +439,8 @@ function removeLine(index: number) {
|
||||
function onLineProductSelect(index: number, product: ProductSearchItem) {
|
||||
const line = form.items[index]
|
||||
if (!line) return
|
||||
line.item_id = product.id
|
||||
line.product_id = product.id
|
||||
line.item_id = null
|
||||
line.item_code = product.item_code || ''
|
||||
line.item_name = product.item_name || ''
|
||||
// 记录商品所属货主,切换店铺时用来校验 / 清空不一致的明细
|
||||
@ -459,7 +461,7 @@ const itemsAmount = computed(() =>
|
||||
|
||||
/** 明细是否有实际内容(空行不计):有明细时商品总金额由明细派生,不允许手改 */
|
||||
const hasRealItems = computed(() =>
|
||||
form.items.some(line => String(line.item_code || '').trim() || Number(line.item_id || 0) > 0),
|
||||
form.items.some(line => String(line.item_code || '').trim() || Number(line.product_id || line.item_id || 0) > 0),
|
||||
)
|
||||
|
||||
/** 商品总金额(两位小数) */
|
||||
@ -476,9 +478,12 @@ watch(
|
||||
/** 提交前清理:空行剔除、行号补全、空串转 undefined */
|
||||
function buildPayload(): OrderStatusPayload {
|
||||
const items = form.items
|
||||
.filter(line => (line.item_code && String(line.item_code).trim()) || (line.item_id && line.item_id > 0))
|
||||
.filter(line => (line.item_code && String(line.item_code).trim()) || Number(line.product_id || line.item_id || 0) > 0)
|
||||
.map((line, index) => ({
|
||||
order_line_no: String(line.order_line_no || index + 1),
|
||||
// 选中的系统商品:product_id 是推送/取号/统计统一口径;
|
||||
// item_id 仅历史手工单数据沿用(后端写库时会按商品编码核对后迁到 product_id)
|
||||
product_id: line.product_id ?? null,
|
||||
item_id: line.item_id ?? null,
|
||||
item_code: line.item_code ? String(line.item_code).trim() : null,
|
||||
item_name: line.item_name ? String(line.item_name).trim() : null,
|
||||
@ -868,7 +873,7 @@ async function submit() {
|
||||
<el-table-column label="商品" min-width="220">
|
||||
<template #default="{ row, $index }">
|
||||
<ProductSelect
|
||||
v-model="row.item_id"
|
||||
v-model="row.product_id"
|
||||
:model-label="[ row.item_code, row.item_name ].filter(Boolean).join(' ')"
|
||||
:subsidiary-id="shopSubsidiaryId"
|
||||
@select="(p: ProductSearchItem) => onLineProductSelect($index, p)"
|
||||
|
||||
@ -41,6 +41,7 @@ import {
|
||||
type OrderStage,
|
||||
type OrderStatusFilters,
|
||||
type OrderStatusItem,
|
||||
type OrderStatusSnCode,
|
||||
} from '@/api/orderStatus'
|
||||
|
||||
/**
|
||||
@ -84,6 +85,8 @@ const query = reactive({
|
||||
platform_codes: [] as string[],
|
||||
/** 平台单号(多个精确匹配,支持批量粘贴) */
|
||||
platform_order_nos: [] as string[],
|
||||
/** 序列号(SN):多个精确匹配,WMS 回传的 snList 反查订单 */
|
||||
sn_codes: [] as string[],
|
||||
receiver: '',
|
||||
address: '',
|
||||
remark: '',
|
||||
@ -175,6 +178,7 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand
|
||||
if (query.shop_id !== '') params.shop_id = query.shop_id
|
||||
if (query.platform_codes.length) params.platform_codes = query.platform_codes.join(',')
|
||||
if (query.platform_order_nos.length) params.platform_order_nos = query.platform_order_nos.join(',')
|
||||
if (query.sn_codes.length) params.sn_codes = query.sn_codes.join(',')
|
||||
if (query.receiver) params.receiver = query.receiver.trim()
|
||||
if (query.address) params.address = query.address.trim()
|
||||
if (query.remark) params.remark = query.remark.trim()
|
||||
@ -207,6 +211,7 @@ function reset() {
|
||||
query.shop_id = ''
|
||||
query.platform_codes = []
|
||||
query.platform_order_nos = []
|
||||
query.sn_codes = []
|
||||
query.receiver = ''
|
||||
query.address = ''
|
||||
query.remark = ''
|
||||
@ -227,6 +232,7 @@ const exportFilters = computed(() => ({
|
||||
shop_id: query.shop_id,
|
||||
platform_codes: query.platform_codes.join(','),
|
||||
platform_order_nos: query.platform_order_nos.join(','),
|
||||
sn_codes: query.sn_codes.join(','),
|
||||
created_from: query.createdRange[0],
|
||||
created_to: query.createdRange[1],
|
||||
archived_from: query.archivedRange[0],
|
||||
@ -585,16 +591,54 @@ const detailVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detailRow = ref<OrderStatusItem | null>(null)
|
||||
const detailProducts = ref<OrderItemLine[]>([])
|
||||
/** 仓库回传的序列号(order_sn_codes,随详情返回) */
|
||||
const detailSnCodes = ref<OrderStatusSnCode[]>([])
|
||||
/** 商品明细里已展开 SN 列表的行(el-table 的受控展开行 key = 明细 id) */
|
||||
const expandedItemIds = ref<number[]>([])
|
||||
|
||||
/** 该明细行对应的回传序列号(优先按行号匹配,缺行号时按商品编码匹配) */
|
||||
function snCodesOfLine(row: OrderItemLine): OrderStatusSnCode[] {
|
||||
const lineNo = String(row.order_line_no == null ? '' : row.order_line_no).trim()
|
||||
const itemCode = String(row.item_code == null ? '' : row.item_code).trim()
|
||||
return detailSnCodes.value.filter(sn => {
|
||||
const snLineNo = String(sn.order_line_no == null ? '' : sn.order_line_no).trim()
|
||||
if (lineNo && snLineNo) return snLineNo === lineNo
|
||||
return Boolean(itemCode) && String(sn.item_code == null ? '' : sn.item_code).trim() === itemCode
|
||||
})
|
||||
}
|
||||
|
||||
function isItemSnExpanded(row: OrderItemLine): boolean {
|
||||
return row.id != null && expandedItemIds.value.includes(Number(row.id))
|
||||
}
|
||||
|
||||
/** 点「SN码」切换该明细行的折叠 SN 列表 */
|
||||
function toggleItemSn(row: OrderItemLine) {
|
||||
if (row.id == null) return
|
||||
const id = Number(row.id)
|
||||
expandedItemIds.value = isItemSnExpanded(row)
|
||||
? expandedItemIds.value.filter(item => item !== id)
|
||||
: [ ...expandedItemIds.value, id ]
|
||||
}
|
||||
|
||||
/** el-table 展开箭头与按钮共用同一份展开状态 */
|
||||
function onItemExpandChange(_row: OrderItemLine, expandedRows: OrderItemLine[]) {
|
||||
expandedItemIds.value = (expandedRows || [])
|
||||
.map(item => Number(item.id))
|
||||
.filter(id => Number.isInteger(id))
|
||||
}
|
||||
|
||||
async function openDetail(row: OrderStatusItem) {
|
||||
detailRow.value = row
|
||||
detailProducts.value = []
|
||||
detailSnCodes.value = []
|
||||
expandedItemIds.value = []
|
||||
detailVisible.value = true
|
||||
detailLoading.value = true
|
||||
try {
|
||||
const { order, items } = await getOrderStatusDetail(row.id)
|
||||
detailRow.value = order
|
||||
detailProducts.value = items
|
||||
detailSnCodes.value = order.sn_codes || []
|
||||
} catch {
|
||||
// 拦截器已提示,退化为列表行展示
|
||||
} finally {
|
||||
@ -881,7 +925,7 @@ onBeforeUnmount(() => {
|
||||
class="unbound-switch"
|
||||
@change="onUnboundSwitchChange"
|
||||
/>
|
||||
<ExportButton type="order" :filters="exportFilters" size="small" plain />
|
||||
<ExportButton type="order" :filters="exportFilters" :selected-ids="selectedIds" size="small" plain />
|
||||
<el-button v-if="props.status === 'pending'" size="small" @click="syncDialogVisible = true">
|
||||
一键拉取订单
|
||||
</el-button>
|
||||
@ -904,6 +948,14 @@ onBeforeUnmount(() => {
|
||||
@update:model-value="search"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="序列号">
|
||||
<MultiValueFilter
|
||||
v-model="query.sn_codes"
|
||||
placeholder="批量查询,多个 SN"
|
||||
width="200px"
|
||||
@update:model-value="search"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="创建时间">
|
||||
<el-date-picker
|
||||
v-model="query.createdRange"
|
||||
@ -1128,7 +1180,7 @@ onBeforeUnmount(() => {
|
||||
/>
|
||||
|
||||
<!-- 详情(单据头 + 明细,实时取自详情接口) -->
|
||||
<el-drawer v-model="detailVisible" :title="`订单 ${detailRow?.order_no || ''}`" size="720px">
|
||||
<el-drawer v-model="detailVisible" :title="`订单 ${detailRow?.order_no || ''}`" size="860px">
|
||||
<template v-if="detailRow">
|
||||
<el-descriptions v-loading="detailLoading" :column="2" border size="small">
|
||||
<el-descriptions-item label="订单号">{{ detailRow.order_no }}</el-descriptions-item>
|
||||
@ -1200,23 +1252,59 @@ onBeforeUnmount(() => {
|
||||
</template>
|
||||
</el-descriptions>
|
||||
|
||||
<el-divider content-position="left">商品明细({{ detailProducts.length }} 行)</el-divider>
|
||||
<DataTable :data="detailProducts" :stripe="true">
|
||||
<el-table-column prop="order_line_no" label="行号" width="70" />
|
||||
<el-table-column prop="item_code" label="商品编码" width="150" show-overflow-tooltip />
|
||||
<el-table-column prop="item_name" label="商品名称" min-width="150" show-overflow-tooltip />
|
||||
<el-table-column label="数量" width="80" align="right">
|
||||
<el-divider content-position="left">
|
||||
商品明细({{ detailProducts.length }} 行{{ detailSnCodes.length ? ` · 序列号 ${detailSnCodes.length} 个` : '' }})
|
||||
</el-divider>
|
||||
<DataTable
|
||||
:data="detailProducts"
|
||||
:stripe="true"
|
||||
row-key="id"
|
||||
:expand-row-keys="expandedItemIds"
|
||||
@expand-change="onItemExpandChange"
|
||||
>
|
||||
<el-table-column type="expand" width="32">
|
||||
<template #default="{ row }">
|
||||
<div class="sn-expand">
|
||||
<template v-if="snCodesOfLine(row).length">
|
||||
<div v-for="sn in snCodesOfLine(row)" :key="sn.id" class="sn-expand__item">
|
||||
<el-tag size="small" effect="plain">{{ sn.sn_code }}</el-tag>
|
||||
<span v-if="sn.express_code" class="sn-expand__meta">运单号 {{ sn.express_code }}</span>
|
||||
<span class="sn-expand__meta">{{ formatDateTime(sn.created_at) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<span v-else class="muted">该行没有仓库回传的序列号</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="order_line_no" label="行号" width="60" />
|
||||
<el-table-column prop="item_code" label="商品编码" width="140" show-overflow-tooltip />
|
||||
<el-table-column prop="item_name" label="商品名称" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column label="数量" width="60" align="right">
|
||||
<template #default="{ row }">{{ fmtNum(row.plan_qty) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="单价" width="80" align="right">
|
||||
<el-table-column label="单价" width="70" align="right">
|
||||
<template #default="{ row }">{{ fmtNum(row.actual_price) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="金额" width="90" align="right">
|
||||
<el-table-column label="金额" width="80" align="right">
|
||||
<template #default="{ row }">{{ lineAmount(row) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="库存类型" width="90">
|
||||
<el-table-column label="库存类型" width="80">
|
||||
<template #default="{ row }">{{ row.inventory_type === 'CC' ? '残次' : '正品' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
v-if="snCodesOfLine(row).length"
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="toggleItemSn(row)"
|
||||
>
|
||||
{{ isItemSnExpanded(row) ? '收起SN码' : `SN码(${snCodesOfLine(row).length})` }}
|
||||
</el-button>
|
||||
<span v-else class="muted">-</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</DataTable>
|
||||
</template>
|
||||
</el-drawer>
|
||||
@ -1343,6 +1431,20 @@ onBeforeUnmount(() => {
|
||||
.muted {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
/* 商品明细:展开的 SN 列表(一行一个序列号) */
|
||||
.sn-expand {
|
||||
padding: 4px 8px 4px 28px;
|
||||
}
|
||||
.sn-expand__item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 2px 0;
|
||||
}
|
||||
.sn-expand__meta {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.add-line {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
@ -533,7 +533,7 @@ onBeforeUnmount(() => {
|
||||
<el-form-item label="关键词">
|
||||
<el-input
|
||||
v-model="query.keyword"
|
||||
placeholder="标题 / 商家编码 / 商品ID / 规格ID"
|
||||
placeholder="标题 / 商家编码 / 商品ID / 规格ID / 规格"
|
||||
clearable
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
@ -620,6 +620,9 @@ onBeforeUnmount(() => {
|
||||
<el-table-column prop="outer_code" label="商家编码" width="120">
|
||||
<template #default="{ row }">{{ row.outer_code || '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="spec" label="规格" width="180" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.spec || '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="售价" width="100" align="right">
|
||||
<template #default="{ row }">{{ row.price ?? '-' }}</template>
|
||||
</el-table-column>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user