feat(backend): 订单状态分表、WMS 推送与归档
- 新增 order_index 索引表 + 6 张同构状态表(待审核/异常/委外中/配送/已作废/已取消)与历史表, 订单 ID 全局唯一,状态由业务事务推动:审核、驳回、取消、作废、恢复、归档 - 明细表 order_status_items、收件人文本智能解析、批量切换仓库/店铺并刷新快照 - WMS deliveryorder.create 推送(单条/批量)、推送失败定时重试、订单归档定时任务 - 迁移:建表、旧发货单数据迁入新表、菜单合并与迁移记录清理 - routes / swagger contract 补充订单状态接口 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
d22f3e1f0a
commit
6c03a20364
@ -378,6 +378,72 @@ module.exports = {
|
||||
data: { type: 'array', itemType: 'productSearchItem', description: '命中的启用商品列表' },
|
||||
},
|
||||
|
||||
// ---------- 商品属性(分类/品牌/单位,按主体隔离) ----------
|
||||
/** 商品属性项(分类/品牌/单位字段结构一致,仅语义不同):列表与详情共用 */
|
||||
productAttributeItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
name: { type: 'string', description: '名称(分类名/品牌名/单位名)' },
|
||||
code: { type: 'string', description: '编码' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
sort: { type: 'integer', description: '排序,越小越靠前' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
used_count: { type: 'integer', description: '被商品使用次数(>0 禁止删除)' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
productCategoryPage: buildPage('productAttributeItem', '商品分类列表'),
|
||||
productBrandPage: buildPage('productAttributeItem', '商品品牌列表'),
|
||||
productUnitPage: buildPage('productAttributeItem', '商品单位列表'),
|
||||
productCategoryListResponse: buildListResponse('productCategoryPage'),
|
||||
productBrandListResponse: buildListResponse('productBrandPage'),
|
||||
productUnitListResponse: buildListResponse('productUnitPage'),
|
||||
createProductCategoryRequest: {
|
||||
principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' },
|
||||
name: { type: 'string', required: true, description: '分类名称,主体内唯一' },
|
||||
code: { type: 'string', description: '分类编码' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
|
||||
sort: { type: 'integer', description: '排序,默认0' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
updateProductCategoryRequest: {
|
||||
name: { type: 'string', description: '分类名称,主体内唯一' },
|
||||
code: { type: 'string', description: '分类编码' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
sort: { type: 'integer', description: '排序' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
createProductBrandRequest: {
|
||||
principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' },
|
||||
name: { type: 'string', required: true, description: '品牌名称,主体内唯一' },
|
||||
code: { type: 'string', description: '品牌编码' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
|
||||
sort: { type: 'integer', description: '排序,默认0' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
updateProductBrandRequest: {
|
||||
name: { type: 'string', description: '品牌名称,主体内唯一' },
|
||||
code: { type: 'string', description: '品牌编码' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
sort: { type: 'integer', description: '排序' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
createProductUnitRequest: {
|
||||
principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' },
|
||||
name: { type: 'string', required: true, description: '单位名称,主体内唯一' },
|
||||
code: { type: 'string', description: '单位编码' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
|
||||
sort: { type: 'integer', description: '排序,默认0' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
updateProductUnitRequest: {
|
||||
name: { type: 'string', description: '单位名称,主体内唯一' },
|
||||
code: { type: 'string', description: '单位编码' },
|
||||
status: { type: 'integer', description: '状态:1启用 0禁用' },
|
||||
sort: { type: 'integer', description: '排序' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
|
||||
// ---------- 组合商品 combo_products ----------
|
||||
comboProductSubItem: {
|
||||
product_id: { type: 'integer', description: '系统商品ID' },
|
||||
@ -1573,6 +1639,409 @@ module.exports = {
|
||||
stockRecordPage: buildPage('stockRecord', '出入库记录(库存流水)列表'),
|
||||
stockRecordListResponse: buildListResponse('stockRecordPage'),
|
||||
|
||||
// ---------- 订单(状态分表)order ----------
|
||||
/** 订单的商品明细行(product_info JSON 数组元素) */
|
||||
orderStatusProductLine: {
|
||||
item_code: { type: 'string', description: '商品编码' },
|
||||
item_name: { type: 'string', description: '商品名称' },
|
||||
quantity: { type: 'number', description: '数量' },
|
||||
price: { type: 'number', description: '单价' },
|
||||
},
|
||||
/** 订单状态选项 */
|
||||
orderStatusOption: {
|
||||
value: { type: 'string', description: '状态值:pending 待审核 / queued 待推送 / exception 异常 / outsourcing 委外中 / delivery 配送 / void 已作废 / canceled 已取消 / history 历史' },
|
||||
label: { type: 'string', description: '状态中文名' },
|
||||
},
|
||||
/** 店铺下拉项 */
|
||||
orderStatusShopOption: {
|
||||
id: { type: 'integer', description: '店铺ID' },
|
||||
name: { type: 'string', description: '店铺名称' },
|
||||
},
|
||||
/** 筛选条件下拉数据源(GET /api/order-status/filters) */
|
||||
orderStatusFilters: {
|
||||
statuses: { type: 'array', itemType: 'orderStatusOption', description: '状态枚举(按页面 tab 顺序:待审核/待推送/异常/委外中/配送/已作废/已取消/历史)' },
|
||||
status_labels: { type: 'object', description: '状态值 → 中文名映射' },
|
||||
active_statuses: { type: 'array', itemType: 'string', description: '活动状态(非历史):pending/queued/exception/outsourcing/delivery/void/canceled' },
|
||||
archive_months: { type: 'integer', description: '超期自动归档阈值(月),默认 3' },
|
||||
index_table: { type: 'string', description: '订单索引表名(order_index)' },
|
||||
item_table: { type: 'string', description: '订单明细表名(order_status_items)' },
|
||||
shops: { type: 'array', itemType: 'orderStatusShopOption', description: '当前主体下的店铺(筛选/表单下拉)' },
|
||||
warehouses: { type: 'array', itemType: 'orderStatusWarehouseOption', description: '当前主体下的仓库(切换仓库下拉)' },
|
||||
},
|
||||
/** 仓库下拉项 */
|
||||
orderStatusWarehouseOption: {
|
||||
id: { type: 'integer', description: '仓库ID' },
|
||||
code: { type: 'string', description: '仓库编码' },
|
||||
name: { type: 'string', description: '仓库名称' },
|
||||
},
|
||||
orderStatusFiltersResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusFilters', description: '筛选条件下拉数据源' },
|
||||
},
|
||||
/** 订单(列表行:4 张状态表与历史表同构,历史表另含归档/转入时间) */
|
||||
orderStatusItem: {
|
||||
id: { type: 'integer', description: '订单ID(= order_index.id,全局唯一)' },
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
order_no: { type: 'string', description: '订单号(缺省为「来源订单号-序号」)' },
|
||||
parent_order_no: { type: 'string', description: '来源订单号(上游/平台订单号)' },
|
||||
shop_id: { type: 'integer', description: '店铺ID' },
|
||||
shop_name: { type: 'string', description: '店铺名称(列表按 shop_id 补全)' },
|
||||
product_info: { type: 'array', itemType: 'orderStatusProductLine', description: '商品明细' },
|
||||
product_summary: { type: 'string', description: '商品明细摘要(如「商品A ×2;商品B ×1」,最多展示 3 项)' },
|
||||
product_kind: { type: 'integer', description: '商品种类数' },
|
||||
receiver: { type: 'string', description: '收货人' },
|
||||
address: { type: 'string', description: '收货地址(省市区镇 + 详细地址的汇总快照)' },
|
||||
// —— 以下为「为容纳老表(原订单表 orders + 发货单 order_deliveries)而扩展」的字段 ——
|
||||
order_type: { type: 'string', description: '订单类型:WMS 编码 JYCK/HHCK/BFCK(老 order_type 数值以字符串保留)' },
|
||||
wms_status: { type: 'string', description: '外部WMS状态(回调回写)' },
|
||||
wms_order_no: { type: 'string', description: '外部WMS单号' },
|
||||
wms_synced_at: { type: 'string', description: '最近一次 WMS 同步时间' },
|
||||
submit_status: { type: 'integer', description: '上交状态:0未上交 1上交中 2已上交 3上交失败' },
|
||||
submit_order_no: { type: 'string', description: '上交后返回的单号' },
|
||||
submit_at: { type: 'string', description: '上交时间' },
|
||||
submit_msg: { type: 'string', description: '上交结果 / 失败原因' },
|
||||
total_amount: { type: 'number', description: '订单总金额' },
|
||||
pay_amount: { type: 'number', description: '实付金额' },
|
||||
legacy_status: { type: 'integer', description: '迁移来源的老状态原值(orders.status / order_deliveries.status)' },
|
||||
warehouse_id: { type: 'integer', description: '仓库ID' },
|
||||
warehouse_code: { type: 'string', description: '仓库编码(报文 warehouseCode 快照)' },
|
||||
order_flag: { type: 'string', description: '订单标记' },
|
||||
pre_delivery_order_code: { type: 'string', description: '预发货单号' },
|
||||
pre_delivery_order_id: { type: 'string', description: '预发货单ID' },
|
||||
is_urgency: { type: 'string', description: '是否紧急:Y/N' },
|
||||
invoice_flag: { type: 'string', description: '是否需要发票:Y/N' },
|
||||
source_platform_code: { type: 'string', description: '来源平台编码' },
|
||||
source_platform_name: { type: 'string', description: '来源平台名称' },
|
||||
shop_nick: { type: 'string', description: '店铺名称' },
|
||||
seller_nick: { type: 'string', description: '卖家名称' },
|
||||
buyer_nick: { type: 'string', description: '买家名称' },
|
||||
buyer_message: { type: 'string', description: '买家留言' },
|
||||
seller_message: { type: 'string', description: '卖家留言' },
|
||||
place_order_time: { type: 'string', description: '下单时间' },
|
||||
pay_time: { type: 'string', description: '支付时间' },
|
||||
pay_no: { type: 'string', description: '支付单号' },
|
||||
operate_time: { type: 'string', description: 'ERP 审核/操作时间' },
|
||||
item_amount: { type: 'number', description: '商品总金额(按明细派生)' },
|
||||
discount_amount: { type: 'number', description: '订单折扣金额' },
|
||||
freight: { type: 'number', description: '快递费用' },
|
||||
ar_amount: { type: 'number', description: '应收金额' },
|
||||
got_amount: { type: 'number', description: '已收金额' },
|
||||
logistics_code: { type: 'string', description: '物流公司编码(WMS 标准编码,如 SF/YTO)' },
|
||||
logistics_name: { type: 'string', description: '物流公司名称' },
|
||||
express_code: { type: 'string', description: '运单号(面单号,回调回写)' },
|
||||
express_codes: { type: 'array', itemType: 'string', description: '运单号集合(多包裹)' },
|
||||
logistics_area_code: { type: 'string', description: '快递区域编码' },
|
||||
operator_name: { type: 'string', description: '操作人 / 审核人' },
|
||||
oaid_order_source_code: { type: 'string', description: 'OAID 订单来源编码' },
|
||||
source_order_codes: { type: 'string', description: '来源订单号集合' },
|
||||
extend_props: { type: 'object', description: '请求级扩展属性' },
|
||||
need_oms_waybill: { type: 'integer', description: '是否需要回 OMS 取号:0否 1是' },
|
||||
tel: { type: 'string', description: '收货人电话' },
|
||||
mobile: { type: 'string', description: '收货人手机号' },
|
||||
email: { type: 'string', description: '收货人邮箱' },
|
||||
country_code: { type: 'string', description: '国家编码' },
|
||||
province: { type: 'string', description: '省份' },
|
||||
city: { type: 'string', description: '城市' },
|
||||
area: { type: 'string', description: '区县' },
|
||||
town: { type: 'string', description: '街道/镇' },
|
||||
detail_address: { type: 'string', description: '详细地址' },
|
||||
zip_code: { type: 'string', description: '邮编' },
|
||||
oaid: { type: 'string', description: 'OAID' },
|
||||
stock_locked: { type: 'integer', description: '库存锁定标记:1=当前占用锁定库存 0=未锁定(系统托管)' },
|
||||
shop_sync_status: { type: 'integer', description: '回传平台店铺状态:0未同步 1同步中 2同步成功 3同步失败' },
|
||||
shop_sync_retry_count: { type: 'integer', description: '回传平台店铺的重试次数' },
|
||||
created_by: { type: 'integer', description: '创建人ID' },
|
||||
pushed_at: { type: 'string', description: 'WMS 推送时间(系统托管)' },
|
||||
wms_push_result: { type: 'object', description: 'WMS 推送结果(系统托管)' },
|
||||
legacy_order_id: { type: 'integer', description: '迁移来源:orders.id(非搬迁数据为 NULL)' },
|
||||
item_total: { type: 'number', description: '商品总数(明细计划数量合计)' },
|
||||
item_kind: { type: 'integer', description: '商品种类数' },
|
||||
audit_by: { type: 'integer', description: '审核人ID' },
|
||||
audit_time: { type: 'string', description: '审核时间' },
|
||||
void_at: { type: 'string', description: '作废时间' },
|
||||
void_by: { type: 'integer', description: '作废人ID' },
|
||||
void_reason: { type: 'string', description: '作废原因' },
|
||||
status: { type: 'string', description: '状态:pending 待审核 / queued 待推送 / exception 异常 / outsourcing 委外中 / delivery 配送 / void 已作废 / canceled 已取消 / history 历史' },
|
||||
status_label: { type: 'string', description: '状态中文名' },
|
||||
remark: { type: 'string', description: '备注 / 异常原因' },
|
||||
current_table: { type: 'string', description: '当前所在表(索引表 current_table,与状态同值)' },
|
||||
created_at: { type: 'string', description: '创建时间(超 3 个月自动归档的判断依据)' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
archived_at: { type: 'string', description: '归档时间(仅历史表)' },
|
||||
transferred_at: { type: 'string', description: '转入历史时间(仅历史表)' },
|
||||
},
|
||||
orderStatusPage: buildPage('orderStatusItem', '订单列表'),
|
||||
orderStatusListResponse: buildListResponse('orderStatusPage'),
|
||||
/** 新建订单(含发货单口径:可直接带 items 创建明细) */
|
||||
createOrderStatusRequest: {
|
||||
parent_order_no: { type: 'string', description: '来源订单号(上游/平台订单号;与 order_no 至少传一个,都不传时按 FH_{id} 生成)' },
|
||||
order_no: { type: 'string', description: '订单号,缺省按「来源订单号-序号」自动生成;无来源单号时按 FH_{id} 生成(需主体内唯一)' },
|
||||
items: { type: 'array', itemType: 'orderStatusItemLine', description: '商品明细(发货单口径;不传时可用 product_info 存快照)' },
|
||||
shop_id: { type: 'integer', description: '店铺ID(需属于当前主体,同步写 shop_nick 快照)' },
|
||||
product_info: { type: 'array', itemType: 'orderStatusProductLine', description: '商品明细快照' },
|
||||
receiver: { type: 'string', description: '收货人' },
|
||||
address: { type: 'string', description: '收货地址(不传时按省市区镇 + 详细地址自动拼接)' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
// —— 以下为扩展字段(为容纳老表而扩展,均可由接口写入;系统托管字段见控制器注释)——
|
||||
order_type: { type: 'string', description: '订单类型:JYCK/HHCK/BFCK' },
|
||||
warehouse_id: { type: 'integer', description: '仓库ID' },
|
||||
warehouse_code: { type: 'string', description: '仓库编码' },
|
||||
order_flag: { type: 'string', description: '订单标记' },
|
||||
pre_delivery_order_code: { type: 'string', description: '预发货单号' },
|
||||
pre_delivery_order_id: { type: 'string', description: '预发货单ID' },
|
||||
is_urgency: { type: 'string', description: '是否紧急:Y/N' },
|
||||
invoice_flag: { type: 'string', description: '是否需要发票:Y/N' },
|
||||
source_platform_code: { type: 'string', description: '来源平台编码' },
|
||||
source_platform_name: { type: 'string', description: '来源平台名称' },
|
||||
shop_nick: { type: 'string', description: '店铺名称' },
|
||||
seller_nick: { type: 'string', description: '卖家名称' },
|
||||
buyer_nick: { type: 'string', description: '买家名称' },
|
||||
buyer_message: { type: 'string', description: '买家留言' },
|
||||
seller_message: { type: 'string', description: '卖家留言' },
|
||||
place_order_time: { type: 'string', description: '下单时间' },
|
||||
pay_time: { type: 'string', description: '支付时间' },
|
||||
pay_no: { type: 'string', description: '支付单号' },
|
||||
operate_time: { type: 'string', description: 'ERP 审核/操作时间' },
|
||||
total_amount: { type: 'number', description: '订单总金额' },
|
||||
pay_amount: { type: 'number', description: '实付金额' },
|
||||
item_amount: { type: 'number', description: '商品总金额' },
|
||||
discount_amount: { type: 'number', description: '订单折扣金额' },
|
||||
freight: { type: 'number', description: '快递费用' },
|
||||
ar_amount: { type: 'number', description: '应收金额' },
|
||||
got_amount: { type: 'number', description: '已收金额' },
|
||||
logistics_code: { type: 'string', description: '物流公司编码' },
|
||||
logistics_name: { type: 'string', description: '物流公司名称' },
|
||||
logistics_area_code: { type: 'string', description: '快递区域编码' },
|
||||
oaid_order_source_code: { type: 'string', description: 'OAID 订单来源编码' },
|
||||
source_order_codes: { type: 'string', description: '来源订单号集合' },
|
||||
extend_props: { type: 'object', description: '请求级扩展属性' },
|
||||
need_oms_waybill: { type: 'integer', description: '是否需要回 OMS 取号:0否 1是' },
|
||||
tel: { type: 'string', description: '收货人电话' },
|
||||
mobile: { type: 'string', description: '收货人手机号' },
|
||||
email: { type: 'string', description: '收货人邮箱' },
|
||||
country_code: { type: 'string', description: '国家编码' },
|
||||
province: { type: 'string', description: '省份' },
|
||||
city: { type: 'string', description: '城市' },
|
||||
area: { type: 'string', description: '区县' },
|
||||
town: { type: 'string', description: '街道/镇' },
|
||||
detail_address: { type: 'string', description: '详细地址' },
|
||||
zip_code: { type: 'string', description: '邮编' },
|
||||
oaid: { type: 'string', description: 'OAID' },
|
||||
legacy_status: { type: 'integer', description: '迁移来源的老状态原值(orders.status / order_deliveries.status)' },
|
||||
},
|
||||
orderStatusCreateData: {
|
||||
id: { type: 'integer', description: '订单ID(= order_index.id)' },
|
||||
order_no: { type: 'string', description: '订单号' },
|
||||
status: { type: 'string', description: '状态:pending 待审核' },
|
||||
status_label: { type: 'string', description: '状态中文名' },
|
||||
item_count: { type: 'integer', description: '创建时写入的明细条数' },
|
||||
},
|
||||
orderStatusCreateResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusCreateData', description: '新建结果' },
|
||||
},
|
||||
/** 批量操作:仅需订单ID数组(审核 / 转回待审核) */
|
||||
orderStatusIdsRequest: {
|
||||
ids: { type: 'array', itemType: 'integer', required: true, description: '订单ID数组(取自索引表 order_index.id,可跨状态表混选)' },
|
||||
},
|
||||
/** 批量推送外部标记 */
|
||||
pushOrderStatusRequest: {
|
||||
ids: { type: 'array', itemType: 'integer', required: true, description: '订单ID数组(仅「待推送」的订单可标记)' },
|
||||
outcome: { type: 'string', required: true, description: '推送结果:success 推送成功(→ 委外中)/ failed 推送失败(→ 异常)' },
|
||||
remark: { type: 'string', description: '失败原因(outcome=failed 时写入订单 remark)' },
|
||||
},
|
||||
/** 归档到历史 */
|
||||
archiveOrderStatusRequest: {
|
||||
ids: { type: 'array', itemType: 'integer', description: '指定归档的订单ID数组;不传则归档创建时间超过 months 个月的订单' },
|
||||
months: { type: 'integer', description: '超期月数,默认 3(不传 ids 时生效)' },
|
||||
},
|
||||
orderStatusTransitionData: {
|
||||
count: { type: 'integer', description: '流转成功的订单数' },
|
||||
status: { type: 'string', description: '流转后状态:queued 待推送 / outsourcing 委外中 / delivery 配送 / exception 异常 / pending 待审核 / void 已作废 / canceled 已取消 / history 历史' },
|
||||
status_label: { type: 'string', description: '流转后状态中文名' },
|
||||
order_nos: { type: 'array', itemType: 'string', description: '流转成功的订单号' },
|
||||
},
|
||||
orderStatusTransitionResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusTransitionData', description: '流转结果' },
|
||||
},
|
||||
orderStatusArchiveData: {
|
||||
count: { type: 'integer', description: '归档成功的订单数' },
|
||||
status: { type: 'string', description: '归档后状态:history(指定 ids 归档时返回)' },
|
||||
status_label: { type: 'string', description: '归档后状态中文名' },
|
||||
order_nos: { type: 'array', itemType: 'string', description: '归档成功的订单号(指定 ids 归档时返回)' },
|
||||
months: { type: 'integer', description: '超期月数(未指定 ids 时返回)' },
|
||||
threshold: { type: 'string', description: '超期阈值时间(未指定 ids 时返回)' },
|
||||
by_status: { type: 'object', description: '各来源状态归档条数(未指定 ids 时返回),如 {"delivery": 2}' },
|
||||
},
|
||||
orderStatusArchiveResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusArchiveData', description: '归档结果' },
|
||||
},
|
||||
/** 订单商品明细行(order_status_items,发货单明细与平台明细的超集) */
|
||||
orderStatusItemLine: {
|
||||
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_code: { type: 'string', description: '商品编码' },
|
||||
item_name: { type: 'string', description: '商品名称' },
|
||||
plan_qty: { type: 'number', description: '计划数量(必须大于 0)' },
|
||||
actual_price: { type: 'number', description: '实际单价(必填,不小于 0)' },
|
||||
retail_price: { type: 'number', description: '零售价' },
|
||||
ext_code: { type: 'string', description: '外部编码' },
|
||||
inventory_type: { type: 'string', description: '库存类型:ZP 正品 / CC 残次' },
|
||||
source_order_code: { type: 'string', description: '来源订单编码' },
|
||||
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' },
|
||||
sku_code: { type: 'string', description: '商家编码' },
|
||||
spec: { type: 'string', description: '规格' },
|
||||
image: { type: 'string', description: '图片' },
|
||||
created_at: { type: 'string', description: '创建时间' },
|
||||
updated_at: { type: 'string', description: '更新时间' },
|
||||
},
|
||||
/** 明细整体保存(新增/编辑明细统一走覆盖式保存) */
|
||||
saveOrderStatusItemsRequest: {
|
||||
order_id: { type: 'integer', required: true, description: '订单ID' },
|
||||
items: { type: 'array', itemType: 'orderStatusItemLine', required: true, description: '明细数组(整体覆盖写入;plan_qty>0、actual_price 必填、item_id/item_code 至少一个)' },
|
||||
},
|
||||
orderStatusItemListData: {
|
||||
list: { type: 'array', itemType: 'orderStatusItemLine', description: '明细列表(行号升序)' },
|
||||
total: { type: 'integer', description: '明细条数' },
|
||||
},
|
||||
orderStatusItemListResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusItemListData', description: '明细列表' },
|
||||
},
|
||||
/** 订单详情(单据头 + 明细) */
|
||||
orderStatusDetailData: {
|
||||
order: { type: 'orderStatusItem', description: '订单单据头' },
|
||||
items: { type: 'array', itemType: 'orderStatusItemLine', description: '商品明细' },
|
||||
},
|
||||
orderStatusDetailResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusDetailData', description: '订单详情' },
|
||||
},
|
||||
/** 编辑订单(仅待审核 / 异常可编辑;未传字段保持原值) */
|
||||
editOrderStatusRequest: {
|
||||
receiver: { type: 'string', description: '收货人' },
|
||||
province: { type: 'string', description: '省份' },
|
||||
city: { type: 'string', description: '城市' },
|
||||
area: { type: 'string', description: '区县' },
|
||||
town: { type: 'string', description: '街道/镇' },
|
||||
detail_address: { type: 'string', description: '详细地址' },
|
||||
tel: { type: 'string', description: '收货人电话' },
|
||||
mobile: { type: 'string', description: '收货人手机号' },
|
||||
warehouse_id: { type: 'integer', description: '仓库ID(变更时同步刷新 warehouse_code 快照)' },
|
||||
shop_id: { type: 'integer', description: '店铺ID(变更时同步刷新 shop_nick 快照)' },
|
||||
order_type: { type: 'string', description: '订单类型:JYCK/HHCK/BFCK' },
|
||||
total_amount: { type: 'number', description: '订单总金额' },
|
||||
pay_amount: { type: 'number', description: '实付金额' },
|
||||
freight: { type: 'number', description: '快递费用' },
|
||||
logistics_code: { type: 'string', description: '物流公司编码' },
|
||||
logistics_name: { type: 'string', description: '物流公司名称' },
|
||||
is_urgency: { type: 'string', description: '是否紧急:Y/N' },
|
||||
invoice_flag: { type: 'string', description: '是否需要发票:Y/N' },
|
||||
seller_message: { type: 'string', description: '卖家留言' },
|
||||
buyer_message: { type: 'string', description: '买家留言' },
|
||||
remark: { type: 'string', description: '备注' },
|
||||
},
|
||||
orderStatusUpdateData: {
|
||||
id: { type: 'integer', description: '订单ID' },
|
||||
order_no: { type: 'string', description: '订单号' },
|
||||
},
|
||||
orderStatusUpdateResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusUpdateData', description: '编辑结果' },
|
||||
},
|
||||
/** 取消订单 */
|
||||
cancelOrderStatusRequest: {
|
||||
ids: { type: 'array', itemType: 'integer', required: true, description: '订单ID数组(待审核/异常/待推送/委外中可取消)' },
|
||||
remark: { type: 'string', description: '取消原因(写入订单 remark)' },
|
||||
},
|
||||
/** 作废订单 */
|
||||
voidOrderStatusRequest: {
|
||||
ids: { type: 'array', itemType: 'integer', required: true, description: '订单ID数组(待审核/异常/待推送可作废)' },
|
||||
void_reason: { type: 'string', description: '作废原因(写入 void_reason)' },
|
||||
remark: { type: 'string', description: '备注(写入订单 remark)' },
|
||||
},
|
||||
/** 单据级流转结果(驳回 / 恢复:可能换号) */
|
||||
orderStatusSingleFlowItem: {
|
||||
id: { type: 'integer', description: '订单ID' },
|
||||
order_no: { type: 'string', description: '流转后的订单号(换号时为新号)' },
|
||||
bill_no_changed: { type: 'boolean', description: '是否换号' },
|
||||
},
|
||||
orderStatusSingleFlowData: {
|
||||
count: { type: 'integer', description: '流转成功的订单数' },
|
||||
status: { type: 'string', description: '流转后状态:pending 待审核' },
|
||||
status_label: { type: 'string', description: '流转后状态中文名' },
|
||||
items: { type: 'array', itemType: 'orderStatusSingleFlowItem', description: '逐单结果' },
|
||||
},
|
||||
orderStatusSingleFlowResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusSingleFlowData', description: '流转结果' },
|
||||
},
|
||||
/** 推送仓库(WMS deliveryorder.create) */
|
||||
orderStatusPushWmsData: {
|
||||
id: { type: 'integer', description: '订单ID' },
|
||||
attempts: { type: 'integer', description: '本次为第几次尝试' },
|
||||
wms_response: { type: 'object', description: 'WMS 返回报文' },
|
||||
},
|
||||
orderStatusPushWmsResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusPushWmsData', description: '推送结果' },
|
||||
},
|
||||
orderStatusPushWmsBatchDetail: {
|
||||
id: { type: 'integer', description: '订单ID' },
|
||||
ok: { type: 'boolean', description: '是否推送成功' },
|
||||
message: { type: 'string', description: '结果说明' },
|
||||
},
|
||||
orderStatusPushWmsBatchData: {
|
||||
requested: { type: 'integer', description: '请求推送条数' },
|
||||
processed: { type: 'integer', description: '本次处理条数(受批量上限限制)' },
|
||||
pendingRest: { type: 'integer', description: '超出批量上限、留给定时任务继续推送的条数' },
|
||||
pushed: { type: 'integer', description: '推送成功条数' },
|
||||
failed: { type: 'integer', description: '推送失败(已转异常)条数' },
|
||||
retry: { type: 'integer', description: '可重试(保留委外中)条数' },
|
||||
skipped: { type: 'integer', description: '跳过条数(状态不符 / 未配置接口 / 重试间隔内)' },
|
||||
details: { type: 'array', itemType: 'orderStatusPushWmsBatchDetail', description: '逐单结果' },
|
||||
},
|
||||
orderStatusPushWmsBatchResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusPushWmsBatchData', description: '批量推送结果' },
|
||||
},
|
||||
/** 批量切换仓库 / 设置所属店铺 */
|
||||
changeOrderStatusWarehouseRequest: {
|
||||
ids: { type: 'array', itemType: 'integer', required: true, description: '订单ID数组(待审核/异常/待推送)' },
|
||||
warehouse_id: { type: 'integer', required: true, description: '目标仓库ID(需属于当前主体,同步刷新 warehouse_code 快照)' },
|
||||
},
|
||||
changeOrderStatusShopRequest: {
|
||||
ids: { type: 'array', itemType: 'integer', required: true, description: '订单ID数组(待审核/异常/待推送/委外中)' },
|
||||
shop_id: { type: 'integer', required: true, description: '目标店铺ID(需属于当前主体,同步刷新 shop_nick 快照)' },
|
||||
},
|
||||
orderStatusChangeOwnerData: {
|
||||
updated: { type: 'integer', description: '更新条数' },
|
||||
target: { type: 'object', description: '目标仓库 / 店铺(id + 名称,仓库另含 code)' },
|
||||
scope: { type: 'object', description: '本次作用的订单ID集合' },
|
||||
},
|
||||
orderStatusChangeOwnerResponse: {
|
||||
code: { type: 'integer', description: '业务状态码,0 成功' },
|
||||
message: { type: 'string', description: '提示信息' },
|
||||
data: { type: 'orderStatusChangeOwnerData', description: '变更结果' },
|
||||
},
|
||||
|
||||
// ---------- 仪表盘报表 dashboard ----------
|
||||
/** 报表时间区间 */
|
||||
dashboardRange: {
|
||||
|
||||
495
backend/app/controller/orderStatus.js
Normal file
495
backend/app/controller/orderStatus.js
Normal file
@ -0,0 +1,495 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/**
|
||||
* @controller OrderStatusController 订单(状态分表)
|
||||
*
|
||||
* 订单按状态分表存储,页面按「待审核 / 待推送 / 异常 / 委外中 / 配送 / 已作废 / 已取消 / 历史」八个视图管理:
|
||||
* - 数据模型:order_index(索引表,订单 ID 全局唯一 + current_table/current_status)
|
||||
* + order_status_pending / queued / exception / outsourcing / delivery / void / canceled(7 张同构状态表)
|
||||
* + order_status_history;
|
||||
* - 状态流转由业务事务推动(审核 / 推送仓库 / 标记推送结果 / 驳回 / 取消 / 作废 / 恢复 / 归档),不提供直接改状态的接口;
|
||||
* 审核 → 待推送 → 推送成功 → 委外中 → 仓库回传确认 → 配送;推送失败 → 异常;
|
||||
* - 列表按 status 定位状态表(历史表另含归档时间/转入时间),筛选条件由 filters 接口提供下拉数据源;
|
||||
* - 数据按主体隔离(principal_id 由 principalCheck 中间件校验后写入 ctx.state.principalId)。
|
||||
*
|
||||
* 权限点(建议,当前仅菜单可见性用 order:list,操作权限点待产品确认):
|
||||
* order:list 查看 / order:audit 审核 / order:push 推送外部 / order:return 转回待审核 / order:archive 归档
|
||||
*/
|
||||
class OrderStatusController extends Controller {
|
||||
/**
|
||||
* 统一把服务层异常(err.status)转成业务响应,避免 500 直接抛给前端
|
||||
* @param {Object} ctx koa 上下文
|
||||
* @param {Error} err 异常(可带 status)
|
||||
* @param {String} fallbackMessage 兜底提示
|
||||
* @return {void} 无
|
||||
*/
|
||||
_fail(ctx, err, fallbackMessage) {
|
||||
const status = Number(err && err.status) || 500;
|
||||
ctx.status = status;
|
||||
ctx.body = { code: status, message: (err && err.message) || fallbackMessage };
|
||||
if (status >= 500) ctx.logger.error('[order] %s', (err && err.message) || fallbackMessage, err);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取并校验 ids(订单ID数组)
|
||||
* @return {Array} 订单ID数组
|
||||
*/
|
||||
_pickIds() {
|
||||
const ids = (this.ctx.request.body || {}).ids;
|
||||
if (!Array.isArray(ids) || !ids.length) {
|
||||
const err = new Error('ids(订单ID数组)为必填项:请至少勾选一条订单');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 订单列表
|
||||
* @description 按 status 定位状态表分页查询(pending 待审核 / queued 待推送 / exception 异常 /
|
||||
* outsourcing 委外中 / delivery 配送 / void 已作废 / canceled 已取消 / history 历史)。
|
||||
* 支持订单号、来源订单号、店铺、收货人、收货地址、备注(异常原因)、关键词与创建时间区间过滤;
|
||||
* 历史视图另支持归档时间区间。返回行附状态中文、店铺名称与商品明细摘要。
|
||||
* @router get /api/order-status/list
|
||||
* @apikey
|
||||
* @request query string status 状态(=所在表):pending 待审核(默认)/ queued 待推送 / exception 异常 / outsourcing 委外中 / delivery 配送 / void 已作废 / canceled 已取消 / history 历史
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query string order_no 订单号,模糊匹配
|
||||
* @request query string parent_order_no 来源订单号,模糊匹配
|
||||
* @request query integer shop_id 店铺ID
|
||||
* @request query string receiver 收货人,模糊匹配
|
||||
* @request query string address 收货地址,模糊匹配
|
||||
* @request query string remark 备注 / 异常原因,模糊匹配
|
||||
* @request query string keyword 关键词:订单号 / 来源订单号 / 收货人 / 收货地址
|
||||
* @request query string created_from 创建时间起(YYYY-MM-DD)
|
||||
* @request query string created_to 创建时间止(YYYY-MM-DD)
|
||||
* @request query string archived_from 归档时间起(仅 status=history)
|
||||
* @request query string archived_to 归档时间止(仅 status=history)
|
||||
* @response 200 orderStatusListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||||
try {
|
||||
const { list, total } = await ctx.service.orderStatus.list({ ...ctx.query, offset, limit });
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, total, { page, pageSize }) };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '查询订单列表失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 订单筛选项
|
||||
* @description 返回状态枚举(含中文)、当前主体下的店铺下拉、归档阈值(月)与索引表名,
|
||||
* 供筛选区/表单使用,避免前后端枚举漂移。
|
||||
* @router get /api/order-status/filters
|
||||
* @apikey
|
||||
* @response 200 orderStatusFiltersResponse success
|
||||
*/
|
||||
async filters() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.filters();
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '查询筛选条件失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新建订单
|
||||
* @description 写入索引表(取全局唯一 id)与待审核表,状态为「待审核」。
|
||||
* 订单号缺省按「来源订单号-序号」生成(序号取索引表中该来源订单号已有订单数 +1)。
|
||||
* @router post /api/order-status
|
||||
* @apikey
|
||||
* @request body createOrderStatusRequest
|
||||
* @response 200 orderStatusCreateResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.create(ctx.request.body || {});
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '新建订单失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 批量审核(待审核 / 异常 → 待推送)
|
||||
* @description 审核即校验明细与店铺并**锁定库存**,通过后进入「待推送」等待推送仓库;
|
||||
* 异常订单可直接审核进入待推送。两个场景按索引表记录的当前所在表自动分流,无需前端区分。
|
||||
* @router post /api/order-status/audit
|
||||
* @apikey
|
||||
* @request body orderStatusIdsRequest
|
||||
* @response 200 orderStatusTransitionResponse success
|
||||
*/
|
||||
async audit() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.audit({ ids: this._pickIds() });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '批量审核失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 手工标记推送结果(待推送 → 委外中 / 异常)
|
||||
* @description 正常推送走「推送仓库」接口(真实递交 WMS),本接口用于无外部仓库时的手工流转,
|
||||
* 或修正外部实际结果:outcome=success 表示已推送成功(→ 委外中),
|
||||
* outcome=failed 表示推送失败(→ 异常,remark 记录失败原因并释放锁定库存)。
|
||||
* @router post /api/order-status/push
|
||||
* @apikey
|
||||
* @request body pushOrderStatusRequest
|
||||
* @response 200 orderStatusTransitionResponse success
|
||||
*/
|
||||
async push() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.push({
|
||||
ids: this._pickIds(),
|
||||
outcome: body.outcome,
|
||||
remark: body.remark,
|
||||
});
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '批量推送外部失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 批量转回待审核(异常 → 待审核)
|
||||
* @description 异常为侧路状态,可批量回流转正到待审核,重新走审核流程。
|
||||
* @router post /api/order-status/return-to-pending
|
||||
* @apikey
|
||||
* @request body orderStatusIdsRequest
|
||||
* @response 200 orderStatusTransitionResponse success
|
||||
*/
|
||||
async returnToPending() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.returnToPending({ ids: this._pickIds() });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '批量转回待审核失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 订单详情(单据头 + 商品明细)
|
||||
* @description 按索引表定位订单当前所在状态表并返回单据头,附商品明细、状态中文、店铺/仓库名称。
|
||||
* @router get /api/order-status/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 订单ID
|
||||
* @response 200 orderStatusDetailResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.detail({ id: ctx.params.id });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '查询订单详情失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 编辑订单(仅待审核 / 异常)
|
||||
* @description 未传入字段保持原值;仓库/店铺变更会同步刷新 warehouse_code / shop_nick 快照;
|
||||
* 收件人按「现值 + 本次变更」合并校验(姓名/省/市/区/镇必填,电话与手机至少一个)。
|
||||
* @router put /api/order-status/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 订单ID
|
||||
* @request body updateOrderStatusRequest
|
||||
* @response 200 orderStatusUpdateResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.update({ ...(ctx.request.body || {}), id: ctx.params.id });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '编辑订单失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除订单(仅待审核 / 异常 / 已取消)
|
||||
* @description 已审核及之后的订单禁止删除(可改为作废 / 取消);已锁定库存的订单会先释放锁定,避免锁定泄漏。
|
||||
* @router delete /api/order-status/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 订单ID
|
||||
* @response 200 orderStatusTransitionResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.remove({ ids: [ ctx.params.id ] });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '删除订单失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 商品明细(按订单ID)
|
||||
* @description 返回该订单的全部商品明细(行号升序),供详情抽屉与明细编辑弹窗使用。
|
||||
* @router get /api/order-status/items
|
||||
* @apikey
|
||||
* @request query integer order_id 订单ID(必填)
|
||||
* @response 200 orderStatusItemListResponse success
|
||||
*/
|
||||
async items() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.listItems({ order_id: ctx.query.order_id });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '查询商品明细失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 保存商品明细(整体替换,仅待审核 / 异常)
|
||||
* @description 明细整体覆盖写入并重算 item_total(数量合计)/ item_kind(种类数);
|
||||
* 校验口径与老发货单一致:plan_qty > 0、actual_price 必填、item_id/item_code 至少一个、行号不重复。
|
||||
* @router post /api/order-status/items
|
||||
* @apikey
|
||||
* @request body saveOrderStatusItemsRequest
|
||||
* @response 200 orderStatusItemListResponse success
|
||||
*/
|
||||
async saveItems() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.saveItems({ order_id: body.order_id, items: body.items });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '保存商品明细失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 驳回(待推送 → 待审核)
|
||||
* @description 与老发货单一致:驳回即换号(X → X_1 → X_2,避免重推被 WMS 判「单号已存在」),
|
||||
* 释放审核锁定库存并清空审核 / 推送痕迹(重试计数归零);
|
||||
* 已推送成功的(委外中)不支持驳回,请用「取消」(会同步取消外部单据)。
|
||||
* @router post /api/order-status/reject
|
||||
* @apikey
|
||||
* @request body orderStatusIdsRequest
|
||||
* @response 200 orderStatusSingleFlowResponse success
|
||||
*/
|
||||
async reject() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.reject({ ids: this._pickIds() });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '驳回订单失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 取消(待审核 / 异常 / 待推送 / 委外中 → 已取消)
|
||||
* @description 已推送成功(委外中)的在途订单会先调用 WMS order.cancel 取消外部单据,成功后释放锁定库存再流转;
|
||||
* 已配送 / 已作废 / 已取消不可取消。
|
||||
* @router post /api/order-status/cancel
|
||||
* @apikey
|
||||
* @request body cancelOrderStatusRequest
|
||||
* @response 200 orderStatusTransitionResponse success
|
||||
*/
|
||||
async cancel() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
try {
|
||||
const ids = this._pickIds();
|
||||
const data = await ctx.service.orderStatus.cancel({ ids, remark: body.remark });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '取消订单失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 作废(待审核 / 异常 / 待推送 → 已作废)
|
||||
* @description 记录作废人 / 作废时间 / 作废原因,并释放审核锁定库存;作废不可恢复也禁止删除;
|
||||
* 已推送成功的(委外中)请用「取消」。
|
||||
* @router post /api/order-status/void
|
||||
* @apikey
|
||||
* @request body voidOrderStatusRequest
|
||||
* @response 200 orderStatusTransitionResponse success
|
||||
*/
|
||||
async voidOrder() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.voidOrder({
|
||||
ids: this._pickIds(),
|
||||
void_reason: body.void_reason,
|
||||
remark: body.remark,
|
||||
});
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '作废订单失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 恢复(已取消 / 已作废 → 待审核)
|
||||
* @description 曾推送过的订单恢复时换号(WMS 侧单号唯一,取消/作废后原号仍被占用),
|
||||
* 并清空审核 / 推送痕迹与作废原因。
|
||||
* @router post /api/order-status/restore
|
||||
* @apikey
|
||||
* @request body orderStatusIdsRequest
|
||||
* @response 200 orderStatusSingleFlowResponse success
|
||||
*/
|
||||
async restore() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.restore({ ids: this._pickIds() });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '恢复订单失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 推送仓库(WMS deliveryorder.create)
|
||||
* @description 待推送订单立即递交一次到 WMS:成功流转「委外中」并写 wms_status/wms_order_no(等仓库回传确认进入配送);
|
||||
* 对方明确失败或连续 3 次无响应则转「异常」并释放锁定库存。
|
||||
* @router post /api/order-status/{id}/push-wms
|
||||
* @apikey
|
||||
* @request path integer *id 订单ID
|
||||
* @response 200 orderStatusPushWmsResponse success
|
||||
*/
|
||||
async pushWms() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const result = await ctx.service.orderWms.pushOne(ctx.params.id, { source: 'manual' });
|
||||
if (!result.ok) {
|
||||
ctx.status = result.skipped ? 400 : 502;
|
||||
ctx.body = { code: ctx.status, message: result.message };
|
||||
return;
|
||||
}
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: { id: Number(ctx.params.id), attempts: result.attempts, wms_response: result.response },
|
||||
};
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '推送仓库失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 批量推送仓库
|
||||
* @description 对选中的待推送订单顺序限流推送(每次最多 50 条,其余由定时任务继续),返回逐单结果。
|
||||
* @router post /api/order-status/push-wms
|
||||
* @apikey
|
||||
* @request body orderStatusIdsRequest
|
||||
* @response 200 orderStatusPushWmsBatchResponse success
|
||||
*/
|
||||
async pushWmsBatch() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const ids = this._pickIds().map(id => Number(id));
|
||||
const data = await ctx.service.orderWms.pushMany(ids);
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '批量推送仓库失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 批量切换仓库
|
||||
* @description 待审核 / 异常 / 待推送的订单可切换仓库(同步刷新 warehouse_code 快照);
|
||||
* 已推送仓库后不再变更(仓库编码已递交 WMS)。
|
||||
* @router post /api/order-status/change-warehouse
|
||||
* @apikey
|
||||
* @request body changeOrderStatusWarehouseRequest
|
||||
* @response 200 orderStatusChangeOwnerResponse success
|
||||
*/
|
||||
async changeWarehouse() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.changeWarehouse({ ids: this._pickIds(), warehouse_id: body.warehouse_id });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '切换仓库失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 批量设置所属店铺
|
||||
* @description 店铺只影响推送时的快递策略匹配(shopNick)与 OMS 记录、不回写 WMS,
|
||||
* 因此委外中也允许修正(同步刷新 shop_nick 快照)。
|
||||
* @router post /api/order-status/change-shop
|
||||
* @apikey
|
||||
* @request body changeOrderStatusShopRequest
|
||||
* @response 200 orderStatusChangeOwnerResponse success
|
||||
*/
|
||||
async changeShop() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.changeShop({ ids: this._pickIds(), shop_id: body.shop_id });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '设置所属店铺失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 智能识别收件人文本
|
||||
* @description 把「姓名 电话 地址」等自由文本解析为收件人字段,供新增/编辑表单一键填充。
|
||||
* @router post /api/order-status/parse-receiver
|
||||
* @apikey
|
||||
* @request body parseReceiverRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async parseReceiver() {
|
||||
const { ctx } = this;
|
||||
const text = String((ctx.request.body || {}).text || '').trim();
|
||||
if (!text) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'text(待识别的文本)为必填项' };
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const data = await ctx.service.ai.parseReceiver(text);
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '智能识别失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 归档到历史(写入归档时间 / 转入时间)
|
||||
* @description 传 ids 时归档指定订单;不传 ids 时归档当前主体下创建时间超过 months(默认 3)个月的订单。
|
||||
* 归档为物理迁移:状态表删除 + 历史表插入,并写入 archived_at / transferred_at。
|
||||
* 定时任务(app/schedule/orderArchive.js)同样走本逻辑,但跨主体处理。
|
||||
* @router post /api/order-status/archive
|
||||
* @apikey
|
||||
* @request body archiveOrderStatusRequest
|
||||
* @response 200 orderStatusArchiveResponse success
|
||||
*/
|
||||
async archive() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
try {
|
||||
const data = await ctx.service.orderStatus.archive({ ids: body.ids, months: body.months });
|
||||
ctx.body = { code: 0, message: 'success', data };
|
||||
} catch (err) {
|
||||
this._fail(ctx, err, '归档到历史失败');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderStatusController;
|
||||
@ -3,6 +3,7 @@
|
||||
const completeInbound = require('../utils/completeInbound');
|
||||
const { applyStockChange } = require('../utils/stockRecord');
|
||||
const { deductDeliveryStock } = require('../utils/deliveryStock');
|
||||
const { ORDER_STATUS, orderModelName, orderStatusLabel } = require('./orderStatus');
|
||||
|
||||
/**
|
||||
* 外部回调(对外通用回调接口 /openapi)驱动 OMS 单据的共用处理逻辑。
|
||||
@ -332,9 +333,15 @@ function toPlainObject(value) {
|
||||
* @return {String} 稳定字符串
|
||||
*/
|
||||
function stableStringify(value) {
|
||||
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map(stableStringify).join(',')}]`;
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
|
||||
const body = Object.keys(value)
|
||||
.sort()
|
||||
.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`)
|
||||
.join(',');
|
||||
return `{${body}}`;
|
||||
}
|
||||
return JSON.stringify(value === undefined ? null : value);
|
||||
}
|
||||
@ -834,9 +841,8 @@ async function confirmDelivery(ctx, { principalId, warehouseId, data }) {
|
||||
const code = pickFirst(payload, DELIVERY_CODE_PATHS);
|
||||
if (!code) return { ok: false, message: '缺少发货单号(deliveryOrderCode / outBizCode)' };
|
||||
|
||||
const order = await ctx.model.OrderDelivery.findOne({
|
||||
where: { delivery_order_code: code, principal_id: principalId },
|
||||
});
|
||||
const resolved = await resolveDeliveryBill(ctx, { code, principalId });
|
||||
const order = resolved.order;
|
||||
if (!order) return { ok: false, message: `未找到发货单:${code}` };
|
||||
// 历史单据可能没有 warehouse_id,仅在双方都有值时校验仓库归属
|
||||
if (order.warehouse_id && warehouseId && Number(order.warehouse_id) !== Number(warehouseId)) {
|
||||
@ -851,7 +857,17 @@ async function confirmDelivery(ctx, { principalId, warehouseId, data }) {
|
||||
if (!expressResult.ok) return { ok: false, message: expressResult.message };
|
||||
|
||||
// 运单号/物流公司回写:幂等(值未变化则不写库),已完成单据也允许补写缺失值
|
||||
const pkgInfo = await applyDeliveryPackageInfo(ctx, order, packages, { express: expressResult.first });
|
||||
const pkgInfo = await applyDeliveryPackageInfo(
|
||||
ctx,
|
||||
resolved.isNewModel ? wrapNewOrderView(resolved) : order,
|
||||
packages,
|
||||
{ express: expressResult.first }
|
||||
);
|
||||
|
||||
// 新表(order_index + 状态表):委外中 → 配送(扣减锁定库存),已配送幂等回执
|
||||
if (resolved.isNewModel) {
|
||||
return confirmOrderStatusDelivery(ctx, { resolved, payload, packages, lines, pkgInfo });
|
||||
}
|
||||
|
||||
// 幂等:已完成(4) 直接回成功,不再流转状态、不重复扣减库存(外部重复推送同一报文时返回相同结果)
|
||||
if (Number(order.status) === DELIVERY_STATUS_DONE) {
|
||||
@ -918,6 +934,108 @@ async function confirmDelivery(ctx, { principalId, warehouseId, data }) {
|
||||
return { ok: true, message: 'ok', data: result };
|
||||
}
|
||||
|
||||
/**
|
||||
* 定位发货单(订单):先查新表(order_index.order_no → 对应状态表),再回退老表(order_deliveries)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} options 参数
|
||||
* @param {String} options.code 外部回传的单号(deliveryOrderCode / outBizCode)
|
||||
* @param {Number} options.principalId 主体ID
|
||||
* @return {Promise<{isNewModel: Boolean, order: Object|null, index: Object|null}>} 定位结果
|
||||
*/
|
||||
async function resolveDeliveryBill(ctx, { code, principalId }) {
|
||||
const index = await ctx.model.OrderIndex.findOne({ where: { order_no: code, principal_id: principalId } });
|
||||
if (index) {
|
||||
const row = await ctx.model[orderModelName(index.current_status)].findByPk(index.id);
|
||||
if (row) return { isNewModel: true, order: row, index };
|
||||
}
|
||||
const legacy = await ctx.model.OrderDelivery.findOne({
|
||||
where: { delivery_order_code: code, principal_id: principalId },
|
||||
});
|
||||
return { isNewModel: false, order: legacy, index: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* 新表(状态表行)的视图包装:补齐 delivery_order_code 别名,并把 update 落到状态表
|
||||
* @param {Object} resolved resolveDeliveryBill 的返回
|
||||
* @return {Object} 供 applyDeliveryPackageInfo 使用的视图对象
|
||||
*/
|
||||
function wrapNewOrderView(resolved) {
|
||||
const order = resolved.order;
|
||||
const view = {
|
||||
...order.get({ plain: true }),
|
||||
delivery_order_code: resolved.index.order_no,
|
||||
update: async patch => {
|
||||
await order.update(patch);
|
||||
Object.assign(view, patch);
|
||||
},
|
||||
};
|
||||
return view;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新表发货确认:委外中 → 配送(扣减审核时锁定的库存),已配送幂等回执
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} options 参数
|
||||
* @param {Object} options.resolved resolveDeliveryBill 的返回
|
||||
* @param {Object} options.payload 归一化报文
|
||||
* @param {Array} options.packages 包裹数组
|
||||
* @param {Array} options.lines 发货明细行
|
||||
* @param {Object} options.pkgInfo 运单/物流回写结果
|
||||
* @return {Promise<Object>} 处理结果
|
||||
*/
|
||||
async function confirmOrderStatusDelivery(ctx, { resolved, payload, packages, lines, pkgInfo }) {
|
||||
const { order, index } = resolved;
|
||||
const base = {
|
||||
delivery_order_id: Number(order.id),
|
||||
delivery_order_code: index.order_no,
|
||||
express_code: pkgInfo.express_code,
|
||||
express_codes: pkgInfo.express_codes,
|
||||
logistics_code: pkgInfo.logistics_code,
|
||||
logistics_name: pkgInfo.logistics_name,
|
||||
package_updated: pkgInfo.changed,
|
||||
stock_locked: Number(order.stock_locked) === 1,
|
||||
};
|
||||
|
||||
// 幂等:已配送(已完成)再次收到相同报文只补写缺失字段,不重复流转、不重复扣减库存
|
||||
if (index.current_status === ORDER_STATUS.DELIVERY) {
|
||||
const done = { ...base, status: ORDER_STATUS.DELIVERY, already_completed: true };
|
||||
ctx.logger.info('[order-callback] 订单已配送,跳过(幂等回执)', done);
|
||||
return { ok: true, message: 'ok', data: done };
|
||||
}
|
||||
if (index.current_status !== ORDER_STATUS.OUTSOURCING) {
|
||||
return {
|
||||
ok: false,
|
||||
message: `单据 ${index.order_no} 当前状态(${orderStatusLabel(index.current_status)})不允许发货确认,需为「委外中」`,
|
||||
};
|
||||
}
|
||||
|
||||
const d = (payload && payload.deliveryOrder) || {};
|
||||
const externalId = toNumberOrNull(d.deliveryOrderId);
|
||||
const now = new Date();
|
||||
const prev = order.wms_push_result && typeof order.wms_push_result === 'object' ? order.wms_push_result : {};
|
||||
// 推送结果与确认报文摘要先回写,随状态流转一并搬到配送表
|
||||
await order.update({
|
||||
wms_status: 'delivered',
|
||||
wms_order_no: externalId == null ? order.wms_order_no : String(externalId),
|
||||
wms_synced_at: now,
|
||||
wms_push_result: { ...prev, confirm: buildDeliveryConfirmSummary(payload, packages, lines) },
|
||||
});
|
||||
|
||||
await ctx.service.orderStatus.confirmDelivery({
|
||||
ids: [ Number(order.id) ],
|
||||
principalId: Number(order.principal_id),
|
||||
});
|
||||
|
||||
const result = {
|
||||
...base,
|
||||
status: ORDER_STATUS.DELIVERY,
|
||||
already_completed: false,
|
||||
line_count: (lines || []).length,
|
||||
};
|
||||
ctx.logger.info('[order-callback] 订单发货确认完成', result);
|
||||
return { ok: true, message: 'ok', data: result };
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单取消通知(order.cancel):外部已取消该单据
|
||||
* 未完成(≠4)的单据置为「已取消(9)」;出库单若已推送(3)则同时释放锁定库存
|
||||
@ -1009,5 +1127,6 @@ module.exports = {
|
||||
matchInbound,
|
||||
confirmOutbound,
|
||||
confirmDelivery,
|
||||
resolveDeliveryBill,
|
||||
cancelOrder,
|
||||
};
|
||||
|
||||
271
backend/app/lib/orderFields.js
Normal file
271
backend/app/lib/orderFields.js
Normal file
@ -0,0 +1,271 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单状态表 / 历史表 / 明细表的字段口径(唯一来源,供模型与迁移共用)。
|
||||
*
|
||||
* 设计口径:新表结构是「原订单表 orders + 发货单 order_deliveries(含其明细表)」的**超集**——
|
||||
* 老表任一个字段都能在新表找到同名、同类型的落点,保证老数据可以无损迁入(不允许再出现字段丢失)。
|
||||
*
|
||||
* 字段分三组:
|
||||
* 1) CORE 状态流程核心字段(order_no/parent_order_no/shop_id/product_info/receiver/address/status/remark)
|
||||
* 2) LEGACY_ORDER 原订单表 orders 的字段(order_type、wms_ 系列、submit_ 系列、total_amount、pay_amount)
|
||||
* 3) LEGACY_DELIVERY 发货单 order_deliveries 的字段(仓库/物流/收件人 12 项/金额 6 项/推送与审核作废痕迹等)
|
||||
*
|
||||
* 老字段 → 新字段的映射(不能同名落地的):
|
||||
* - orders.order_no、order_deliveries.delivery_order_code → order_no
|
||||
* - orders.receiver(JSON { name, phone, address })→ receiver / tel / mobile / address
|
||||
* - orders.status(1待处理 2处理中 3已完成 4已取消)与 order_deliveries.status
|
||||
* (1待处理 2已审核 3已推送 4已完成 5已作废 9已取消)→ status(订单流程状态,见 app/lib/orderStatus.js)
|
||||
* - orders.id、order_deliveries.id → id(= order_index.id)
|
||||
* - order_deliveries.name → receiver;detail_address 保留同名列,address 为省市区镇+详细地址的汇总快照
|
||||
* - 明细:order_items.name → item_name,order_delivery_items.order_delivery_id / order_items.order_id → order_id
|
||||
*/
|
||||
|
||||
/**
|
||||
* 状态流程核心字段(状态表与历史表共用)
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @param {String} status 该表的默认状态
|
||||
* @return {Object} 字段定义
|
||||
*/
|
||||
function coreColumns(Sequelize, status) {
|
||||
const { BIGINT, STRING, JSON: JsonType } = Sequelize;
|
||||
return {
|
||||
order_no: { type: STRING(50), allowNull: false, comment: '订单号(老 order_no / delivery_order_code)' },
|
||||
parent_order_no: { type: STRING(50), comment: '来源订单号(上游/平台订单号)' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' },
|
||||
shop_id: { type: BIGINT.UNSIGNED, comment: '店铺ID' },
|
||||
product_info: { type: JsonType, comment: '商品明细快照(JSON 数组;结构化明细见 order_status_items)' },
|
||||
receiver: { type: STRING(50), comment: '收货人(老 orders.receiver.name / order_deliveries.name)' },
|
||||
address: { type: STRING(255), comment: '收货地址(省市区镇 + 详细地址的汇总快照)' },
|
||||
status: {
|
||||
type: STRING(16),
|
||||
allowNull: false,
|
||||
defaultValue: status,
|
||||
comment: '流程状态:pending 待审核 / exception 异常 / outsourcing 委外中 / delivery 配送 / history 历史',
|
||||
},
|
||||
remark: { type: STRING(255), comment: '备注 / 异常原因' },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 原订单表 orders 的字段(超集,保证老数据可无损迁入)
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Object} 字段定义
|
||||
*/
|
||||
function orderLegacyColumns(Sequelize) {
|
||||
const { STRING, TINYINT, DECIMAL, DATE } = Sequelize;
|
||||
return {
|
||||
order_type: { type: STRING(50), allowNull: false, defaultValue: 'JYCK', comment: '订单类型(老 orders.order_type 数值转为字符串;发货单口径为 WMS 编码 JYCK/HHCK/BFCK)' },
|
||||
wms_status: { type: STRING(50), comment: '外部WMS状态(如 CREATED/PICKING/SHIPPED,由回调回写)' },
|
||||
wms_order_no: { type: STRING(50), comment: '外部WMS单号' },
|
||||
wms_synced_at: { type: DATE, comment: '最近一次 WMS 同步时间' },
|
||||
submit_status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '上交状态:0未上交 1上交中 2已上交 3上交失败' },
|
||||
submit_order_no: { type: STRING(50), comment: '上交后返回的单号' },
|
||||
submit_at: { type: DATE, comment: '上交时间' },
|
||||
submit_msg: { type: STRING(255), comment: '上交结果 / 失败原因' },
|
||||
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '订单总金额' },
|
||||
pay_amount: { type: DECIMAL(12, 2), comment: '实付金额' },
|
||||
legacy_status: { type: TINYINT.UNSIGNED, comment: '迁移来源的老状态原值(orders.status / order_deliveries.status);流程状态见 status' },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 发货单 order_deliveries 的字段(超集,保证老数据可无损迁入)
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Object} 字段定义
|
||||
*/
|
||||
function deliveryLegacyColumns(Sequelize) {
|
||||
const { BIGINT, STRING, TEXT, TINYINT, INTEGER, DECIMAL, DATE, ENUM, JSON: JsonType } = Sequelize;
|
||||
return {
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, comment: '仓库ID(关联 warehouses)' },
|
||||
warehouse_code: { type: STRING(50), comment: '仓库编码(报文 warehouseCode 快照)' },
|
||||
order_flag: { type: TEXT, comment: '订单标记' },
|
||||
pre_delivery_order_code: { type: STRING(50), comment: '预发货单号' },
|
||||
pre_delivery_order_id: { type: STRING(50), comment: '预发货单ID' },
|
||||
is_urgency: { type: ENUM('Y', 'N'), defaultValue: 'N', comment: '是否紧急:Y是 N否(默认 N)' },
|
||||
invoice_flag: { type: ENUM('Y', 'N'), defaultValue: 'N', comment: '是否需要发票:Y是 N否(默认 N)' },
|
||||
source_platform_code: { type: STRING(50), comment: '来源平台编码' },
|
||||
source_platform_name: { type: STRING(200), comment: '来源平台名称' },
|
||||
shop_nick: { type: STRING(200), comment: '店铺名称' },
|
||||
seller_nick: { type: STRING(200), comment: '卖家名称' },
|
||||
buyer_nick: { type: STRING(200), comment: '买家名称' },
|
||||
buyer_message: { type: STRING(500), comment: '买家留言' },
|
||||
seller_message: { type: STRING(500), comment: '卖家留言' },
|
||||
place_order_time: { type: DATE, comment: '店铺创建订单时间' },
|
||||
pay_time: { type: DATE, comment: '支付时间' },
|
||||
pay_no: { type: STRING(50), comment: '支付单号' },
|
||||
operate_time: { type: DATE, comment: 'ERP 审核时间' },
|
||||
item_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '商品总金额(按明细派生)' },
|
||||
discount_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '订单折扣金额' },
|
||||
freight: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '快递费用' },
|
||||
ar_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '应收金额' },
|
||||
got_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '已收金额' },
|
||||
logistics_code: { type: STRING(50), comment: '物流公司编码(WMS 标准编码,如 SF/YTO)' },
|
||||
logistics_name: { type: STRING(200), comment: '物流公司名称' },
|
||||
express_code: { type: STRING(50), comment: '运单号(面单号)' },
|
||||
express_codes: { type: JsonType, comment: '运单号集合(多包裹)' },
|
||||
logistics_area_code: { type: STRING(50), comment: '快递区域编码' },
|
||||
operator_name: { type: STRING(50), comment: '操作人 / 审核人(奇门 operatorName)' },
|
||||
oaid_order_source_code: { type: STRING(50), comment: 'OAID 订单来源编码' },
|
||||
source_order_codes: { type: TEXT, comment: '来源订单号集合' },
|
||||
extend_props: { type: JsonType, comment: '请求级扩展属性(如 ewaybill_order_code)' },
|
||||
need_oms_waybill: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '是否需要回 OMS 取号:0否 1是' },
|
||||
tel: { type: STRING(50), comment: '收货人电话' },
|
||||
mobile: { type: STRING(50), comment: '收货人手机号' },
|
||||
email: { type: STRING(100), comment: '收货人邮箱' },
|
||||
country_code: { type: STRING(50), comment: '国家编码' },
|
||||
province: { type: STRING(100), comment: '省份' },
|
||||
city: { type: STRING(100), comment: '城市' },
|
||||
area: { type: STRING(100), comment: '区县' },
|
||||
town: { type: STRING(100), comment: '街道/镇' },
|
||||
detail_address: { type: STRING(500), comment: '详细地址' },
|
||||
zip_code: { type: STRING(20), comment: '邮编' },
|
||||
oaid: { type: STRING(100), comment: 'OAID' },
|
||||
stock_locked: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '库存锁定标记:1=当前占用锁定库存 0=未锁定' },
|
||||
shop_sync_status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '回传平台店铺状态:0未同步 1同步中 2同步成功 3同步失败' },
|
||||
shop_sync_retry_count: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '回传平台店铺的重试次数' },
|
||||
created_by: { type: BIGINT.UNSIGNED, comment: '创建人ID(关联 users)' },
|
||||
pushed_at: { type: DATE, comment: 'WMS 推送时间' },
|
||||
wms_push_result: { type: JsonType, comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)' },
|
||||
legacy_order_id: { type: BIGINT.UNSIGNED, comment: '迁移来源主键(orders.id / order_deliveries.id;非迁移数据为 NULL)' },
|
||||
legacy_source: { type: STRING(30), comment: '迁移来源表:orders / order_deliveries(非迁移数据为 NULL)' },
|
||||
item_total: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '商品总数(明细计划数量合计)' },
|
||||
item_kind: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '商品种类数(不重复商品数)' },
|
||||
audit_by: { type: BIGINT.UNSIGNED, comment: '审核人ID(关联 users)' },
|
||||
audit_time: { type: DATE, comment: '审核时间' },
|
||||
void_at: { type: DATE, comment: '作废时间' },
|
||||
void_by: { type: BIGINT.UNSIGNED, comment: '作废人ID(关联 users)' },
|
||||
void_reason: { type: STRING(255), comment: '作废原因' },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态表 / 历史表的业务字段(CORE + 两套老表字段 = 老表超集)
|
||||
* @param {Object} Sequelize sequelize 构造函数(模型文件里的 app.Sequelize)
|
||||
* @param {String} status 该表的默认状态(pending/exception/outsourcing/delivery/history)
|
||||
* @return {Object} 模型字段定义
|
||||
*/
|
||||
function businessFields(Sequelize, status) {
|
||||
const { BIGINT, DATE } = Sequelize;
|
||||
return {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, comment: '主键(= order_index.id,全局唯一,订单 ID 以此为准)' },
|
||||
...coreColumns(Sequelize, status),
|
||||
...orderLegacyColumns(Sequelize),
|
||||
...deliveryLegacyColumns(Sequelize),
|
||||
created_at: { type: DATE, comment: '创建时间(用于超 3 个月自动归档判断)' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 历史表额外字段:归档时间与转入时间
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Object} 模型字段定义
|
||||
*/
|
||||
function historyFields(Sequelize) {
|
||||
const { DATE } = Sequelize;
|
||||
return {
|
||||
archived_at: { type: DATE, comment: '归档时间(转入历史表时写入)' },
|
||||
transferred_at: { type: DATE, comment: '转入时间(状态流转进入历史的时间)' },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 明细表 order_status_items 的字段(order_delivery_items ∪ order_items 的超集)
|
||||
*
|
||||
* 5 张状态表共用这一张明细表(按 order_id 关联,订单 ID 取自 order_index),
|
||||
* 老的两套明细字段都保留,保证无字段丢失;落地时按需填充(发货单口径字段优先)。
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Object} 模型字段定义
|
||||
*/
|
||||
function itemFields(Sequelize) {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, DATE, JSON: JsonType } = Sequelize;
|
||||
return {
|
||||
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 / 状态表 id)' },
|
||||
shop_id: { type: BIGINT.UNSIGNED, comment: '店铺ID(老 order_items.shop_id)' },
|
||||
order_line_no: { type: STRING(20), allowNull: false, defaultValue: '', comment: '行号(老 order_delivery_items.order_line_no,缺省按行序号)' },
|
||||
item_id: { type: BIGINT.UNSIGNED, comment: 'WMS 内部商品ID(取自 warehouse_products.wms_item_id)' },
|
||||
item_code: { type: STRING(100), comment: '商品编码' },
|
||||
item_name: { type: STRING(255), comment: '商品名称(老 order_items.name)' },
|
||||
plan_qty: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '计划数量(发货单口径)' },
|
||||
actual_price: { type: DECIMAL(12, 2), comment: '实际单价(发货单口径)' },
|
||||
retail_price: { type: DECIMAL(12, 2), comment: '零售价' },
|
||||
ext_code: { type: STRING(100), comment: '外部编码(extCode)' },
|
||||
inventory_type: { type: STRING(10), allowNull: false, defaultValue: 'ZP', comment: '库存类型:ZP=正品 CC=残次' },
|
||||
source_order_code: { type: STRING(50), comment: '来源订单编码' },
|
||||
sub_source_order_code: { type: STRING(50), comment: '子来源订单编码' },
|
||||
stock_id: { type: BIGINT.UNSIGNED, comment: 'WMS 仓库库存ID(stockId)' },
|
||||
extend_props: { type: JsonType, comment: '扩展属性(extendProps)' },
|
||||
legacy_order_item_id: { type: BIGINT.UNSIGNED, comment: '迁移来源明细主键(order_items.id / order_delivery_items.id)' },
|
||||
legacy_source: { type: STRING(30), comment: '迁移来源表:order_items / order_delivery_items(非迁移数据为 NULL)' },
|
||||
product_id: { type: BIGINT.UNSIGNED, comment: '系统商品ID(老 order_items.product_id)' },
|
||||
combo_product_id: { type: BIGINT.UNSIGNED, comment: '组合商品ID(老 order_items.combo_product_id)' },
|
||||
shop_product_id: { type: BIGINT.UNSIGNED, comment: '命中的店铺商品ID(老 order_items.shop_product_id)' },
|
||||
item_type: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '明细类型(老 order_items.item_type):0未识别 1普通商品 2组合商品' },
|
||||
parse_status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '解析状态(老 order_items.parse_status):0未解析 1已解析 2解析失败' },
|
||||
parse_msg: { type: STRING(255), comment: '解析失败原因(老 order_items.parse_msg)' },
|
||||
outer_item_id: { type: STRING(100), comment: '平台商品ID(老 order_items.outer_item_id)' },
|
||||
outer_sku_id: { type: STRING(100), comment: '平台规格ID(老 order_items.outer_sku_id)' },
|
||||
sku_code: { type: STRING(100), comment: '商家编码(老 order_items.sku_code)' },
|
||||
spec: { type: STRING(255), comment: '规格(快照)' },
|
||||
image: { type: STRING(255), comment: '图片(快照)' },
|
||||
quantity: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '数量(老 order_items.quantity)' },
|
||||
price: { type: DECIMAL(12, 2), comment: '单价(老 order_items.price)' },
|
||||
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '明细金额(老 order_items.total_amount)' },
|
||||
raw: { type: JsonType, comment: '平台返回的明细原始数据(老 order_items.raw)' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
};
|
||||
}
|
||||
|
||||
/** 流转搬运时排除的字段(id 由索引表决定,status 由目标状态决定,时间戳单独处理) */
|
||||
const COPY_EXCLUDE = [ 'id', 'status', 'created_at', 'updated_at' ];
|
||||
|
||||
/**
|
||||
* 流转时需要整体搬运的业务列名(除 id/status/created_at/updated_at 外的全部业务列)
|
||||
* 由字段定义派生,避免新增字段时漏搬。
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Array<String>} 列名数组
|
||||
*/
|
||||
function copyColumnNames(Sequelize) {
|
||||
return Object.keys(businessFields(Sequelize, 'pending')).filter(name => !COPY_EXCLUDE.includes(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 相对「状态流程核心字段」扩展出来的列名(= 为容纳老表而新增的字段),供迁移 down 精确回退
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Array<String>} 列名数组
|
||||
*/
|
||||
function legacyExtraColumnNames(Sequelize) {
|
||||
return [
|
||||
...Object.keys(orderLegacyColumns(Sequelize)),
|
||||
...Object.keys(deliveryLegacyColumns(Sequelize)),
|
||||
].filter((name, index, arr) => arr.indexOf(name) === index);
|
||||
}
|
||||
|
||||
/**
|
||||
* 非空且有默认值的业务列名(如 total_amount / item_amount / discount_amount / freight 等金额列)
|
||||
*
|
||||
* 用途:请求里显式传 null 时跳过该列,落库由默认值兜底(否则会触发 notNull Violation)。
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Array<String>} 列名数组
|
||||
*/
|
||||
function notNullDefaultColumnNames(Sequelize) {
|
||||
const fields = businessFields(Sequelize, 'pending');
|
||||
return Object.keys(fields).filter(name => fields[name].allowNull === false && fields[name].defaultValue !== undefined);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
coreColumns,
|
||||
orderLegacyColumns,
|
||||
deliveryLegacyColumns,
|
||||
businessFields,
|
||||
historyFields,
|
||||
itemFields,
|
||||
copyColumnNames,
|
||||
legacyExtraColumnNames,
|
||||
notNullDefaultColumnNames,
|
||||
COPY_EXCLUDE,
|
||||
};
|
||||
40
backend/app/lib/orderReceiver.js
Normal file
40
backend/app/lib/orderReceiver.js
Normal file
@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单收件人信息校验(与发货单口径一致,见 app/controller/orderDelivery.js#validateReceiver)
|
||||
* - 必填:姓名 / 省 / 市 / 区 / 街道(镇)
|
||||
* - 电话(tel)与手机(mobile)至少填写一个
|
||||
*/
|
||||
|
||||
/** 收件人必填字段(对齐取号硬依赖) */
|
||||
const RECEIVER_REQUIRED_FIELDS = [
|
||||
[ 'name', '收件人姓名' ],
|
||||
[ 'province', '省份' ],
|
||||
[ 'city', '城市' ],
|
||||
[ 'area', '区县' ],
|
||||
[ 'town', '街道/镇' ],
|
||||
];
|
||||
|
||||
/**
|
||||
* 校验收件人信息
|
||||
* @param {Object} data 待校验数据(可为记录现值 + 本次变更合并后的结果)
|
||||
* @return {String} 错误信息,校验通过返回空串
|
||||
*/
|
||||
function validateReceiver(data) {
|
||||
const source = data || {};
|
||||
// 老单据的收件人姓名可能落在 receiver 列上(新表核心字段),合并判断
|
||||
const merged = { ...source, name: source.name || source.receiver };
|
||||
for (const [ key, label ] of RECEIVER_REQUIRED_FIELDS) {
|
||||
const value = merged[key] == null ? '' : String(merged[key]).trim();
|
||||
if (!value) return `收件人信息不完整:${label}为必填项`;
|
||||
}
|
||||
const tel = merged.tel == null ? '' : String(merged.tel).trim();
|
||||
const mobile = merged.mobile == null ? '' : String(merged.mobile).trim();
|
||||
if (!tel && !mobile) return '收件人信息不完整:电话(tel)与手机(mobile)至少填写一个';
|
||||
return '';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
RECEIVER_REQUIRED_FIELDS,
|
||||
validateReceiver,
|
||||
};
|
||||
189
backend/app/lib/orderStatus.js
Normal file
189
backend/app/lib/orderStatus.js
Normal file
@ -0,0 +1,189 @@
|
||||
'use strict';
|
||||
|
||||
const { copyColumnNames } = require('./orderFields');
|
||||
|
||||
/**
|
||||
* 订单状态与「所在表」口径的唯一来源。
|
||||
*
|
||||
* 订单按状态分表存储,订单 ID 全局唯一(取自 order_index):
|
||||
* - order_index 订单索引表:current_table / current_status 记录订单当前所在表与状态
|
||||
* - order_status_pending 待审核
|
||||
* - order_status_queued 待推送(审核通过、已锁定库存,等待推送仓库)
|
||||
* - order_status_exception 异常
|
||||
* - order_status_outsourcing 委外中(推送仓库成功,等仓库回传发货确认)
|
||||
* - order_status_delivery 配送
|
||||
* - order_status_void 已作废(侧路:审核后不再走履约)
|
||||
* - order_status_canceled 已取消(侧路:可恢复回待审核)
|
||||
* - order_status_history 历史(多 archived_at 归档时间 / transferred_at 转入时间)
|
||||
* - order_status_items 明细表(各状态表共用,字段为发货单明细 ∪ 原订单明细的超集)
|
||||
*
|
||||
* 生命周期:待审核 →(审核+锁库存)待推送 →(推送仓库成功)委外中 →(仓库回传确认)配送
|
||||
* →(创建时间超 3 个月)历史;
|
||||
* 侧路状态:异常(推送仓库失败进入,可回流转正)、已作废、已取消(可恢复)。
|
||||
*/
|
||||
|
||||
/** 状态枚举(同时也是 current_table / current_status 的取值与页面 tab 的 key) */
|
||||
const ORDER_STATUS = {
|
||||
PENDING: 'pending',
|
||||
QUEUED: 'queued',
|
||||
EXCEPTION: 'exception',
|
||||
OUTSOURCING: 'outsourcing',
|
||||
DELIVERY: 'delivery',
|
||||
VOID: 'void',
|
||||
CANCELED: 'canceled',
|
||||
HISTORY: 'history',
|
||||
};
|
||||
|
||||
/** 状态 → 中文标签 */
|
||||
const ORDER_STATUS_LABELS = {
|
||||
[ORDER_STATUS.PENDING]: '待审核',
|
||||
[ORDER_STATUS.QUEUED]: '待推送',
|
||||
[ORDER_STATUS.EXCEPTION]: '异常',
|
||||
[ORDER_STATUS.OUTSOURCING]: '委外中',
|
||||
[ORDER_STATUS.DELIVERY]: '配送',
|
||||
[ORDER_STATUS.VOID]: '已作废',
|
||||
[ORDER_STATUS.CANCELED]: '已取消',
|
||||
[ORDER_STATUS.HISTORY]: '历史',
|
||||
};
|
||||
|
||||
/** 页面左侧 tab 顺序(也是状态展示顺序;历史(归档)放最后) */
|
||||
const ORDER_STATUS_ORDER = [
|
||||
ORDER_STATUS.PENDING,
|
||||
ORDER_STATUS.QUEUED,
|
||||
ORDER_STATUS.EXCEPTION,
|
||||
ORDER_STATUS.OUTSOURCING,
|
||||
ORDER_STATUS.DELIVERY,
|
||||
ORDER_STATUS.VOID,
|
||||
ORDER_STATUS.CANCELED,
|
||||
ORDER_STATUS.HISTORY,
|
||||
];
|
||||
|
||||
/** 活动状态(非历史,各自一张状态表) */
|
||||
const ORDER_ACTIVE_STATUSES = [
|
||||
ORDER_STATUS.PENDING,
|
||||
ORDER_STATUS.QUEUED,
|
||||
ORDER_STATUS.EXCEPTION,
|
||||
ORDER_STATUS.OUTSOURCING,
|
||||
ORDER_STATUS.DELIVERY,
|
||||
ORDER_STATUS.VOID,
|
||||
ORDER_STATUS.CANCELED,
|
||||
];
|
||||
|
||||
/** 状态表统一前缀:表名 = `${ORDER_TABLE_PREFIX}${status}` */
|
||||
const ORDER_TABLE_PREFIX = 'order_status_';
|
||||
|
||||
/** 订单索引表表名 */
|
||||
const ORDER_INDEX_TABLE = 'order_index';
|
||||
|
||||
/** 订单明细表表名(各状态表共用) */
|
||||
const ORDER_ITEM_TABLE = 'order_status_items';
|
||||
|
||||
/** 订单明细表模型名 */
|
||||
const ORDER_ITEM_MODEL = 'OrderStatusItem';
|
||||
|
||||
/** 状态 → 所在表名 */
|
||||
const ORDER_TABLE_BY_STATUS = ORDER_STATUS_ORDER.reduce((acc, status) => {
|
||||
acc[status] = `${ORDER_TABLE_PREFIX}${status}`;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
/** 状态 → 模型名(ctx.model.xxx,对应 app/model 下的文件名) */
|
||||
const ORDER_MODEL_BY_STATUS = {
|
||||
[ORDER_STATUS.PENDING]: 'OrderStatusPending',
|
||||
[ORDER_STATUS.QUEUED]: 'OrderStatusQueued',
|
||||
[ORDER_STATUS.EXCEPTION]: 'OrderStatusException',
|
||||
[ORDER_STATUS.OUTSOURCING]: 'OrderStatusOutsourcing',
|
||||
[ORDER_STATUS.DELIVERY]: 'OrderStatusDelivery',
|
||||
[ORDER_STATUS.VOID]: 'OrderStatusVoid',
|
||||
[ORDER_STATUS.CANCELED]: 'OrderStatusCanceled',
|
||||
[ORDER_STATUS.HISTORY]: 'OrderStatusHistory',
|
||||
};
|
||||
|
||||
/**
|
||||
* 流转时需要整体搬运的业务列名(由字段定义派生,新增字段自动纳入,避免漏搬)
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Array<String>} 列名数组
|
||||
*/
|
||||
function orderCopyFields(Sequelize) {
|
||||
return copyColumnNames(Sequelize);
|
||||
}
|
||||
|
||||
/** 超期归档阈值(月):创建时间超过该月数的订单由定时任务归档到历史表 */
|
||||
const ORDER_ARCHIVE_MONTHS = 3;
|
||||
|
||||
/** 枚举列表(下拉/提示用,按 tab 顺序) */
|
||||
const ORDER_STATUS_LIST = ORDER_STATUS_ORDER.map(value => ({
|
||||
value,
|
||||
label: ORDER_STATUS_LABELS[value],
|
||||
}));
|
||||
|
||||
/**
|
||||
* 是否为合法状态值
|
||||
* @param {*} value 原值
|
||||
* @return {Boolean} 合法返回 true
|
||||
*/
|
||||
function isValidOrderStatus(value) {
|
||||
return Object.prototype.hasOwnProperty.call(ORDER_STATUS_LABELS, String(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化状态值
|
||||
* @param {*} value 原值
|
||||
* @param {String} [fallback] 非法值兜底(默认返回 null)
|
||||
* @return {String|null} 合法状态值
|
||||
*/
|
||||
function normalizeOrderStatus(value, fallback) {
|
||||
const status = String(value == null ? '' : value).trim().toLowerCase();
|
||||
return isValidOrderStatus(status) ? status : (fallback || null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态对应的中文标签
|
||||
* @param {*} value 状态值
|
||||
* @return {String} 中文标签(未知状态原样返回)
|
||||
*/
|
||||
function orderStatusLabel(value) {
|
||||
const status = normalizeOrderStatus(value);
|
||||
return status ? ORDER_STATUS_LABELS[status] : String(value == null ? '' : value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态对应的表名
|
||||
* @param {*} value 状态值
|
||||
* @return {String|null} 表名
|
||||
*/
|
||||
function orderTableOf(value) {
|
||||
const status = normalizeOrderStatus(value);
|
||||
return status ? ORDER_TABLE_BY_STATUS[status] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态对应的模型名
|
||||
* @param {*} value 状态值
|
||||
* @return {String|null} 模型名
|
||||
*/
|
||||
function orderModelName(value) {
|
||||
const status = normalizeOrderStatus(value);
|
||||
return status ? ORDER_MODEL_BY_STATUS[status] : null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ORDER_STATUS,
|
||||
ORDER_STATUS_LABELS,
|
||||
ORDER_STATUS_ORDER,
|
||||
ORDER_ACTIVE_STATUSES,
|
||||
ORDER_TABLE_PREFIX,
|
||||
ORDER_INDEX_TABLE,
|
||||
ORDER_ITEM_TABLE,
|
||||
ORDER_ITEM_MODEL,
|
||||
ORDER_TABLE_BY_STATUS,
|
||||
ORDER_MODEL_BY_STATUS,
|
||||
ORDER_STATUS_LIST,
|
||||
ORDER_ARCHIVE_MONTHS,
|
||||
orderCopyFields,
|
||||
isValidOrderStatus,
|
||||
normalizeOrderStatus,
|
||||
orderStatusLabel,
|
||||
orderTableOf,
|
||||
orderModelName,
|
||||
};
|
||||
32
backend/app/model/orderIndex.js
Normal file
32
backend/app/model/orderIndex.js
Normal file
@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
|
||||
const { ORDER_INDEX_TABLE } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 订单索引表(order_index)
|
||||
*
|
||||
* 订单的**全局唯一 ID 以本表为准**:各状态表与历史表的主键都取自本表 id,
|
||||
* 另通过 current_table 记录订单当前所在状态表、current_status 记录当前状态,
|
||||
* 便于「不依赖具体状态表」地定位任一订单(批量流转时按索引表分组处理)。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderIndex model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const OrderIndex = app.model.define(ORDER_INDEX_TABLE, {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键(订单全局唯一 ID)' },
|
||||
order_no: { type: STRING(50), allowNull: false, comment: '订单号' },
|
||||
parent_order_no: { type: STRING(50), comment: '来源订单号(上游/平台订单号)' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' },
|
||||
current_table: { type: STRING(16), allowNull: false, defaultValue: 'pending', comment: '当前所在表:pending/exception/outsourcing/delivery/history' },
|
||||
current_status: { type: STRING(16), allowNull: false, defaultValue: 'pending', comment: '当前状态:pending 待审核 / exception 异常 / outsourcing 委外中 / delivery 配送 / history 历史' },
|
||||
created_at: { type: DATE, comment: '创建时间(用于超 3 个月自动归档判断)' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: ORDER_INDEX_TABLE,
|
||||
comment: '订单索引表(订单 ID 以此为准)',
|
||||
});
|
||||
|
||||
return OrderIndex;
|
||||
};
|
||||
22
backend/app/model/orderStatusCanceled.js
Normal file
22
backend/app/model/orderStatusCanceled.js
Normal file
@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
const { businessFields } = require('../lib/orderFields');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 已取消订单表(order_status_canceled)
|
||||
*
|
||||
* 侧路状态:老流程的「取消」(可恢复到待审核重新流转);已推送外部时需先取消外部单据再流转。
|
||||
* 创建时间超过 3 个月时由归档任务转入历史表。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusCanceled model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const tableName = ORDER_TABLE_BY_STATUS[ORDER_STATUS.CANCELED];
|
||||
const OrderStatusCanceled = app.model.define(tableName, businessFields(app.Sequelize, ORDER_STATUS.CANCELED), {
|
||||
tableName,
|
||||
comment: '订单-已取消',
|
||||
});
|
||||
|
||||
return OrderStatusCanceled;
|
||||
};
|
||||
21
backend/app/model/orderStatusDelivery.js
Normal file
21
backend/app/model/orderStatusDelivery.js
Normal file
@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
|
||||
const { businessFields } = require('../lib/orderFields');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 配送中订单表(order_status_delivery)
|
||||
*
|
||||
* 外部系统回传履约结果后进入;创建时间超过 3 个月时由归档任务转入历史表。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusDelivery model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const tableName = ORDER_TABLE_BY_STATUS[ORDER_STATUS.DELIVERY];
|
||||
const OrderStatusDelivery = app.model.define(tableName, businessFields(app.Sequelize, ORDER_STATUS.DELIVERY), {
|
||||
tableName,
|
||||
comment: '订单-配送',
|
||||
});
|
||||
|
||||
return OrderStatusDelivery;
|
||||
};
|
||||
21
backend/app/model/orderStatusException.js
Normal file
21
backend/app/model/orderStatusException.js
Normal file
@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
|
||||
const { businessFields } = require('../lib/orderFields');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 异常订单表(order_status_exception)
|
||||
*
|
||||
* 侧路状态:委外中推送外部失败时进入;可批量转回待审核,或直接审核通过进入委外中。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusException model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const tableName = ORDER_TABLE_BY_STATUS[ORDER_STATUS.EXCEPTION];
|
||||
const OrderStatusException = app.model.define(tableName, businessFields(app.Sequelize, ORDER_STATUS.EXCEPTION), {
|
||||
tableName,
|
||||
comment: '订单-异常',
|
||||
});
|
||||
|
||||
return OrderStatusException;
|
||||
};
|
||||
27
backend/app/model/orderStatusHistory.js
Normal file
27
backend/app/model/orderStatusHistory.js
Normal file
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
const { businessFields, historyFields } = require('../lib/orderFields');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 历史订单表(order_status_history)
|
||||
*
|
||||
* 结构与 4 张状态表一致,另加:
|
||||
* - archived_at 归档时间(转入历史表时写入)
|
||||
* - transferred_at 转入时间(状态流转进入历史的时间)
|
||||
* 归档为物理迁移(状态表删除 + 本表插入),页面「历史」tab 只读展示。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusHistory model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const tableName = ORDER_TABLE_BY_STATUS[ORDER_STATUS.HISTORY];
|
||||
const OrderStatusHistory = app.model.define(tableName, {
|
||||
...businessFields(app.Sequelize, ORDER_STATUS.HISTORY),
|
||||
...historyFields(app.Sequelize),
|
||||
}, {
|
||||
tableName,
|
||||
comment: '订单-历史(归档)',
|
||||
});
|
||||
|
||||
return OrderStatusHistory;
|
||||
};
|
||||
22
backend/app/model/orderStatusItem.js
Normal file
22
backend/app/model/orderStatusItem.js
Normal file
@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
const { itemFields } = require('../lib/orderFields');
|
||||
const { ORDER_ITEM_TABLE } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 订单明细表(order_status_items)
|
||||
*
|
||||
* 5 张状态表共用的结构化明细表(按 order_id 关联订单,订单 ID 取自 order_index)。
|
||||
* 字段是「发货单明细 order_delivery_items ∪ 原订单明细 order_items」的超集,老数据可无损迁入。
|
||||
* 状态流转只搬订单主表,明细随订单 ID 不变(无需搬迁)。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusItem model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const OrderStatusItem = app.model.define(ORDER_ITEM_TABLE, itemFields(app.Sequelize), {
|
||||
tableName: ORDER_ITEM_TABLE,
|
||||
comment: '订单明细(5 张状态表共用)',
|
||||
});
|
||||
|
||||
return OrderStatusItem;
|
||||
};
|
||||
21
backend/app/model/orderStatusOutsourcing.js
Normal file
21
backend/app/model/orderStatusOutsourcing.js
Normal file
@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
|
||||
const { businessFields } = require('../lib/orderFields');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 委外中订单表(order_status_outsourcing)
|
||||
*
|
||||
* 审核通过后进入;推送外部成功回传后转入 order_status_delivery(配送),失败则转入异常表。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusOutsourcing model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const tableName = ORDER_TABLE_BY_STATUS[ORDER_STATUS.OUTSOURCING];
|
||||
const OrderStatusOutsourcing = app.model.define(tableName, businessFields(app.Sequelize, ORDER_STATUS.OUTSOURCING), {
|
||||
tableName,
|
||||
comment: '订单-委外中',
|
||||
});
|
||||
|
||||
return OrderStatusOutsourcing;
|
||||
};
|
||||
21
backend/app/model/orderStatusPending.js
Normal file
21
backend/app/model/orderStatusPending.js
Normal file
@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
|
||||
const { businessFields } = require('../lib/orderFields');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 待审核订单表(order_status_pending)
|
||||
*
|
||||
* 订单起点状态:审核通过后整行转入 order_status_outsourcing(委外中)。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusPending model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const tableName = ORDER_TABLE_BY_STATUS[ORDER_STATUS.PENDING];
|
||||
const OrderStatusPending = app.model.define(tableName, businessFields(app.Sequelize, ORDER_STATUS.PENDING), {
|
||||
tableName,
|
||||
comment: '订单-待审核',
|
||||
});
|
||||
|
||||
return OrderStatusPending;
|
||||
};
|
||||
23
backend/app/model/orderStatusQueued.js
Normal file
23
backend/app/model/orderStatusQueued.js
Normal file
@ -0,0 +1,23 @@
|
||||
'use strict';
|
||||
|
||||
const { businessFields } = require('../lib/orderFields');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 待推送订单表(order_status_queued)
|
||||
*
|
||||
* 审核通过(已校验明细/店铺并锁定库存)后进入本表,等待定时任务或手动「推送仓库」:
|
||||
* - 推送成功 → 转入 order_status_outsourcing(委外中,等仓库回传发货确认)
|
||||
* - 推送失败 → 转入 order_status_exception(异常,释放锁定库存,可转回待审核)
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusQueued model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const tableName = ORDER_TABLE_BY_STATUS[ORDER_STATUS.QUEUED];
|
||||
const OrderStatusQueued = app.model.define(tableName, businessFields(app.Sequelize, ORDER_STATUS.QUEUED), {
|
||||
tableName,
|
||||
comment: '订单-待推送',
|
||||
});
|
||||
|
||||
return OrderStatusQueued;
|
||||
};
|
||||
22
backend/app/model/orderStatusVoid.js
Normal file
22
backend/app/model/orderStatusVoid.js
Normal file
@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
const { businessFields } = require('../lib/orderFields');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 已作废订单表(order_status_void)
|
||||
*
|
||||
* 侧路状态:审核后不再履约的单据(老流程的「作废」,写 void_at / void_by / void_reason);
|
||||
* 创建时间超过 3 个月时由归档任务转入历史表。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderStatusVoid model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const tableName = ORDER_TABLE_BY_STATUS[ORDER_STATUS.VOID];
|
||||
const OrderStatusVoid = app.model.define(tableName, businessFields(app.Sequelize, ORDER_STATUS.VOID), {
|
||||
tableName,
|
||||
comment: '订单-已作废',
|
||||
});
|
||||
|
||||
return OrderStatusVoid;
|
||||
};
|
||||
@ -45,6 +45,39 @@ module.exports = app => {
|
||||
router.post('/api/principal-users/invite', jwtAuth, principalCheck({ model: 'PrincipalUser' }), controller.principalUser.invite);
|
||||
// 商品快速搜索(聚合:商品编码/货品编码/条码/商品名称),需在 resources('products') 之前注册避免被 :id 误匹配
|
||||
router.get('/api/products/search', jwtAuth, principalCheck({ model: 'Product' }), controller.product.search);
|
||||
// 订单(状态分表):索引表 order_index(订单 ID 全局唯一 + current_table/current_status)
|
||||
// + 6 张同构状态表(待审核/异常/委外中/配送/已作废/已取消)+ 历史表;页面按状态分视图,状态由业务事务推动
|
||||
router.get('/api/order-status/list', jwtAuth, principalCheck(), controller.orderStatus.index);
|
||||
router.get('/api/order-status/filters', jwtAuth, principalCheck(), controller.orderStatus.filters);
|
||||
// 新建订单:写入索引表(取全局唯一 id)与待审核表;带 items 时为发货单口径创建(明细落 order_status_items)
|
||||
router.post('/api/order-status', jwtAuth, principalCheck(), controller.orderStatus.create);
|
||||
// 收件人文本智能识别(与老发货单同一能力)
|
||||
router.post('/api/order-status/parse-receiver', jwtAuth, controller.orderStatus.parseReceiver);
|
||||
// 商品明细:查询 / 整体保存(仅待审核、异常可维护)
|
||||
router.get('/api/order-status/items', jwtAuth, principalCheck(), controller.orderStatus.items);
|
||||
router.post('/api/order-status/items', jwtAuth, principalCheck(), controller.orderStatus.saveItems);
|
||||
// 状态流转专用动作需在 /:id 之前注册,避免被误匹配:
|
||||
// 审核(待审核/异常 → 委外中,含锁定库存)/ 推送外部标记 / 转回待审核 / 归档到历史
|
||||
router.post('/api/order-status/audit', jwtAuth, principalCheck(), controller.orderStatus.audit);
|
||||
router.post('/api/order-status/push', jwtAuth, principalCheck(), controller.orderStatus.push);
|
||||
router.post('/api/order-status/return-to-pending', jwtAuth, principalCheck(), controller.orderStatus.returnToPending);
|
||||
router.post('/api/order-status/archive', jwtAuth, principalCheck(), controller.orderStatus.archive);
|
||||
// 侧路流转:驳回(换号+释放库存)/ 取消 / 作废 / 恢复
|
||||
router.post('/api/order-status/reject', jwtAuth, principalCheck(), controller.orderStatus.reject);
|
||||
router.post('/api/order-status/cancel', jwtAuth, principalCheck(), controller.orderStatus.cancel);
|
||||
router.post('/api/order-status/void', jwtAuth, principalCheck(), controller.orderStatus.voidOrder);
|
||||
router.post('/api/order-status/restore', jwtAuth, principalCheck(), controller.orderStatus.restore);
|
||||
// 推送仓库(WMS deliveryorder.create):单条 / 批量
|
||||
router.post('/api/order-status/push-wms', jwtAuth, principalCheck(), controller.orderStatus.pushWmsBatch);
|
||||
// 批量切换仓库 / 设置所属店铺(同步刷新快照)
|
||||
router.post('/api/order-status/change-warehouse', jwtAuth, principalCheck(), controller.orderStatus.changeWarehouse);
|
||||
router.post('/api/order-status/change-shop', jwtAuth, principalCheck(), controller.orderStatus.changeShop);
|
||||
// 订单详情 / 编辑 / 删除(删除仅限待审核、异常、已取消)/ 推送仓库(单条)
|
||||
router.get('/api/order-status/:id', jwtAuth, principalCheck(), controller.orderStatus.show);
|
||||
router.put('/api/order-status/:id', jwtAuth, principalCheck(), controller.orderStatus.update);
|
||||
router.delete('/api/order-status/:id', jwtAuth, principalCheck(), controller.orderStatus.destroy);
|
||||
router.post('/api/order-status/:id/push-wms', jwtAuth, principalCheck(), controller.orderStatus.pushWms);
|
||||
|
||||
// 以下资源均归属某个主体,需做主体校验与数据隔离,防止跨主体操作
|
||||
router.resources('products', '/api/products', jwtAuth, principalCheck({ model: 'Product' }), controller.product);
|
||||
router.resources('comboProducts', '/api/combo-products', jwtAuth, principalCheck({ model: 'ComboProduct' }), controller.comboProduct);
|
||||
@ -112,6 +145,14 @@ module.exports = app => {
|
||||
router.get('/api/express-companies/select', jwtAuth, controller.expressCompany.select);
|
||||
router.resources('expressCompanies', '/api/express-companies', jwtAuth, controller.expressCompany);
|
||||
|
||||
// 商品属性字典(分类/品牌/单位,按主体隔离):下拉需在 resources 之前注册,避免 /select 被当作 :id
|
||||
router.get('/api/product-categories/select', jwtAuth, principalCheck({ model: 'ProductCategory' }), controller.productCategory.select);
|
||||
router.resources('productCategories', '/api/product-categories', jwtAuth, principalCheck({ model: 'ProductCategory' }), controller.productCategory);
|
||||
router.get('/api/product-brands/select', jwtAuth, principalCheck({ model: 'ProductBrand' }), controller.productBrand.select);
|
||||
router.resources('productBrands', '/api/product-brands', jwtAuth, principalCheck({ model: 'ProductBrand' }), controller.productBrand);
|
||||
router.get('/api/product-units/select', jwtAuth, principalCheck({ model: 'ProductUnit' }), controller.productUnit.select);
|
||||
router.resources('productUnits', '/api/product-units', jwtAuth, principalCheck({ model: 'ProductUnit' }), controller.productUnit);
|
||||
|
||||
// 仓库快递映射(外部传入的自定义快递编码 → OMS 默认快递编码,按仓库维度;供回传解析与「外部仓库」页配置)
|
||||
router.resources('warehouseExpressMappings', '/api/warehouse-express-mappings', jwtAuth, principalCheck({ model: 'WarehouseExpressMapping' }), controller.warehouseExpressMapping);
|
||||
|
||||
|
||||
33
backend/app/schedule/orderArchive.js
Normal file
33
backend/app/schedule/orderArchive.js
Normal file
@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单自动归档:每日凌晨 3:00 执行,把创建时间超过 3 个月的订单从状态表迁入历史表。
|
||||
*
|
||||
* 迁移口径与手工归档一致(app/service/orderStatus.js#archiveExpired):
|
||||
* - 物理迁移:状态表删除 + 历史表插入,写入 archived_at(归档时间)与 transferred_at(转入时间);
|
||||
* - 同步更新索引表 order_index 的 current_table/current_status 为 history;
|
||||
* - 定时任务无主体上下文,按主体分组跨主体处理(每次单表最多 ARCHIVE_BATCH_LIMIT 条)。
|
||||
*/
|
||||
const { ORDER_ARCHIVE_MONTHS } = require('../lib/orderStatus');
|
||||
|
||||
module.exports = {
|
||||
schedule: {
|
||||
// 秒 分 时 日 月 周 —— 每天 03:00:00
|
||||
cron: '0 0 3 * * *',
|
||||
type: 'worker',
|
||||
disable: false,
|
||||
},
|
||||
|
||||
async task(ctx) {
|
||||
const result = await ctx.service.orderStatus.archiveExpired({ months: ORDER_ARCHIVE_MONTHS });
|
||||
if (result.count > 0) {
|
||||
ctx.logger.info(
|
||||
'[order-archive] 已归档超期订单 %d 条(阈值 %s,明细 %j)',
|
||||
result.count,
|
||||
result.threshold,
|
||||
result.by_status
|
||||
);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
35
backend/app/schedule/orderWmsPush.js
Normal file
35
backend/app/schedule/orderWmsPush.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单推送队列:每 30 秒扫描「待推送」的订单并递交 WMS(deliveryorder.create,ORDER 组)
|
||||
*
|
||||
* 说明(与老发货单推送口径一致,数据落在新表 order_status_queued → order_status_outsourcing):
|
||||
* - 审核只入队(待审核 → 待推送),由本定时任务异步推送,避免集中审核时把对方服务打满
|
||||
* - 推送成功:流转「委外中」(写 wms_status/wms_order_no/pushed_at 与推送结果),等仓库回传确认才转「配送」
|
||||
* - 失败处理见 app/service/orderWms.js:对方明确失败或连续 3 次无响应/超时 → 转「异常」并释放锁定库存
|
||||
* - **前置缺失也转「异常」**(无仓库 / 无店铺 / 仓库无启用接口 / 无明细):否则这类单据会永远卡在待推送队列里
|
||||
* - 并发安全:服务层用 pushed_at 做乐观锁抢占(CAS),多 worker 下同一单只会被推送一次
|
||||
*/
|
||||
module.exports = {
|
||||
schedule: {
|
||||
interval: '30s',
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 扫描并推送待推送订单
|
||||
* @param {Egg.Context} ctx egg context(定时任务上下文)
|
||||
* @return {Promise<Object>} 本轮统计
|
||||
*/
|
||||
async task(ctx) {
|
||||
const stat = await ctx.service.orderWms.processPending();
|
||||
if (stat.scanned > 0) {
|
||||
ctx.logger.info(
|
||||
`[order-wms] 本轮扫描 ${stat.scanned} 条:成功 ${stat.pushed},失败 ${stat.failed},转异常(前置缺失) ${stat.aborted},待重试 ${stat.retry},跳过 ${stat.skipped}`
|
||||
);
|
||||
}
|
||||
return stat;
|
||||
},
|
||||
};
|
||||
1665
backend/app/service/orderStatus.js
Normal file
1665
backend/app/service/orderStatus.js
Normal file
File diff suppressed because it is too large
Load Diff
457
backend/app/service/orderWms.js
Normal file
457
backend/app/service/orderWms.js
Normal file
@ -0,0 +1,457 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||||
const { ORDER_STATUS } = require('../lib/orderStatus');
|
||||
const { releaseOrderStock } = require('../utils/orderStock');
|
||||
|
||||
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
|
||||
const PUSH_MAX_ATTEMPTS = 3;
|
||||
/** 同一单据两次尝试的最小间隔(毫秒):避免失败单在定时任务里被连续猛推 */
|
||||
const PUSH_THROTTLE_MS = 20000;
|
||||
/** 定时任务每次最多处理的单据数 */
|
||||
const PUSH_PENDING_LIMIT = 10;
|
||||
/** 手动批量推送每次最多处理的单据数(其余交给定时任务,避免一次请求打爆对方服务) */
|
||||
const PUSH_BATCH_LIMIT = 50;
|
||||
/** 手动批量推送时两条之间的间隔(毫秒),用于限流 */
|
||||
const PUSH_BATCH_GAP_MS = 150;
|
||||
|
||||
/**
|
||||
* 订单推送服务(新表口径:order_index + order_status_queued → order_status_outsourcing)
|
||||
*
|
||||
* 与老发货单推送(app/service/orderDeliveryPush.js)口径一致,只是不再把「已审核待推送」与
|
||||
* 「已推送成功」混在同一状态:
|
||||
* - 审核后订单进入「待推送」(= 老「已审核(2)」),由定时任务 / 手动推送递交 WMS
|
||||
* - 推送成功:流转「委外中」,写 pushed_at(乐观锁)、wms_status=已推送、wms_order_no(外部单据ID)、
|
||||
* wms_synced_at 与 wms_push_result;**等 WMS 回传 deliveryorder.confirm 才流转「配送」**
|
||||
* - 对方明确响应失败 / 连续超时:流转「异常」并释放审核锁定的库存(老口径为退回待审核)
|
||||
*
|
||||
* 并发防重:用 pushed_at 做乐观锁(CAS)抢占单据,多 worker 下同一单只会被一个进程推送一次
|
||||
*/
|
||||
class OrderWmsService extends Service {
|
||||
/**
|
||||
* 查该仓库启用的类奇门接口配置
|
||||
* @param {Object} order 订单(需含 principal_id / warehouse_id)
|
||||
* @return {Promise<Object|null>} warehouse_apis 记录
|
||||
*/
|
||||
async findWarehouseApi(order) {
|
||||
return this.ctx.model.WarehouseApi.findOne({
|
||||
where: {
|
||||
warehouse_id: order.warehouse_id,
|
||||
principal_id: order.principal_id,
|
||||
type: 'qimen',
|
||||
status: 1,
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按商品编码回查该仓库的 WMS 内部商品ID(warehouse_products.wms_item_id)
|
||||
* @param {Object} order 订单
|
||||
* @param {Array} items 订单明细
|
||||
* @return {Promise<Object>} { byProduct, byItemCode }
|
||||
*/
|
||||
async resolveWmsItemIds(order, items) {
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const codes = [ ...new Set((items || []).map(i => i.item_code).filter(Boolean)) ];
|
||||
if (!codes.length) return { byProduct: {}, byItemCode: {} };
|
||||
|
||||
const products = await this.ctx.model.Product.findAll({
|
||||
where: { principal_id: order.principal_id, item_code: { [Op.in]: codes } },
|
||||
attributes: [ 'id', 'item_code' ],
|
||||
});
|
||||
if (!products.length) return { byProduct: {}, byItemCode: {} };
|
||||
|
||||
const links = await this.ctx.model.WarehouseProduct.findAll({
|
||||
where: {
|
||||
principal_id: order.principal_id,
|
||||
warehouse_id: order.warehouse_id,
|
||||
product_id: { [Op.in]: products.map(p => Number(p.id)) },
|
||||
},
|
||||
attributes: [ 'product_id', 'wms_item_id' ],
|
||||
});
|
||||
const byProduct = {};
|
||||
for (const l of links) {
|
||||
if (l.wms_item_id != null) byProduct[Number(l.product_id)] = Number(l.wms_item_id);
|
||||
}
|
||||
const byItemCode = {};
|
||||
for (const p of products) {
|
||||
const wmsItemId = byProduct[Number(p.id)];
|
||||
if (wmsItemId != null) byItemCode[p.item_code] = wmsItemId;
|
||||
}
|
||||
return { byProduct, byItemCode };
|
||||
}
|
||||
|
||||
/**
|
||||
* 冲正外部单据(best-effort,失败只记录不抛出)
|
||||
* @param {Object} client QimenWmsClient
|
||||
* @param {Object} order 订单(适配后的视图对象)
|
||||
* @return {Promise<Object>} 冲正返回或异常信息
|
||||
*/
|
||||
async cancelRemote(client, order) {
|
||||
try {
|
||||
return await client.cancelDeliveryOrder(order);
|
||||
} catch (err) {
|
||||
return { code: 'EXCEPTION', message: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放订单已锁定的库存(best-effort;失败只记日志,`stock_locked` 保持 1 便于后续再释放)
|
||||
* @param {Object} order 状态表行实例
|
||||
* @param {String} remark 备注(写库存流水)
|
||||
* @param {Object} [transaction] 事务
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async releaseStock(order, remark, transaction) {
|
||||
try {
|
||||
const result = await releaseOrderStock(this.ctx, order, { remark, transaction });
|
||||
if (!result.skipped) {
|
||||
this.ctx.logger.info(`[order-wms] ${order.order_no} 已释放锁定库存(${result.affected} 行):${remark}`);
|
||||
}
|
||||
} catch (err) {
|
||||
this.ctx.logger.error(`[order-wms] ${order.order_no} 释放锁定库存失败:${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取上次推送记录(wms_push_result JSON)
|
||||
* @param {Object} order 状态表行实例
|
||||
* @return {Object} 上次记录(无则空对象)
|
||||
*/
|
||||
_prevResult(order) {
|
||||
const raw = order.wms_push_result;
|
||||
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态表行 → 奇门客户端可用的发货单视图
|
||||
* 新表字段沿用老表列名,只需把 order_no/receiver 映射成 delivery_order_code/name
|
||||
* @param {Object} row 状态表行实例
|
||||
* @param {Object} warehouse 仓库(含 code)
|
||||
* @return {Object} 视图对象
|
||||
*/
|
||||
adaptOrder(row, warehouse) {
|
||||
const plain = row.get ? row.get({ plain: true }) : { ...row };
|
||||
return {
|
||||
...plain,
|
||||
delivery_order_code: plain.order_no,
|
||||
name: plain.receiver,
|
||||
warehouse_code: plain.warehouse_code || (warehouse && warehouse.code) || null,
|
||||
warehouse: warehouse ? (warehouse.get ? warehouse.get({ plain: true }) : warehouse) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载待推送订单(含仓库),仅返回「待推送」的单据
|
||||
* @param {Number|String} id 订单ID
|
||||
* @return {Promise<Object|null>} 状态表行实例
|
||||
*/
|
||||
async loadOrder(id) {
|
||||
return this.ctx.model.OrderStatusQueued.findByPk(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送单条订单(一次尝试)
|
||||
*
|
||||
* 返回 ok=false 时:
|
||||
* - retry=true :无响应/超时,单据保留「待推送」,等下次定时任务重试
|
||||
* - retry=false:对方明确失败或已达重试上限,单据已流转「异常」并释放锁定库存
|
||||
* @param {Number|String} id 订单ID
|
||||
* @param {Object} [options] { source: 'schedule' | 'manual' | 'batch' }
|
||||
* @return {Promise<{ok: Boolean, skipped?: Boolean, retry?: Boolean, message: String, response?: Object, attempts?: Number}>} 推送结果
|
||||
*/
|
||||
async pushOne(id, options = {}) {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const source = options.source || 'manual';
|
||||
|
||||
const order = await this.loadOrder(id);
|
||||
if (!order) return { ok: false, skipped: true, message: '订单不存在或不在「待推送」' };
|
||||
// 以下三项属「永久性前置缺失」:标 fatal,由调用方(定时任务)转「异常」并写明原因,避免单据卡在待推送
|
||||
if (!(Number(order.warehouse_id) > 0)) {
|
||||
return { ok: false, skipped: true, fatal: true, message: '订单未设置仓库,无法推送:请补全仓库后重新审核' };
|
||||
}
|
||||
if (!(Number(order.shop_id) > 0)) {
|
||||
return { ok: false, skipped: true, fatal: true, message: '订单未设置店铺,无法推送:请先设置店铺(批量操作 → 设置所属店铺)' };
|
||||
}
|
||||
|
||||
const api = await this.findWarehouseApi(order);
|
||||
if (!api) {
|
||||
return {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
fatal: true,
|
||||
message: `仓库#${order.warehouse_id} 未配置启用中的类奇门接口,无法推送:请到「外部仓库」补全接口配置`,
|
||||
};
|
||||
}
|
||||
const warehouse = await ctx.model.Warehouse.findByPk(order.warehouse_id, { attributes: [ 'id', 'code', 'name' ] });
|
||||
|
||||
// 乐观锁抢占:多 worker / 并发请求下同一单只推一次(同时把本次尝试时间写入 pushed_at)
|
||||
const now = new Date();
|
||||
const throttleBefore = new Date(now.getTime() - PUSH_THROTTLE_MS);
|
||||
const [ claimed ] = await ctx.model.OrderStatusQueued.update(
|
||||
{ pushed_at: now },
|
||||
{
|
||||
where: {
|
||||
id: order.id,
|
||||
principal_id: order.principal_id,
|
||||
status: ORDER_STATUS.QUEUED,
|
||||
[Op.or]: [
|
||||
{ pushed_at: null },
|
||||
{ pushed_at: { [Op.lt]: throttleBefore } },
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
if (!claimed) {
|
||||
return { ok: false, skipped: true, message: '该订单正在推送或处于重试间隔内,已跳过' };
|
||||
}
|
||||
order.pushed_at = now;
|
||||
|
||||
const prev = this._prevResult(order);
|
||||
const attempts = Number(prev.attempts || 0) + 1;
|
||||
const base = {
|
||||
orderId: Number(order.id),
|
||||
deliveryOrderCode: order.order_no,
|
||||
warehouseApiId: api.id,
|
||||
apiType: api.type,
|
||||
attempts,
|
||||
maxAttempts: PUSH_MAX_ATTEMPTS,
|
||||
source,
|
||||
attemptedAt: now.toISOString(),
|
||||
};
|
||||
|
||||
// 店铺名称兜底:shopNick 取所选店铺名称(WMS 侧靠它匹配快递策略)
|
||||
if (!order.shop_nick && order.shop_id) {
|
||||
const shop = await ctx.model.Shop.findByPk(order.shop_id, { attributes: [ 'id', 'name' ] });
|
||||
if (shop && shop.name) {
|
||||
order.shop_nick = shop.name;
|
||||
await order.update({ shop_nick: shop.name });
|
||||
ctx.logger.info(`[order-wms] ${order.order_no} 补齐店铺名称快照:${shop.name}`);
|
||||
}
|
||||
}
|
||||
if (!order.shop_nick) {
|
||||
ctx.logger.warn(`[order-wms] ${order.order_no} 未取到店铺名称(shop_nick 为空),推送报文中不会有 shopNick`);
|
||||
}
|
||||
|
||||
const itemRows = await ctx.model.OrderStatusItem.findAll({
|
||||
where: { order_id: order.id, principal_id: order.principal_id },
|
||||
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
if (!itemRows.length) {
|
||||
await order.update({
|
||||
wms_push_result: { ...base, success: false, failureKind: 'empty_items', message: '订单无明细,无法推送' },
|
||||
});
|
||||
return { ok: false, retry: false, fatal: true, message: '订单无明细,无法推送', attempts };
|
||||
}
|
||||
|
||||
const client = new QimenWmsClient(api, this.app);
|
||||
const items = itemRows.map(item => item.get({ plain: true }));
|
||||
const wmsItemIds = await this.resolveWmsItemIds(order, items);
|
||||
const view = this.adaptOrder(order, warehouse);
|
||||
|
||||
let resp;
|
||||
try {
|
||||
resp = await client.createDeliveryOrder(view, items, {
|
||||
warehouse: view.warehouse,
|
||||
wmsItemIdByProduct: wmsItemIds.byProduct,
|
||||
wmsItemIdByItemCode: wmsItemIds.byItemCode,
|
||||
});
|
||||
} catch (err) {
|
||||
// 超时 / 网络异常 / 非法响应:可重试
|
||||
const canRetry = attempts < PUSH_MAX_ATTEMPTS;
|
||||
if (canRetry) {
|
||||
await order.update({
|
||||
wms_push_result: { ...base, success: false, failureKind: 'timeout', retryable: true, error: err.message },
|
||||
});
|
||||
ctx.logger.warn(`[order-wms] ${order.order_no} 第 ${attempts}/${PUSH_MAX_ATTEMPTS} 次推送异常(将重试):${err.message}`);
|
||||
return { ok: false, retry: true, message: err.message, attempts };
|
||||
}
|
||||
const cancelResult = await this.cancelRemote(client, view);
|
||||
await order.update({
|
||||
wms_push_result: {
|
||||
...base,
|
||||
success: false,
|
||||
failureKind: 'timeout',
|
||||
retryable: false,
|
||||
error: err.message,
|
||||
cancelResult,
|
||||
},
|
||||
});
|
||||
await this.toException(order, `连续 ${attempts} 次推送无响应/超时:${err.message}`);
|
||||
ctx.logger.error(`[order-wms] ${order.order_no} 连续 ${attempts} 次推送异常,已转异常:${err.message}`);
|
||||
return { ok: false, retry: false, message: `连续 ${attempts} 次无响应/超时,已转异常:${err.message}`, attempts };
|
||||
}
|
||||
|
||||
if (client.isSuccess(resp)) {
|
||||
const externalNo = resp && (resp.deliveryOrderId || resp.outBizCode || null);
|
||||
// 推送成功才进「委外中」:外部单据号 + 推送痕迹与状态流转同事务写入(字段随流转一并搬表)
|
||||
await ctx.service.orderStatus.markPushed({
|
||||
ids: [ Number(order.id) ],
|
||||
principalId: Number(order.principal_id),
|
||||
overrides: {
|
||||
pushed_at: now,
|
||||
operate_time: now,
|
||||
wms_status: 'pushed',
|
||||
wms_order_no: externalNo == null ? order.wms_order_no : String(externalNo),
|
||||
wms_synced_at: now,
|
||||
wms_push_result: { ...base, success: true, response: resp },
|
||||
},
|
||||
});
|
||||
ctx.logger.info(`[order-wms] ${order.order_no} 推送成功(第 ${attempts} 次),已转「委外中」`);
|
||||
return { ok: true, message: '已推送仓库', response: resp, attempts };
|
||||
}
|
||||
|
||||
// 对方明确响应失败:不重试,转「异常」并释放审核锁定的库存
|
||||
const cancelResult = await this.cancelRemote(client, view);
|
||||
const message = resp && (resp.message || resp.code);
|
||||
await order.update({
|
||||
wms_push_result: {
|
||||
...base,
|
||||
success: false,
|
||||
failureKind: 'business',
|
||||
retryable: false,
|
||||
code: resp && resp.code,
|
||||
message,
|
||||
response: resp,
|
||||
cancelResult,
|
||||
},
|
||||
});
|
||||
await this.toException(order, `推送仓库失败:${message}`);
|
||||
ctx.logger.warn(`[order-wms] ${order.order_no} 推送失败(对方明确拒绝),已转异常:${message}`);
|
||||
return { ok: false, retry: false, message: `WMS 返回失败:${message}`, response: resp, attempts };
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送失败转「异常」(释放锁定库存 + 状态流转,同一事务)
|
||||
* @param {Object} order 状态表行实例(委外中)
|
||||
* @param {String} reason 异常原因(写入备注)
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async toException(order, reason) {
|
||||
await this.ctx.service.orderStatus.markPushFailed({
|
||||
ids: [ Number(order.id) ],
|
||||
principalId: Number(order.principal_id),
|
||||
reason,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描「待推送」的订单并推送(定时任务入口)
|
||||
*
|
||||
* 扫描范围:全部待推送订单(**不过滤仓库**,否则无仓库/无接口配置的单据会永远卡在队列里);
|
||||
* ① 可推送 → 递交 WMS:成功转「委外中」、失败转「异常」
|
||||
* ② 永久性前置缺失(无仓库 / 无店铺 / 仓库无启用接口 / 无明细)→ 转「异常」并写明原因
|
||||
* ③ 瞬时跳过(另一 worker 正在推送 / 重试间隔内)→ 保留待推送,下轮再试
|
||||
* @param {Object} [options] { limit }
|
||||
* @return {Promise<Object>} { scanned, pushed, failed, retry, skipped, aborted }
|
||||
*/
|
||||
async processPending(options = {}) {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const limit = Number(options.limit) > 0 ? Number(options.limit) : PUSH_PENDING_LIMIT;
|
||||
const throttleBefore = new Date(Date.now() - PUSH_THROTTLE_MS);
|
||||
|
||||
const orders = await ctx.model.OrderStatusQueued.findAll({
|
||||
where: {
|
||||
status: ORDER_STATUS.QUEUED,
|
||||
[Op.or]: [
|
||||
{ pushed_at: null },
|
||||
{ pushed_at: { [Op.lt]: throttleBefore } },
|
||||
],
|
||||
},
|
||||
attributes: [ 'id', 'principal_id' ],
|
||||
order: [[ 'pushed_at', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
limit,
|
||||
});
|
||||
|
||||
const stat = { scanned: orders.length, pushed: 0, failed: 0, retry: 0, skipped: 0, aborted: 0 };
|
||||
for (const row of orders) {
|
||||
const res = await this.pushOne(row.id, { source: 'schedule' });
|
||||
if (res.ok) {
|
||||
stat.pushed++;
|
||||
} else if (res.fatal) {
|
||||
// 永久性前置缺失:转异常(释放锁定库存 + 写明原因),队列不再残留
|
||||
stat.aborted++;
|
||||
try {
|
||||
await ctx.service.orderStatus.markPushFailed({
|
||||
ids: [ Number(row.id) ],
|
||||
principalId: Number(row.principal_id),
|
||||
reason: res.message,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.error(`[order-wms] id=${row.id} 转异常失败:${err.message}`);
|
||||
}
|
||||
} else if (res.skipped) {
|
||||
stat.skipped++;
|
||||
} else if (res.retry) {
|
||||
stat.retry++;
|
||||
} else {
|
||||
stat.failed++;
|
||||
}
|
||||
}
|
||||
return stat;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量推送指定ID列表(限流顺序执行)
|
||||
* @param {Array} ids 订单ID列表
|
||||
* @param {Object} [options] { limit, gap }
|
||||
* @return {Promise<Object>} { requested, processed, pendingRest, pushed, failed, retry, skipped, details }
|
||||
*/
|
||||
async pushMany(ids, options = {}) {
|
||||
const limit = Number(options.limit) > 0 ? Number(options.limit) : PUSH_BATCH_LIMIT;
|
||||
const gap = options.gap === undefined ? PUSH_BATCH_GAP_MS : Number(options.gap);
|
||||
const targets = ids.slice(0, limit);
|
||||
const result = {
|
||||
requested: ids.length,
|
||||
processed: targets.length,
|
||||
pendingRest: Math.max(ids.length - targets.length, 0),
|
||||
pushed: 0,
|
||||
failed: 0,
|
||||
retry: 0,
|
||||
skipped: 0,
|
||||
aborted: 0,
|
||||
details: [],
|
||||
};
|
||||
|
||||
for (let i = 0; i < targets.length; i++) {
|
||||
const res = await this.pushOne(targets[i], { source: 'batch' });
|
||||
if (res.ok) result.pushed++;
|
||||
else if (res.fatal) result.aborted++;
|
||||
else if (res.skipped) result.skipped++;
|
||||
else if (res.retry) result.retry++;
|
||||
else result.failed++;
|
||||
result.details.push({ id: targets[i], ok: res.ok, fatal: Boolean(res.fatal), message: res.message });
|
||||
if (gap > 0 && i < targets.length - 1) await new Promise(resolve => setTimeout(resolve, gap));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消外部单据(已推送成功、处于委外中的订单取消前调用)
|
||||
* @param {Object} order 状态表行实例
|
||||
* @return {Promise<Object>} { ok: Boolean, message: String, response?: Object }
|
||||
*/
|
||||
async cancelRemoteOrder(order) {
|
||||
const api = await this.findWarehouseApi(order);
|
||||
if (!api) return { ok: false, message: '该仓库未配置启用的类奇门接口,无法取消已推送的外部单据' };
|
||||
const warehouse = await this.ctx.model.Warehouse.findByPk(order.warehouse_id, { attributes: [ 'id', 'code' ] });
|
||||
const client = new QimenWmsClient(api, this.app);
|
||||
const view = this.adaptOrder(order, warehouse);
|
||||
let resp;
|
||||
try {
|
||||
resp = await client.cancelDeliveryOrder(view);
|
||||
} catch (err) {
|
||||
return { ok: false, message: `取消仓库单据失败:${err.message}` };
|
||||
}
|
||||
if (!client.isSuccess(resp)) {
|
||||
return { ok: false, message: `取消仓库单据失败:${resp && (resp.message || resp.code)}`, response: resp };
|
||||
}
|
||||
return { ok: true, message: '已取消外部单据', response: resp };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderWmsService;
|
||||
182
backend/app/utils/orderStock.js
Normal file
182
backend/app/utils/orderStock.js
Normal file
@ -0,0 +1,182 @@
|
||||
'use strict';
|
||||
|
||||
const { applyStockChange } = require('./stockRecord');
|
||||
const { orderModelName } = require('../lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 订单(新表)库存动作:审核锁定 / 释放 / 发货确认扣减。
|
||||
*
|
||||
* 与老发货单模块(app/utils/deliveryStock.js)口径完全一致,只是数据源换成新表:
|
||||
* - **审核**:按明细锁定库存(order_lock),可用不足则审核失败
|
||||
* - **推送失败 / 驳回 / 取消 / 作废**:释放锁定(order_unlock)
|
||||
* - **WMS 发货确认**:扣减库存(总数量与锁定同减,order_deduct)
|
||||
*
|
||||
* 幂等依据是状态表上的 `stock_locked` 标记:
|
||||
* - lock:已锁定(1) 直接跳过,不重复占用
|
||||
* - release/deduct:未锁定(0) 直接跳过(老数据搬迁进来的单据保持 0,不会被凭空释放/扣减)
|
||||
*
|
||||
* 明细商品解析:order_status_items 未存 product_id 时按 `item_code` 关联 products(主体隔离),
|
||||
* 匹配不到的明细行会被跳过并返回 skippedLines 供调用方提示。
|
||||
*/
|
||||
|
||||
/** 动作 → 出入库记录业务动作(常量见 app/utils/stockRecord.js#BIZ_TYPES) */
|
||||
const ACTION_BIZ_TYPES = {
|
||||
lock: 'order_lock',
|
||||
release: 'order_unlock',
|
||||
deduct: 'order_deduct',
|
||||
};
|
||||
|
||||
/** 默认备注 */
|
||||
const DEFAULT_REMARKS = {
|
||||
lock: '订单审核锁定库存',
|
||||
release: '订单释放锁定库存',
|
||||
deduct: '订单发货确认扣减库存',
|
||||
};
|
||||
|
||||
/**
|
||||
* 取订单明细并解析系统商品
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} order 订单(状态表行,需含 id / principal_id)
|
||||
* @param {Object} [transaction] Sequelize 事务
|
||||
* @return {Promise<Array<Object>>} [{ product_id, item_code, item_name, plan_qty, inventory_type }]
|
||||
*/
|
||||
async function loadOrderLines(ctx, order, transaction) {
|
||||
const Op = ctx.app.Sequelize.Op;
|
||||
const items = await ctx.model.OrderStatusItem.findAll({
|
||||
where: { order_id: order.id, principal_id: order.principal_id },
|
||||
attributes: [ 'id', 'order_line_no', 'item_code', 'item_name', 'plan_qty', 'inventory_type', 'product_id' ],
|
||||
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
transaction,
|
||||
});
|
||||
if (!items.length) return [];
|
||||
|
||||
const codes = [ ...new Set(items.map(i => i.item_code).filter(v => v != null && String(v).trim() !== '')) ];
|
||||
const products = codes.length
|
||||
? await ctx.model.Product.findAll({
|
||||
where: { principal_id: order.principal_id, item_code: { [Op.in]: codes } },
|
||||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||||
transaction,
|
||||
})
|
||||
: [];
|
||||
const byCode = new Map(products.map(p => [ p.item_code, p ]));
|
||||
|
||||
return items.map(it => {
|
||||
const row = it.get ? it.get({ plain: true }) : it;
|
||||
const product = row.item_code ? byCode.get(row.item_code) : null;
|
||||
return {
|
||||
product_id: product ? Number(product.id) : (row.product_id != null ? Number(row.product_id) : null),
|
||||
item_code: row.item_code,
|
||||
item_name: row.item_name || (product && product.item_name) || null,
|
||||
plan_qty: Number(row.plan_qty) || 0,
|
||||
inventory_type: row.inventory_type,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行订单库存动作(账实同事务)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} order 订单(状态表行,需含 id / principal_id / warehouse_id / order_no / stock_locked)
|
||||
* @param {String} action lock(审核锁定)/ release(释放锁定)/ deduct(发货确认扣减)
|
||||
* @param {Object} [options] 选项
|
||||
* @param {Number} [options.createdBy] 操作人ID
|
||||
* @param {String} [options.remark] 备注(不传用默认备注)
|
||||
* @param {Object} [options.transaction] 外部事务;不传时内部自建并提交/回滚
|
||||
* @return {Promise<{action: String, affected: Number, skipped: Boolean, skippedLines: Array<String>}>}
|
||||
* affected = 实际发生库存变动的明细行数;skippedLines = 未匹配到系统商品的 item_code
|
||||
*/
|
||||
async function execute(ctx, order, action, options = {}) {
|
||||
const bizType = ACTION_BIZ_TYPES[action];
|
||||
if (!bizType) throw new Error(`未知的订单库存动作:${action}`);
|
||||
|
||||
const locked = Number(order.stock_locked) === 1;
|
||||
// 幂等/兼容:已锁定不再加锁;未锁定不释放、不扣减
|
||||
if (action === 'lock' && locked) return { action, affected: 0, skipped: true, skippedLines: [] };
|
||||
if (action !== 'lock' && !locked) return { action, affected: 0, skipped: true, skippedLines: [] };
|
||||
|
||||
const ownTransaction = !options.transaction;
|
||||
const transaction = options.transaction || await ctx.model.transaction();
|
||||
try {
|
||||
const lines = await loadOrderLines(ctx, order, transaction);
|
||||
const hit = lines.filter(l => l.product_id && l.plan_qty > 0);
|
||||
// 仅把「未匹配到系统商品」的明细计入 skippedLines(数量为空/0 的明细直接忽略,属数据异常)
|
||||
const skippedLines = lines.filter(l => !l.product_id).map(l => l.item_code || '#?');
|
||||
if (!hit.length) {
|
||||
throw new Error('订单明细未匹配到系统商品(按 item_code 关联 products),无法进行库存操作');
|
||||
}
|
||||
|
||||
for (const line of hit) {
|
||||
await applyStockChange(ctx, {
|
||||
bizType,
|
||||
principalId: order.principal_id,
|
||||
warehouseId: order.warehouse_id,
|
||||
productId: line.product_id,
|
||||
itemCode: line.item_code,
|
||||
itemName: line.item_name,
|
||||
itemType: line.inventory_type === 'CC' ? 'CC' : 'ZC',
|
||||
quantity: line.plan_qty,
|
||||
billId: order.id,
|
||||
billNo: order.order_no,
|
||||
createdBy: options.createdBy,
|
||||
remark: options.remark || DEFAULT_REMARKS[action],
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
// 锁定标记与库存动作同事务:lock → 1,release/deduct → 0
|
||||
const Model = ctx.model[orderModelName(order.status)];
|
||||
await Model.update(
|
||||
{ stock_locked: action === 'lock' ? 1 : 0 },
|
||||
{ where: { id: order.id, principal_id: order.principal_id }, transaction }
|
||||
);
|
||||
if (ownTransaction) await transaction.commit();
|
||||
|
||||
if (skippedLines.length) {
|
||||
ctx.logger.warn(`[order-stock] 订单 ${order.order_no} ${action} 跳过未匹配系统商品的明细:${skippedLines.join(', ')}`);
|
||||
}
|
||||
return { action, affected: hit.length, skipped: false, skippedLines };
|
||||
} catch (err) {
|
||||
if (ownTransaction) await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 审核锁定库存(可用不足抛 INSUFFICIENT_STOCK,由调用方转 400)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} order 订单(状态表行)
|
||||
* @param {Object} [options] { createdBy, remark, transaction }
|
||||
* @return {Promise<Object>} execute 的返回
|
||||
*/
|
||||
function lockOrderStock(ctx, order, options = {}) {
|
||||
return execute(ctx, order, 'lock', options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放锁定库存(推送失败 / 驳回 / 取消 / 作废)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} order 订单(状态表行)
|
||||
* @param {Object} [options] { createdBy, remark, transaction }
|
||||
* @return {Promise<Object>} execute 的返回
|
||||
*/
|
||||
function releaseOrderStock(ctx, order, options = {}) {
|
||||
return execute(ctx, order, 'release', options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发货确认扣减库存(WMS 回传 deliveryorder.confirm)
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Object} order 订单(状态表行)
|
||||
* @param {Object} [options] { createdBy, remark, transaction }
|
||||
* @return {Promise<Object>} execute 的返回
|
||||
*/
|
||||
function deductOrderStock(ctx, order, options = {}) {
|
||||
return execute(ctx, order, 'deduct', options);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
loadOrderLines,
|
||||
lockOrderStock,
|
||||
releaseOrderStock,
|
||||
deductOrderStock,
|
||||
};
|
||||
@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 建立订单(状态分表)表结构。
|
||||
*
|
||||
* 表清单:
|
||||
* 1. order_index 订单索引表:订单 ID 全局唯一,current_table/current_status 记录当前归属表与状态
|
||||
* 2. order_status_pending 待审核
|
||||
* 3. order_status_exception 异常
|
||||
* 4. order_status_outsourcing 委外中
|
||||
* 5. order_status_delivery 配送
|
||||
* 6. order_status_history 历史(另含 archived_at 归档时间、transferred_at 转入时间)
|
||||
*
|
||||
* 说明:
|
||||
* - 4 张状态表结构完全一致,订单在各表间流转(来源表删除 + 目标表写入 + 更新索引表);
|
||||
* - DDL 与「旧命名就地改名」逻辑统一放在 database/orderStatusTables.js(唯一来源),保证可重复执行;
|
||||
* - 兼容处理:若库里存在旧命名的状态表(split_order_pending 等,模块早期按「拆单」语义命名),
|
||||
* 本迁移会**就地改名**为当前命名(保留数据与索引),不会重建表、不丢数据;
|
||||
* 更早的「单活动表」设计残留表(split_order_active 等,表内无数据)会被清理。
|
||||
*
|
||||
* 执行:npm run migration:up
|
||||
*/
|
||||
const { migrate, dropTables } = require('../orderStatusTables');
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await migrate(queryInterface, Sequelize);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await dropTables(queryInterface);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 「订单」菜单指向订单页(views/Order/Status.vue),并移除独立挂载的历史菜单「订单拆分」。
|
||||
*
|
||||
* 口径(2026-09-15 按用户要求):订单按状态分表(待审核/异常/委外中/配送/历史)展示,
|
||||
* 该页面就是「订单」菜单的内容,不存在「订单拆分」这一层语义。
|
||||
*
|
||||
* 幂等:见 database/orderMenu.js(UPDATE 按 名称+路径 定位、DELETE 按 名称+路径 定位)。
|
||||
* 执行:npm run migration:up
|
||||
*/
|
||||
const { applyOrderMenu, revertOrderMenu } = require('../orderMenu');
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await applyOrderMenu(queryInterface);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await revertOrderMenu(queryInterface);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 清理已被取代的迁移记录(sequelize_meta)。
|
||||
*
|
||||
* 背景:本模块最初按「拆单(split order)」语义命名并留下 4 个迁移文件
|
||||
* (建表 / 菜单种子 / 结构对账 / 菜单调整),尚未发布到生产即确认语义有误,
|
||||
* 已整体改名为订单语义并合并为:
|
||||
* - 20260916030000-create-order-tables.js(建表 + 旧命名表就地改名)
|
||||
* - 20260916030100-order-menu-to-order-page.js(订单菜单口径)
|
||||
* 由于旧文件已删除,其在本地的执行记录(sequelize_meta)会变成"找不到文件"的孤儿记录,
|
||||
* 本迁移把这些记录清掉,保证 `db:migrate:status` 与 `db:migrate:undo` 干净可用。
|
||||
*
|
||||
* down:不可逆(仅是执行记录清理,不影响任何业务表结构)。
|
||||
*/
|
||||
const SUPERSEDED = [
|
||||
'20260915010000-create-split-order-tables.js',
|
||||
'20260915010100-seed-split-order-menu.js',
|
||||
'20260916010000-reconcile-split-order-tables.js',
|
||||
'20260916020000-order-menu-use-split-order-page.js',
|
||||
];
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT name FROM sequelize_meta WHERE name IN (?)',
|
||||
{ replacements: [ SUPERSEDED ] }
|
||||
);
|
||||
if (!rows.length) return;
|
||||
await queryInterface.sequelize.query(
|
||||
'DELETE FROM sequelize_meta WHERE name IN (?)',
|
||||
{ replacements: [ SUPERSEDED ] }
|
||||
);
|
||||
console.log(`[order] 已清理 ${rows.length} 条被取代的迁移记录:${rows.map(row => row.name).join(', ')}`);
|
||||
},
|
||||
|
||||
async down() {
|
||||
// 不可逆:被取代的迁移文件已删除,不需要也无法恢复其执行记录
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 把订单状态表扩展为「老表的超集」(字段不再丢失)。
|
||||
*
|
||||
* 背景:订单状态表原先只按业务流程需要建了 12 个核心字段,相对老表大量字段缺失:
|
||||
* - 原订单表 orders(19 列):缺 order_type、wms_ 系列、submit_ 系列、total_amount / pay_amount 等 10 列;
|
||||
* - 发货单 order_deliveries(68 列):缺仓库、物流、收件人 12 项、金额 6 项、推送与审核作废痕迹等 59 列;
|
||||
* - 明细:发货单明细 19 列 / 原订单明细 22 列,各自大量字段无处落地。
|
||||
*
|
||||
* 本迁移按「超集」口径补齐结构(字段定义见 app/lib/orderFields.js,唯一来源):
|
||||
* 1. 5 张状态表补齐老表的全部字段(同名同类型,保证老数据可无损迁入);
|
||||
* 2. 新增明细表 order_status_items(= 发货单明细 ∪ 原订单明细 的超集,5 张状态表共用)。
|
||||
*
|
||||
* 幂等:只补缺失的表与列(已存在的列不动、不覆盖数据);全新库上为建表动作。
|
||||
* down:删除为容纳老表而扩展的列,并移除明细表(保留状态流程核心字段与数据)。
|
||||
*
|
||||
* 执行:npm run migration:up
|
||||
*/
|
||||
const { migrate, dropLegacyColumns } = require('../orderStatusTables');
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await migrate(queryInterface, Sequelize);
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await dropLegacyColumns(queryInterface, Sequelize);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单表字段同步(把 app/lib/orderFields.js 里的字段定义补齐到已存在的表上)。
|
||||
*
|
||||
* 用途:字段定义是唯一来源(app/lib/orderFields.js),建表由 20260916030000 / 20260916030300 完成;
|
||||
* 后续任何字段增补,只需在该文件里加字段定义 + 新建一条本文件同款迁移(调用 syncColumns)即可,
|
||||
* 无需手写 ALTER(列已存在则跳过,幂等)。
|
||||
*
|
||||
* 本次补齐:orders / order_deliveries 的 status 是数值枚举、而流程状态是新枚举,
|
||||
* 为不丢老值新增 `legacy_status`(迁移来源的老状态原值)。
|
||||
*
|
||||
* down:不可逆(仅补齐列,删除列会丢数据)。
|
||||
*
|
||||
* 执行:npm run migration:up
|
||||
*/
|
||||
const { syncColumns } = require('../orderStatusTables');
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await syncColumns(queryInterface, Sequelize);
|
||||
},
|
||||
|
||||
async down() {
|
||||
// 不可逆:字段同步只做补齐,不回退(回退会丢数据)
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 补回「发货单」菜单(挂在「订单管理」下)。
|
||||
*
|
||||
* 背景:订单管理下原本只有「订单」一个列表菜单,2026-09-15 把「订单」菜单改指向订单(状态分表)页面后,
|
||||
* 发货单列表页(views/Order/Index.vue,读写 /api/order-deliveries)失去了菜单入口 → 发货单在界面上不可见。
|
||||
* 本迁移为它补一个独立菜单项,路径 /order-delivery,与「创建发货单」(/order-create) 成对。
|
||||
*
|
||||
* 幂等:按 name + path 定位,已存在则跳过。
|
||||
*/
|
||||
const MENU = {
|
||||
name: '发货单',
|
||||
path: '/order-delivery',
|
||||
type: 2,
|
||||
icon: 'Van',
|
||||
permission: 'orderDelivery:list',
|
||||
component: 'views/Order/Index.vue',
|
||||
sort: 75,
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
const [ orderMgmt ] = await sequelize.query(
|
||||
"SELECT id FROM menus WHERE name = '订单管理' AND parent_id = 0 LIMIT 1",
|
||||
{ type: sequelize.QueryTypes.SELECT },
|
||||
);
|
||||
if (!orderMgmt) return; // 订单管理节点不存在则跳过
|
||||
|
||||
const [ exist ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE name = ? AND path = ? LIMIT 1',
|
||||
{ replacements: [ MENU.name, MENU.path ], type: sequelize.QueryTypes.SELECT },
|
||||
);
|
||||
if (exist) return;
|
||||
|
||||
await sequelize.query(
|
||||
`INSERT INTO menus
|
||||
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`,
|
||||
{
|
||||
replacements: [
|
||||
Number(orderMgmt.id), MENU.name, MENU.type, MENU.path,
|
||||
MENU.icon, MENU.permission, MENU.component, MENU.sort,
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
'DELETE FROM menus WHERE name = ? AND path = ?',
|
||||
{ replacements: [ MENU.name, MENU.path ] },
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 新增订单侧路状态表与迁移来源列。
|
||||
*
|
||||
* 背景:老流程(发货单 / 原订单)还有「作废」「取消」两个状态,新状态机原先只有
|
||||
* 待审核 / 异常 / 委外中 / 配送 / 历史,无法承载老数据与老流程,故补充:
|
||||
* - 新增 2 张侧路状态表:order_status_void(已作废)、order_status_canceled(已取消);
|
||||
* - 各状态表与明细表新增 `legacy_source`(迁移来源表名),配合 `legacy_order_id` / `legacy_order_item_id`
|
||||
* 保证老数据搬迁可幂等重跑、可回溯。
|
||||
*
|
||||
* 幂等:只补缺失的表与列(表结构定义见 app/lib/orderStatus.js 与 app/lib/orderFields.js)。
|
||||
* down:不可逆(仅补结构,回退会丢数据)。
|
||||
*
|
||||
* 执行:npm run migration:up
|
||||
*/
|
||||
const { migrate } = require('../orderStatusTables');
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await migrate(queryInterface, Sequelize);
|
||||
},
|
||||
|
||||
async down() {
|
||||
// 不可逆:结构补齐不回退
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,363 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 老数据搬迁:原订单表 orders(含 order_items)与发货单 order_deliveries(含 order_delivery_items)
|
||||
* → 订单状态表(order_index + order_status_* + order_status_items)。
|
||||
*
|
||||
* 老表数据不动(保留可回溯),搬迁结果按 `legacy_source` + `legacy_order_id`(明细用 legacy_order_item_id)标记,
|
||||
* 可幂等重复执行(已迁过的行跳过)。
|
||||
*
|
||||
* 状态映射(老数值 → 新流程状态,原值写入 legacy_status):
|
||||
* - orders.status:1待处理 → pending、2处理中 → outsourcing、3已完成 → delivery、4已取消 → canceled
|
||||
* - order_deliveries.status:1待处理 → pending、2已审核 → outsourcing、3已推送 → outsourcing、
|
||||
* 4已完成 → delivery、5已作废 → void、9已取消 → canceled
|
||||
* (新流程里「审核后即入委外/推送队列」,故老 2/3 都落在委外中)
|
||||
*
|
||||
* 字段映射(详见 app/lib/orderFields.js 头部注释):
|
||||
* - orders.order_no、order_deliveries.delivery_order_code → order_no
|
||||
* - orders.receiver(JSON {name,phone,address}) → receiver / tel / address
|
||||
* - order_deliveries.name → receiver;source_order_codes → parent_order_no(截断 50)
|
||||
* - 明细:order_delivery_items.order_delivery_id / order_items.order_id → order_status_items.order_id(新的订单 ID)
|
||||
*
|
||||
* 执行:npm run migration:up
|
||||
*/
|
||||
const { ORDER_STATUS, ORDER_STATUS_ORDER, ORDER_TABLE_BY_STATUS, ORDER_INDEX_TABLE } = require('../../app/lib/orderStatus');
|
||||
const { businessFields, itemFields } = require('../../app/lib/orderFields');
|
||||
|
||||
/** 全部状态表(含作废 / 取消 / 历史),顺序与 order_index.current_status 取值一致 */
|
||||
const ALL_STATUS_TABLES = ORDER_STATUS_ORDER.map(status => ORDER_TABLE_BY_STATUS[status]);
|
||||
|
||||
/** 老状态 → 新流程状态 */
|
||||
const ORDER_STATUS_MAP = { 1: ORDER_STATUS.PENDING, 2: ORDER_STATUS.OUTSOURCING, 3: ORDER_STATUS.DELIVERY, 4: ORDER_STATUS.CANCELED };
|
||||
const DELIVERY_STATUS_MAP = {
|
||||
1: ORDER_STATUS.PENDING,
|
||||
2: ORDER_STATUS.OUTSOURCING,
|
||||
3: ORDER_STATUS.OUTSOURCING,
|
||||
4: ORDER_STATUS.DELIVERY,
|
||||
5: ORDER_STATUS.VOID,
|
||||
9: ORDER_STATUS.CANCELED,
|
||||
};
|
||||
|
||||
/**
|
||||
* 字符串截断(按列长)
|
||||
* @param {*} value 原值
|
||||
* @param {Number} len 最大长度
|
||||
* @return {String|null} 截断结果
|
||||
*/
|
||||
function str(value, len) {
|
||||
if (value === null || value === undefined) return null;
|
||||
const text = String(value);
|
||||
return len ? text.slice(0, len) : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析老 orders.receiver(JSON 字符串或对象)
|
||||
* @param {*} value 原值
|
||||
* @return {Object} { name, phone, address }
|
||||
*/
|
||||
function parseReceiver(value) {
|
||||
if (!value) return {};
|
||||
if (typeof value === 'object') return value;
|
||||
try {
|
||||
return JSON.parse(value) || {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按字段定义过滤对象(只保留目标表存在的列,未给的用 undefined 跳过)
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @param {Object} defs 字段定义
|
||||
* @param {Object} row 源数据
|
||||
* @return {Object} 过滤后的列值
|
||||
*/
|
||||
function pickByDefs(Sequelize, defs, row) {
|
||||
const out = {};
|
||||
for (const [ name ] of Object.entries(defs)) {
|
||||
if (row[name] === undefined) continue;
|
||||
out[name] = row[name];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取已搬迁的来源标记(幂等判断)
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @return {Promise<Set<String>>} "source#id" 集合
|
||||
*/
|
||||
async function migratedKeys(queryInterface) {
|
||||
const keys = new Set();
|
||||
for (const table of ALL_STATUS_TABLES) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
`SELECT legacy_source, legacy_order_id FROM \`${table}\` WHERE legacy_source IS NOT NULL`
|
||||
);
|
||||
for (const row of rows) keys.add(`${row.legacy_source}#${row.legacy_order_id}`);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搬迁单条主记录:确保索引表行存在(取订单 ID)+ 写入目标状态表
|
||||
* @param {Object} ctx 上下文 { queryInterface, Sequelize, statusDefs }
|
||||
* @param {Object} p 参数 { source, row, status, orderNo, parentOrderNo, principalId, fields }
|
||||
* @return {Promise<Number>} 新订单 ID
|
||||
*/
|
||||
async function insertOrder(ctx, p) {
|
||||
const { queryInterface, Sequelize, statusDefs } = ctx;
|
||||
const { sequelize } = queryInterface;
|
||||
const table = ORDER_TABLE_BY_STATUS[p.status];
|
||||
const orderNo = str(p.orderNo, 50);
|
||||
const parentOrderNo = str(p.parentOrderNo, 50);
|
||||
|
||||
// 同主体同单号已存在(上次中断留下的半成品 / 人工建过的同号单)→ 复用其订单 ID,避免唯一键冲突
|
||||
const [ found ] = await sequelize.query(
|
||||
`SELECT id FROM \`${ORDER_INDEX_TABLE}\` WHERE principal_id = ? AND order_no = ? LIMIT 1`,
|
||||
{ replacements: [ p.principalId, orderNo ] }
|
||||
);
|
||||
let newId;
|
||||
if (found.length) {
|
||||
newId = Number(found[0].id);
|
||||
await sequelize.query(
|
||||
`UPDATE \`${ORDER_INDEX_TABLE}\` SET parent_order_no = ?, current_table = ?, current_status = ? WHERE id = ?`,
|
||||
{ replacements: [ parentOrderNo, p.status, p.status, newId ] }
|
||||
);
|
||||
} else {
|
||||
// 显式取 ID:不依赖各 driver 对 INSERT 返回值(insertId)的差异
|
||||
const [ seq ] = await sequelize.query(`SELECT COALESCE(MAX(id), 0) + 1 AS id FROM \`${ORDER_INDEX_TABLE}\``);
|
||||
newId = Number(seq[0].id);
|
||||
await sequelize.query(
|
||||
`INSERT INTO \`${ORDER_INDEX_TABLE}\` (id, order_no, parent_order_no, principal_id, current_table, current_status)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
{ replacements: [ newId, orderNo, parentOrderNo, p.principalId, p.status, p.status ] }
|
||||
);
|
||||
}
|
||||
|
||||
// 该 ID 已落在其它状态表 → 冲突,跳过,避免主键冲突或错乱
|
||||
const occupied = await findOccupiedTable(sequelize, newId, table);
|
||||
if (occupied) {
|
||||
console.warn(`[order] 订单 ID ${newId}(${orderNo})已存在于 ${occupied},跳过该单搬迁`);
|
||||
return null;
|
||||
}
|
||||
|
||||
await insertRow(sequelize, table, {
|
||||
...pickByDefs(Sequelize, statusDefs, p.fields),
|
||||
id: newId,
|
||||
order_no: orderNo,
|
||||
parent_order_no: parentOrderNo,
|
||||
principal_id: p.principalId,
|
||||
status: p.status,
|
||||
legacy_source: p.source,
|
||||
legacy_order_id: p.row.id,
|
||||
});
|
||||
return newId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 该订单 ID 是否已存在于除 expectTable 之外的状态表
|
||||
* @param {Object} sequelize sequelize 实例
|
||||
* @param {Number} id 订单 ID
|
||||
* @param {String} expectTable 允许存在的目标表
|
||||
* @return {Promise<String|null>} 冲突表名,无冲突返回 null
|
||||
*/
|
||||
async function findOccupiedTable(sequelize, id, expectTable) {
|
||||
for (const table of ALL_STATUS_TABLES) {
|
||||
if (table === expectTable) continue;
|
||||
const [ rows ] = await sequelize.query(`SELECT id FROM \`${table}\` WHERE id = ? LIMIT 1`, { replacements: [ id ] });
|
||||
if (rows.length) return table;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化参数值:Sequelize 的位置参数只支持标量,JSON 列的对象 / 数组先转 JSON 字符串
|
||||
* @param {*} value 原值
|
||||
* @return {*} 可作为 ? 参数的值
|
||||
*/
|
||||
function toSqlValue(value) {
|
||||
if (value === null || value === undefined) return value;
|
||||
if (value instanceof Date || Buffer.isBuffer(value)) return value;
|
||||
if (typeof value === 'object') return JSON.stringify(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用写入:过滤 undefined,按列拼 INSERT
|
||||
* @param {Object} sequelize sequelize 实例
|
||||
* @param {String} table 目标表
|
||||
* @param {Object} values 列值
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function insertRow(sequelize, table, values) {
|
||||
const filtered = {};
|
||||
for (const [ key, value ] of Object.entries(values)) {
|
||||
if (value === undefined) continue;
|
||||
filtered[key] = toSqlValue(value);
|
||||
}
|
||||
const cols = Object.keys(filtered);
|
||||
if (!cols.length) return;
|
||||
await sequelize.query(
|
||||
`INSERT INTO \`${table}\` (${cols.map(c => `\`${c}\``).join(', ')}) VALUES (${cols.map(() => '?').join(', ')})`,
|
||||
{ replacements: cols.map(c => filtered[c]) }
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { sequelize } = queryInterface;
|
||||
const statusDefs = businessFields(Sequelize, ORDER_STATUS.PENDING);
|
||||
const itemDefs = itemFields(Sequelize);
|
||||
const done = await migratedKeys(queryInterface);
|
||||
const ctx = { queryInterface, Sequelize, statusDefs };
|
||||
const orderIdByLegacy = new Map(); // "source#id" → 新订单 ID
|
||||
let migrated = 0;
|
||||
|
||||
// 1) 原订单表 orders
|
||||
const [ orders ] = await sequelize.query('SELECT * FROM `orders`');
|
||||
for (const row of orders) {
|
||||
if (done.has(`orders#${row.id}`)) continue;
|
||||
const status = ORDER_STATUS_MAP[Number(row.status)] || ORDER_STATUS.PENDING;
|
||||
const receiver = parseReceiver(row.receiver);
|
||||
const newId = await insertOrder(ctx, {
|
||||
source: 'orders',
|
||||
row,
|
||||
status,
|
||||
orderNo: str(row.order_no, 50),
|
||||
parentOrderNo: null,
|
||||
principalId: Number(row.principal_id),
|
||||
fields: {
|
||||
...pickByDefs(Sequelize, statusDefs, row),
|
||||
receiver: str(receiver.name, 50),
|
||||
tel: str(receiver.phone, 50),
|
||||
address: str(receiver.address, 255),
|
||||
detail_address: str(receiver.address, 500),
|
||||
legacy_status: row.status,
|
||||
status,
|
||||
},
|
||||
});
|
||||
if (!newId) continue;
|
||||
orderIdByLegacy.set(`orders#${row.id}`, newId);
|
||||
migrated++;
|
||||
}
|
||||
|
||||
// 2) 原订单明细 order_items → order_status_items
|
||||
const [ orderItems ] = await sequelize.query('SELECT * FROM `order_items`');
|
||||
for (const row of orderItems) {
|
||||
const orderId = orderIdByLegacy.get(`orders#${row.order_id}`) ||
|
||||
(await findMigratedOrderId(sequelize, 'orders', row.order_id));
|
||||
if (!orderId) continue;
|
||||
const exists = await itemExists(sequelize, 'order_items', row.id);
|
||||
if (exists) continue;
|
||||
const values = {
|
||||
...pickByDefs(Sequelize, itemDefs, row),
|
||||
principal_id: Number(row.principal_id),
|
||||
order_id: orderId,
|
||||
shop_id: row.shop_id,
|
||||
item_name: str(row.name, 255),
|
||||
order_line_no: String(row.id).slice(0, 20),
|
||||
legacy_source: 'order_items',
|
||||
legacy_order_item_id: row.id,
|
||||
};
|
||||
await insertRow(sequelize, 'order_status_items', values);
|
||||
migrated++;
|
||||
}
|
||||
|
||||
// 3) 发货单 order_deliveries
|
||||
const [ deliveries ] = await sequelize.query('SELECT * FROM `order_deliveries`');
|
||||
for (const row of deliveries) {
|
||||
if (done.has(`order_deliveries#${row.id}`)) continue;
|
||||
const status = DELIVERY_STATUS_MAP[Number(row.status)] || ORDER_STATUS.PENDING;
|
||||
const newId = await insertOrder(ctx, {
|
||||
source: 'order_deliveries',
|
||||
row,
|
||||
status,
|
||||
orderNo: str(row.delivery_order_code, 50),
|
||||
parentOrderNo: str(row.source_order_codes, 50),
|
||||
principalId: Number(row.principal_id),
|
||||
fields: {
|
||||
...pickByDefs(Sequelize, statusDefs, row),
|
||||
receiver: str(row.name, 50),
|
||||
legacy_status: row.status,
|
||||
status,
|
||||
},
|
||||
});
|
||||
if (!newId) continue;
|
||||
orderIdByLegacy.set(`order_deliveries#${row.id}`, newId);
|
||||
migrated++;
|
||||
}
|
||||
|
||||
// 4) 发货单明细 order_delivery_items → order_status_items
|
||||
const [ deliveryItems ] = await sequelize.query('SELECT * FROM `order_delivery_items`');
|
||||
for (const row of deliveryItems) {
|
||||
const orderId = orderIdByLegacy.get(`order_deliveries#${row.order_delivery_id}`) ||
|
||||
(await findMigratedOrderId(sequelize, 'order_deliveries', row.order_delivery_id));
|
||||
if (!orderId) continue;
|
||||
if (await itemExists(sequelize, 'order_delivery_items', row.id)) continue;
|
||||
const values = {
|
||||
...pickByDefs(Sequelize, itemDefs, row),
|
||||
principal_id: Number(row.principal_id),
|
||||
order_id: orderId,
|
||||
legacy_source: 'order_delivery_items',
|
||||
legacy_order_item_id: row.id,
|
||||
};
|
||||
await insertRow(sequelize, 'order_status_items', values);
|
||||
migrated++;
|
||||
}
|
||||
|
||||
console.log(`[order] 老数据搬迁完成:新增 ${migrated} 条(源表行数 orders=${orders.length} / order_items=${orderItems.length} / order_deliveries=${deliveries.length} / order_delivery_items=${deliveryItems.length})`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
const sources = [ 'orders', 'order_deliveries' ];
|
||||
const itemSources = [ 'order_items', 'order_delivery_items' ];
|
||||
const otherTables = ALL_STATUS_TABLES;
|
||||
|
||||
const ids = [];
|
||||
for (const table of otherTables) {
|
||||
const [ rows ] = await sequelize.query(`SELECT id FROM \`${table}\` WHERE legacy_source IN (?)`, { replacements: [ sources ] });
|
||||
for (const row of rows) ids.push(row.id);
|
||||
}
|
||||
await sequelize.query('DELETE FROM `order_status_items` WHERE legacy_source IN (?)', { replacements: [ itemSources ] });
|
||||
for (const table of otherTables) {
|
||||
await sequelize.query(`DELETE FROM \`${table}\` WHERE legacy_source IN (?)`, { replacements: [ sources ] });
|
||||
}
|
||||
if (ids.length) {
|
||||
await sequelize.query('DELETE FROM `order_index` WHERE id IN (?)', { replacements: [ ids ] });
|
||||
}
|
||||
console.log(`[order] 已回退老数据搬迁:删除 ${ids.length} 条订单与对应明细`);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 查已搬迁订单的新 ID(按来源表 + 源主键)
|
||||
* @param {Object} sequelize sequelize 实例
|
||||
* @param {String} source 来源表
|
||||
* @param {Number} legacyId 源主键
|
||||
* @return {Promise<Number|null>} 新订单 ID
|
||||
*/
|
||||
async function findMigratedOrderId(sequelize, source, legacyId) {
|
||||
for (const table of ALL_STATUS_TABLES) {
|
||||
const [ rows ] = await sequelize.query(
|
||||
`SELECT id FROM \`${table}\` WHERE legacy_source = ? AND legacy_order_id = ? LIMIT 1`,
|
||||
{ replacements: [ source, legacyId ] }
|
||||
);
|
||||
if (rows.length) return rows[0].id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 明细是否已搬迁
|
||||
* @param {Object} sequelize sequelize 实例
|
||||
* @param {String} source 来源表
|
||||
* @param {Number} legacyId 源明细主键
|
||||
* @return {Promise<Boolean>} 已存在返回 true
|
||||
*/
|
||||
async function itemExists(sequelize, source, legacyId) {
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT id FROM `order_status_items` WHERE legacy_source = ? AND legacy_order_item_id = ? LIMIT 1',
|
||||
{ replacements: [ source, legacyId ] }
|
||||
);
|
||||
return rows.length > 0;
|
||||
}
|
||||
@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
|
||||
const { applyOrderMenu, LEGACY_DELIVERY_MENUS } = require('../orderMenu');
|
||||
|
||||
/**
|
||||
* 把老发货单菜单并入「订单」
|
||||
*
|
||||
* 背景:老发货单(order_deliveries)的数据与全部能力(创建 / 审核+锁库存 / 推送仓库 / 驳回换号 /
|
||||
* 取消 / 作废 / 恢复 / 明细维护 / 换仓库换店铺 / 回传确认)已迁到新表(order_index + order_status_*),
|
||||
* 且「订单」页(views/Order/Status.vue)已实现同样的操作,故下线这两个独立菜单入口:
|
||||
* - 创建发货单 /order-create
|
||||
* - 发货单 /order-delivery
|
||||
* 代码文件保留(views/Order/Create.vue、views/Order/Index.vue),菜单不再展示。
|
||||
* 幂等:重复执行结果一致(DELETE 不存在的行不做任何事)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await applyOrderMenu(queryInterface);
|
||||
console.log(`[order] 已下线老发货单菜单:${LEGACY_DELIVERY_MENUS.map(m => `${m.name}(${m.path})`).join('、')}(能力已并入「订单」页)`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
const [ orderMgmt ] = await sequelize.query(
|
||||
"SELECT id FROM menus WHERE name = '订单管理' AND parent_id = 0 LIMIT 1",
|
||||
{ type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (!orderMgmt) return;
|
||||
|
||||
const restore = [
|
||||
{ name: '创建发货单', path: '/order-create', component: 'views/Order/Create.vue', icon: 'Plus', permission: 'orderDelivery:create', sort: 80 },
|
||||
{ name: '发货单', path: '/order-delivery', component: 'views/Order/Index.vue', icon: 'Van', permission: 'orderDelivery:list', sort: 75 },
|
||||
];
|
||||
for (const menu of restore) {
|
||||
const [ exist ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE path = ? LIMIT 1',
|
||||
{ replacements: [ menu.path ], type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (exist) continue;
|
||||
await sequelize.query(
|
||||
`INSERT INTO menus
|
||||
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
|
||||
VALUES (?, ?, 2, ?, ?, ?, ?, ?, 1, NOW(), NOW())`,
|
||||
{
|
||||
replacements: [
|
||||
Number(orderMgmt.id), menu.name, menu.path, menu.icon,
|
||||
menu.permission, menu.component, menu.sort,
|
||||
],
|
||||
}
|
||||
);
|
||||
}
|
||||
console.log('[order] 已恢复老发货单菜单入口');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
const { migrate, STATUS_TABLES } = require('../orderStatusTables');
|
||||
const { ORDER_STATUS, ORDER_TABLE_BY_STATUS } = require('../../app/lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 新增「待推送(queued)」状态表
|
||||
*
|
||||
* 背景(2026-09-16 按用户要求):原来「审核通过」直接进「委外中」,把「已审核待推送」与
|
||||
* 「已推送成功」混在同一个状态里。现在拆开:
|
||||
* 待审核 →(审核+锁库存)待推送 →(推送仓库成功)委外中 →(仓库回传确认)配送
|
||||
* 推送失败 → 异常
|
||||
* 本迁移建表 + 补齐列(结构与其它状态表完全一致,字段定义来自 app/lib/orderFields.js);
|
||||
* 存量「委外中」未推送成功的单据由下一条迁移搬到本表。
|
||||
*
|
||||
* 幂等:`migrate()` 会按需建表/补列,重复执行无副作用。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await migrate(queryInterface, Sequelize);
|
||||
console.log(`[order] 已确保 ${STATUS_TABLES.length} 张状态表就绪(含新增 ${ORDER_TABLE_BY_STATUS[ORDER_STATUS.QUEUED]})`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable(ORDER_TABLE_BY_STATUS[ORDER_STATUS.QUEUED]);
|
||||
console.log(`[order] 已删除 ${ORDER_TABLE_BY_STATUS[ORDER_STATUS.QUEUED]}`);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,88 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
ORDER_STATUS,
|
||||
ORDER_TABLE_BY_STATUS,
|
||||
ORDER_INDEX_TABLE,
|
||||
orderCopyFields,
|
||||
} = require('../../app/lib/orderStatus');
|
||||
|
||||
/**
|
||||
* 存量「委外中」订单按是否推送成功分流:未推送成功的搬到「待推送(queued)」
|
||||
*
|
||||
* 判定「推送成功」的依据(三者任一成立即视为已推送成功,留在委外中):
|
||||
* - `wms_status = 'pushed'`
|
||||
* - `wms_push_result.success = true`
|
||||
* - `wms_order_no` 非空(外部单据号已回写)
|
||||
* 其余(从未推送 / 推送失败但仍在委外中)迁到待推续表,等定时任务或人工推送。
|
||||
*
|
||||
* 幂等:只处理「委外中且未推送成功」的行,重跑不会重复搬迁。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { sequelize } = queryInterface;
|
||||
const fromTable = ORDER_TABLE_BY_STATUS[ORDER_STATUS.OUTSOURCING];
|
||||
const toTable = ORDER_TABLE_BY_STATUS[ORDER_STATUS.QUEUED];
|
||||
const copyFields = orderCopyFields(Sequelize);
|
||||
const notPushed = `(
|
||||
\`wms_status\` IS NULL OR \`wms_status\` <> 'pushed'
|
||||
) AND (
|
||||
\`wms_push_result\` IS NULL OR JSON_EXTRACT(\`wms_push_result\`, '$.success') IS NULL OR JSON_EXTRACT(\`wms_push_result\`, '$.success') = false
|
||||
) AND \`wms_order_no\` IS NULL`;
|
||||
|
||||
const [ targets ] = await sequelize.query(
|
||||
`SELECT id, order_no FROM \`${fromTable}\` WHERE ${notPushed}`
|
||||
);
|
||||
if (!targets.length) {
|
||||
console.log('[order] 无需分流:委外中订单均已推送成功');
|
||||
return;
|
||||
}
|
||||
|
||||
const ids = targets.map(row => Number(row.id));
|
||||
const transaction = await sequelize.transaction();
|
||||
try {
|
||||
// 搬运业务列(id 保留,created_at/updated_at 原样保留)
|
||||
await sequelize.query(
|
||||
`INSERT INTO \`${toTable}\` (id, ${copyFields.map(col => `\`${col}\``).join(', ')}, status, created_at, updated_at)
|
||||
SELECT id, ${copyFields.map(col => `\`${col}\``).join(', ')}, :status, created_at, updated_at FROM \`${fromTable}\`
|
||||
WHERE id IN (:ids)`,
|
||||
{ replacements: { ids, status: ORDER_STATUS.QUEUED }, transaction }
|
||||
);
|
||||
await sequelize.query(
|
||||
`DELETE FROM \`${fromTable}\` WHERE id IN (:ids)`,
|
||||
{ replacements: { ids }, transaction }
|
||||
);
|
||||
await sequelize.query(
|
||||
`UPDATE \`${ORDER_INDEX_TABLE}\` SET current_table = :status, current_status = :status WHERE id IN (:ids)`,
|
||||
{ replacements: { ids, status: ORDER_STATUS.QUEUED }, transaction }
|
||||
);
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
|
||||
console.log(`[order] 已把 ${ids.length} 条未推送成功的委外中订单分流到「${ORDER_STATUS.QUEUED}」:${targets.map(r => r.order_no).join('、')}`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
// 回退:把待推送的表整表搬回委外中(状态语义回退到拆分前的口径)
|
||||
const fromTable = ORDER_TABLE_BY_STATUS[ORDER_STATUS.QUEUED];
|
||||
const toTable = ORDER_TABLE_BY_STATUS[ORDER_STATUS.OUTSOURCING];
|
||||
await sequelize.query(`UPDATE \`${fromTable}\` SET status = '${ORDER_STATUS.OUTSOURCING}'`);
|
||||
const [ rows ] = await sequelize.query(`SELECT id FROM \`${fromTable}\``);
|
||||
if (!rows.length) return;
|
||||
const ids = rows.map(row => Number(row.id));
|
||||
await sequelize.query(
|
||||
`INSERT INTO \`${toTable}\` SELECT * FROM \`${fromTable}\` WHERE id IN (:ids)`,
|
||||
{ replacements: { ids } }
|
||||
);
|
||||
await sequelize.query(`DELETE FROM \`${fromTable}\` WHERE id IN (:ids)`, { replacements: { ids } });
|
||||
await sequelize.query(
|
||||
`UPDATE \`${ORDER_INDEX_TABLE}\` SET current_table = '${ORDER_STATUS.OUTSOURCING}', current_status = '${ORDER_STATUS.OUTSOURCING}' WHERE id IN (:ids)`,
|
||||
{ replacements: { ids } }
|
||||
);
|
||||
console.log(`[order] 已回退:${ids.length} 条待推送订单搬回委外中`);
|
||||
},
|
||||
};
|
||||
133
backend/database/orderMenu.js
Normal file
133
backend/database/orderMenu.js
Normal file
@ -0,0 +1,133 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 「订单」菜单口径(唯一来源,供菜单迁移复用)。
|
||||
*
|
||||
* 口径(2026-09-15 按用户要求):订单按状态分表、页面按状态分视图展示,
|
||||
* 该页面就是「订单」菜单的内容,不再单独挂「订单拆分」菜单。
|
||||
*/
|
||||
const ORDER_MENU = {
|
||||
name: '订单',
|
||||
path: '/order',
|
||||
type: 2,
|
||||
icon: 'Tickets',
|
||||
component: 'views/Order/Status.vue',
|
||||
permission: 'order:list',
|
||||
};
|
||||
|
||||
/** 上一版「订单」页(发货单列表)——回退用;代码保留但不再挂菜单 */
|
||||
const PREVIOUS_ORDER_MENU = {
|
||||
component: 'views/Order/Index.vue',
|
||||
permission: 'order:list',
|
||||
};
|
||||
|
||||
/** 已废弃的独立「订单拆分」菜单 */
|
||||
const LEGACY_SPLIT_MENU = {
|
||||
name: '订单拆分',
|
||||
path: '/order-split',
|
||||
icon: 'Switch',
|
||||
permission: 'splitOrder:list',
|
||||
component: 'views/Order/Status.vue',
|
||||
sort: 60,
|
||||
};
|
||||
|
||||
/**
|
||||
* 已并入「订单」的老发货单菜单(创建发货单 / 发货单列表)
|
||||
*
|
||||
* 口径(2026-09-16 按用户要求):老发货单的**能力**(创建 / 审核 / 推送 / 驳回 / 取消 / 作废 / 恢复 /
|
||||
* 明细维护 / 换仓换店铺)已全部落到新表并在「订单」页实现,数据也已迁入新表,故不再单独挂这两个菜单;
|
||||
* 代码文件保留(views/Order/Index.vue、Create.vue),仅菜单入口下线,必要时可一键恢复。
|
||||
*/
|
||||
const LEGACY_DELIVERY_MENUS = [
|
||||
{ path: '/order-create', name: '创建发货单' },
|
||||
{ path: '/order-delivery', name: '发货单' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 应用「订单」菜单口径:
|
||||
* 1. 「订单」菜单(/order)指向订单页(views/Order/Status.vue),权限 order:list;
|
||||
* 2. 删除历史上单独挂的「订单拆分」菜单(其能力已并入「订单」);
|
||||
* 3. 删除老发货单菜单(创建发货单 / 发货单列表)——能力与数据均已并入「订单」。
|
||||
* 幂等:重复执行结果一致;表/行不存在时为空操作。
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function applyOrderMenu(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET component = ?, permission = ?, icon = ?, updated_at = NOW()
|
||||
WHERE name = ? AND path = ? AND type = ?`,
|
||||
{
|
||||
replacements: [
|
||||
ORDER_MENU.component, ORDER_MENU.permission, ORDER_MENU.icon,
|
||||
ORDER_MENU.name, ORDER_MENU.path, ORDER_MENU.type,
|
||||
],
|
||||
}
|
||||
);
|
||||
|
||||
await sequelize.query(
|
||||
'DELETE FROM menus WHERE name = ? AND path = ?',
|
||||
{ replacements: [ LEGACY_SPLIT_MENU.name, LEGACY_SPLIT_MENU.path ] }
|
||||
);
|
||||
|
||||
for (const menu of LEGACY_DELIVERY_MENUS) {
|
||||
await sequelize.query(
|
||||
'DELETE FROM menus WHERE path = ?',
|
||||
{ replacements: [ menu.path ] }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回退「订单」菜单口径:订单页指回发货单列表,并重建「订单拆分」菜单(挂在「订单管理」下)
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function revertOrderMenu(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
await sequelize.query(
|
||||
`UPDATE menus SET component = ?, permission = ?, updated_at = NOW()
|
||||
WHERE name = ? AND path = ? AND type = ?`,
|
||||
{
|
||||
replacements: [
|
||||
PREVIOUS_ORDER_MENU.component, PREVIOUS_ORDER_MENU.permission,
|
||||
ORDER_MENU.name, ORDER_MENU.path, ORDER_MENU.type,
|
||||
],
|
||||
}
|
||||
);
|
||||
|
||||
const [ orderMgmt ] = await sequelize.query(
|
||||
"SELECT id FROM menus WHERE name = '订单管理' AND parent_id = 0 LIMIT 1",
|
||||
{ type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (!orderMgmt) return;
|
||||
|
||||
const [ exist ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE name = ? AND path = ? LIMIT 1',
|
||||
{ replacements: [ LEGACY_SPLIT_MENU.name, LEGACY_SPLIT_MENU.path ], type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (exist) return;
|
||||
|
||||
await sequelize.query(
|
||||
`INSERT INTO menus
|
||||
(parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at)
|
||||
VALUES (?, ?, 2, ?, ?, ?, ?, ?, 1, NOW(), NOW())`,
|
||||
{
|
||||
replacements: [
|
||||
Number(orderMgmt.id), LEGACY_SPLIT_MENU.name, LEGACY_SPLIT_MENU.path, LEGACY_SPLIT_MENU.icon,
|
||||
LEGACY_SPLIT_MENU.permission, LEGACY_SPLIT_MENU.component, LEGACY_SPLIT_MENU.sort,
|
||||
],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ORDER_MENU,
|
||||
PREVIOUS_ORDER_MENU,
|
||||
LEGACY_SPLIT_MENU,
|
||||
LEGACY_DELIVERY_MENUS,
|
||||
applyOrderMenu,
|
||||
revertOrderMenu,
|
||||
};
|
||||
388
backend/database/orderStatusTables.js
Normal file
388
backend/database/orderStatusTables.js
Normal file
@ -0,0 +1,388 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
ORDER_TABLE_PREFIX,
|
||||
ORDER_INDEX_TABLE,
|
||||
ORDER_ITEM_TABLE,
|
||||
ORDER_TABLE_BY_STATUS,
|
||||
ORDER_STATUS_ORDER,
|
||||
ORDER_STATUS_LABELS,
|
||||
ORDER_STATUS,
|
||||
} = require('../app/lib/orderStatus');
|
||||
const {
|
||||
businessFields,
|
||||
historyFields,
|
||||
itemFields,
|
||||
legacyExtraColumnNames,
|
||||
} = require('../app/lib/orderFields');
|
||||
|
||||
/**
|
||||
* 订单(状态分表)建表 / 改表 DDL(唯一来源,供迁移复用)。
|
||||
*
|
||||
* 表结构:
|
||||
* - order_index 订单索引表:订单 ID 以本表为准,current_table/current_status 记录当前归属表与状态
|
||||
* - order_status_pending 待审核
|
||||
* - order_status_queued 待推送(审核通过,等推送仓库)
|
||||
* - order_status_exception 异常
|
||||
* - order_status_outsourcing 委外中
|
||||
* - order_status_delivery 配送
|
||||
* - order_status_void 已作废(侧路)
|
||||
* - order_status_canceled 已取消(侧路)
|
||||
* - order_status_history 历史(多 archived_at / transferred_at)
|
||||
* - order_status_items 明细表(各状态表共用)
|
||||
*
|
||||
* 结构口径:各状态表字段完全一致,且是「原订单表 orders + 发货单 order_deliveries(含明细)」
|
||||
* 的**超集**(字段定义见 app/lib/orderFields.js),老数据可无损迁入。
|
||||
* 流转 = 来源表删除 + 目标表写入 + 更新索引表 current_table/current_status(明细按订单 ID 关联,不搬迁)。
|
||||
*/
|
||||
|
||||
/** 状态表的建表定义(由状态枚举派生,新增状态自动包含) */
|
||||
const STATUS_TABLES = ORDER_STATUS_ORDER.map(status => ({
|
||||
table: ORDER_TABLE_BY_STATUS[status],
|
||||
status,
|
||||
label: status === ORDER_STATUS.HISTORY ? `订单-${ORDER_STATUS_LABELS[status]}(归档)` : `订单-${ORDER_STATUS_LABELS[status]}`,
|
||||
}));
|
||||
|
||||
/** 状态值 → 中文(建表注释用) */
|
||||
const STATUS_COMMENT = `状态:${ORDER_STATUS_ORDER.map(status => `${status} ${ORDER_STATUS_LABELS[status]}`).join(' / ')}`;
|
||||
|
||||
/**
|
||||
* 当前数据库已存在的表名集合(小写)
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @return {Promise<Set<String>>} 表名集合
|
||||
*/
|
||||
async function existingTables(queryInterface) {
|
||||
const list = await queryInterface.showAllTables();
|
||||
return new Set(
|
||||
(list || []).map(item => String(item && item.tableName ? item.tableName : item).toLowerCase())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 索引表字段定义
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Object} 字段定义
|
||||
*/
|
||||
function indexFields(Sequelize) {
|
||||
const { BIGINT, STRING, DATE } = Sequelize;
|
||||
return {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
comment: '主键(订单全局唯一 ID)',
|
||||
},
|
||||
order_no: { type: STRING(50), allowNull: false, comment: '订单号' },
|
||||
parent_order_no: { type: STRING(50), comment: '来源订单号(上游/平台订单号)' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' },
|
||||
current_table: {
|
||||
type: STRING(16),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '当前所在表:pending/queued/exception/outsourcing/delivery/void/canceled/history(取值同 current_status)',
|
||||
},
|
||||
current_status: {
|
||||
type: STRING(16),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: STATUS_COMMENT,
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间(用于超 3 个月自动归档判断)',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 建表公共选项
|
||||
* @return {Object} createTable 选项
|
||||
*/
|
||||
function tableOptions() {
|
||||
return { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 补齐已存在表的缺失列(幂等):新增字段只需加到 app/lib/orderFields.js 即可,无需手写 ALTER
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @param {String} table 表名
|
||||
* @param {Object} defs 字段定义(name → 定义)
|
||||
* @return {Promise<Array<String>>} 本次新增的列名
|
||||
*/
|
||||
async function syncTableColumns(queryInterface, table, defs) {
|
||||
let columns;
|
||||
try {
|
||||
columns = await queryInterface.describeTable(table);
|
||||
} catch (e) {
|
||||
return []; // 表不存在,由建表逻辑负责
|
||||
}
|
||||
const added = [];
|
||||
for (const [ name, def ] of Object.entries(defs)) {
|
||||
if (columns[name]) continue;
|
||||
await queryInterface.addColumn(table, name, def);
|
||||
added.push(name);
|
||||
}
|
||||
if (added.length) {
|
||||
console.log(`[order] ${table} 补齐 ${added.length} 列:${added.join(', ')}`);
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理「最早一版设计」的残留表(单活动表 + bucket 索引表)
|
||||
* 注:拆单命名时代的状态表(split_order_pending 等)**不在此清理**,由重命名逻辑就地改名,避免丢数据。
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function dropLegacyTables(queryInterface) {
|
||||
const tables = await existingTables(queryInterface);
|
||||
|
||||
const legacyHints = [
|
||||
{ table: 'split_order_active', dropAlways: true },
|
||||
{ table: 'split_order_index', keys: [ 'current_table', 'current_status' ] },
|
||||
{ table: 'split_order_history', keys: [ 'archived_at', 'transferred_at' ] },
|
||||
];
|
||||
|
||||
for (const hint of legacyHints) {
|
||||
if (!tables.has(hint.table)) continue;
|
||||
if (!hint.dropAlways) {
|
||||
const columns = await queryInterface.describeTable(hint.table);
|
||||
const isNewStructure = hint.keys.every(key => columns[key]);
|
||||
if (isNewStructure) continue;
|
||||
}
|
||||
const [[ count ]] = await queryInterface.sequelize.query(
|
||||
`SELECT COUNT(*) AS total FROM \`${hint.table}\``
|
||||
);
|
||||
await queryInterface.dropTable(hint.table);
|
||||
console.log(`[order] 已删除旧设计残留表 ${hint.table}(原有 ${count ? count.total : 0} 条数据,旧设计与新结构不兼容)`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 旧命名表名(拆单命名时代):order_status_pending → split_order_pending
|
||||
* @param {String} table 新表名
|
||||
* @return {String} 旧表名
|
||||
*/
|
||||
function legacyTableNameOf(table) {
|
||||
return table.startsWith(ORDER_TABLE_PREFIX)
|
||||
? table.replace(ORDER_TABLE_PREFIX, 'split_order_')
|
||||
: table;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把状态表在「旧命名(拆单命名时代)」与「当前命名」之间就地改名(保留数据与结构)
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @param {Object} [options] 选项
|
||||
* @param {Boolean} [options.reverse] true 表示反向改名(新 → 旧,供迁移 down 使用)
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function renameLegacyTables(queryInterface, options = {}) {
|
||||
const reverse = Boolean(options.reverse);
|
||||
const tables = await existingTables(queryInterface);
|
||||
|
||||
for (const def of STATUS_TABLES) {
|
||||
const from = reverse ? def.table : legacyTableNameOf(def.table);
|
||||
const to = reverse ? legacyTableNameOf(def.table) : def.table;
|
||||
|
||||
if (tables.has(from) && !tables.has(to)) {
|
||||
await queryInterface.renameTable(from, to);
|
||||
console.log(`[order] 已重命名表 ${from} → ${to}`);
|
||||
} else if (tables.has(to) && tables.has(from)) {
|
||||
console.log(`[order] 表 ${to} 与 ${from} 同时存在,跳过重命名(请人工确认)`);
|
||||
} else if (!tables.has(to)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await renameLegacyIndexes(queryInterface, to, reverse);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把表上仍是「旧命名」的索引改名(索引名同样带状态表名前缀)
|
||||
* 说明:不同 Sequelize 小版本不一定有 queryInterface.renameIndex,这里统一用 remove + add 实现
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @param {String} table 表名
|
||||
* @param {Boolean} reverse true 表示反向改名(新 → 旧)
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function renameLegacyIndexes(queryInterface, table, reverse) {
|
||||
const fromToken = reverse ? '_order_status_' : '_split_order_';
|
||||
const toToken = reverse ? '_split_order_' : '_order_status_';
|
||||
const indexes = await queryInterface.showIndex(table);
|
||||
const names = new Set(indexes.map(item => item.name));
|
||||
|
||||
for (const idx of indexes) {
|
||||
if (!idx.name || idx.name.indexOf(fromToken) === -1) continue;
|
||||
const newName = idx.name.replace(fromToken, toToken);
|
||||
if (names.has(newName)) continue;
|
||||
const fields = (idx.fields || []).map(field => field.attribute).filter(Boolean);
|
||||
if (!fields.length) continue;
|
||||
await queryInterface.removeIndex(table, idx.name);
|
||||
await queryInterface.addIndex(table, { fields, unique: Boolean(idx.unique), name: newName });
|
||||
names.delete(idx.name);
|
||||
names.add(newName);
|
||||
console.log(`[order] 已重命名索引 ${idx.name} → ${newName}(表 ${table})`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建订单索引表、5 张状态表与明细表(已存在则跳过,可重复执行)
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function createTables(queryInterface, Sequelize) {
|
||||
const tables = await existingTables(queryInterface);
|
||||
const options = tableOptions();
|
||||
|
||||
// 1) 索引表
|
||||
if (!tables.has(ORDER_INDEX_TABLE)) {
|
||||
await queryInterface.createTable(ORDER_INDEX_TABLE, indexFields(Sequelize), {
|
||||
...options,
|
||||
comment: '订单索引表(订单 ID 以此为准)',
|
||||
});
|
||||
await queryInterface.addIndex(ORDER_INDEX_TABLE, {
|
||||
fields: [ 'principal_id', 'order_no' ],
|
||||
unique: true,
|
||||
name: 'uk_order_index_principal_no',
|
||||
});
|
||||
await queryInterface.addIndex(ORDER_INDEX_TABLE, {
|
||||
fields: [ 'principal_id', 'current_table', 'current_status' ],
|
||||
name: 'idx_order_index_principal_table',
|
||||
});
|
||||
}
|
||||
|
||||
// 2) 5 张状态表
|
||||
for (const def of STATUS_TABLES) {
|
||||
if (tables.has(def.table)) continue;
|
||||
// 兼容:旧命名表已存在(拆单命名时代)时跳过创建,交由重命名逻辑就地改名,避免与重命名冲突
|
||||
if (tables.has(legacyTableNameOf(def.table))) {
|
||||
console.log(`[order] 检测到旧命名表 ${legacyTableNameOf(def.table)},跳过创建 ${def.table}(由重命名处理)`);
|
||||
continue;
|
||||
}
|
||||
const fields = { ...businessFields(Sequelize, def.status) };
|
||||
if (def.table === ORDER_TABLE_BY_STATUS.history) Object.assign(fields, historyFields(Sequelize));
|
||||
await queryInterface.createTable(def.table, fields, { ...options, comment: def.label });
|
||||
await queryInterface.addIndex(def.table, {
|
||||
fields: [ 'principal_id', 'status' ],
|
||||
name: `idx_${def.table}_principal_status`,
|
||||
});
|
||||
await queryInterface.addIndex(def.table, {
|
||||
fields: [ 'principal_id', 'order_no' ],
|
||||
unique: true,
|
||||
name: `uk_${def.table}_principal_no`,
|
||||
});
|
||||
await queryInterface.addIndex(def.table, {
|
||||
fields: [ 'principal_id', 'created_at' ],
|
||||
name: `idx_${def.table}_principal_created`,
|
||||
});
|
||||
}
|
||||
|
||||
// 3) 明细表(5 张状态表共用)
|
||||
if (!tables.has(ORDER_ITEM_TABLE)) {
|
||||
await queryInterface.createTable(ORDER_ITEM_TABLE, itemFields(Sequelize), {
|
||||
...options,
|
||||
comment: '订单明细(5 张状态表共用;字段为发货单明细 ∪ 原订单明细的超集)',
|
||||
});
|
||||
await queryInterface.addIndex(ORDER_ITEM_TABLE, {
|
||||
fields: [ 'principal_id', 'order_id' ],
|
||||
name: 'idx_order_status_items_principal_order',
|
||||
});
|
||||
await queryInterface.addIndex(ORDER_ITEM_TABLE, {
|
||||
fields: [ 'order_id', 'order_line_no' ],
|
||||
unique: true,
|
||||
name: 'uk_order_status_items_line',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 补齐所有订单表的缺失列(表存在但字段是旧结构时用;新建字段只需改字段定义)
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Promise<Array<String>>} 本次新增的列名合计
|
||||
*/
|
||||
async function syncColumns(queryInterface, Sequelize) {
|
||||
const added = [];
|
||||
for (const def of STATUS_TABLES) {
|
||||
const fields = { ...businessFields(Sequelize, def.status) };
|
||||
if (def.table === ORDER_TABLE_BY_STATUS.history) Object.assign(fields, historyFields(Sequelize));
|
||||
added.push(...await syncTableColumns(queryInterface, def.table, fields));
|
||||
}
|
||||
added.push(...await syncTableColumns(queryInterface, ORDER_ITEM_TABLE, itemFields(Sequelize)));
|
||||
return added;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除订单索引表、全部状态表与明细表
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function dropTables(queryInterface) {
|
||||
for (const table of [
|
||||
ORDER_ITEM_TABLE,
|
||||
...ORDER_STATUS_ORDER.map(status => ORDER_TABLE_BY_STATUS[status]).reverse(),
|
||||
ORDER_INDEX_TABLE,
|
||||
]) {
|
||||
await queryInterface.dropTable(table);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回退「为容纳老表而扩展的字段」:删除扩展列并移除明细表(保留状态流程核心字段)
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function dropLegacyColumns(queryInterface, Sequelize) {
|
||||
const tables = await existingTables(queryInterface);
|
||||
const extras = legacyExtraColumnNames(Sequelize);
|
||||
for (const def of STATUS_TABLES) {
|
||||
if (!tables.has(def.table)) continue;
|
||||
const columns = await queryInterface.describeTable(def.table);
|
||||
for (const name of extras) {
|
||||
if (!columns[name]) continue;
|
||||
await queryInterface.removeColumn(def.table, name);
|
||||
}
|
||||
}
|
||||
if (tables.has(ORDER_ITEM_TABLE)) await queryInterface.dropTable(ORDER_ITEM_TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立订单表结构(幂等,顺序很关键):
|
||||
* 1. 旧命名(拆单命名时代)状态表就地在改名到当前命名(保留数据);
|
||||
* 2. 清理更早的「单活动表」设计残留表;
|
||||
* 3. 建缺失的表;
|
||||
* 4. 补齐已存在表缺失的列(含为容纳老表而扩展的字段)。
|
||||
* @param {Object} queryInterface sequelize queryInterface
|
||||
* @param {Object} Sequelize sequelize 构造函数
|
||||
* @return {Promise<void>} 无
|
||||
*/
|
||||
async function migrate(queryInterface, Sequelize) {
|
||||
await renameLegacyTables(queryInterface);
|
||||
await dropLegacyTables(queryInterface);
|
||||
await createTables(queryInterface, Sequelize);
|
||||
await syncColumns(queryInterface, Sequelize);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
STATUS_TABLES,
|
||||
migrate,
|
||||
createTables,
|
||||
syncColumns,
|
||||
syncTableColumns,
|
||||
dropTables,
|
||||
dropLegacyColumns,
|
||||
renameLegacyTables,
|
||||
legacyTableNameOf,
|
||||
indexFields,
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user