feat(backend): 发货单模块与 WMS 定时推送队列
- 发货单主表/明细表(order_deliveries / order_delivery_items)控制器与模型 - 表头金额与明细派生字段重算(utils/recalcOrderDelivery.js) - 状态流转:审核/驳回/取消/恢复/作废、批量审核、批量切换仓库 - 审核入队 + 定时推送:service/orderDeliveryPush.js(乐观锁 CAS 防重、失败重试上限 3 次、业务失败退回待审核)+ schedule/orderDeliveryPush.js - 收件人 AI 智能识别(service/ai.js,DeepSeek) - 相关迁移:建表、站内字段、明细表、订单类型默认值、快递字典、菜单种子、历史数据搬迁
This commit is contained in:
parent
ec81f8b3cd
commit
11e7b26ced
1042
backend/app/controller/orderDelivery.js
Normal file
1042
backend/app/controller/orderDelivery.js
Normal file
File diff suppressed because it is too large
Load Diff
249
backend/app/controller/orderDeliveryItem.js
Normal file
249
backend/app/controller/orderDeliveryItem.js
Normal file
@ -0,0 +1,249 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
const { validateItems, buildItemRow } = require('../lib/orderDeliveryItems');
|
||||
const recalcOrderDelivery = require('../utils/recalcOrderDelivery');
|
||||
|
||||
/**
|
||||
* 明细仅在所属发货单处于「待处理(1)」时可增删改;
|
||||
* 单据进入已审核(2) 及之后明细即锁定,避免审核后篡改导致仓库侧对账不一致。
|
||||
* @param {Object} ctx egg context
|
||||
* @param {Number} orderDeliveryId 发货单头ID
|
||||
* @return {Promise<{ok: boolean, order?: Object, message?: string}>} 校验结果(ok=false 时 message 为原因)
|
||||
*/
|
||||
async function assertItemsEditable(ctx, orderDeliveryId) {
|
||||
const order = await ctx.model.OrderDelivery.findByPk(orderDeliveryId);
|
||||
if (!order) return { ok: false, message: '所属发货单不存在' };
|
||||
if (Number(order.status) !== 1) {
|
||||
return { ok: false, message: '发货单已审核或已结束,明细已锁定,不允许增删改' };
|
||||
}
|
||||
return { ok: true, order };
|
||||
}
|
||||
|
||||
/**
|
||||
* @controller OrderDeliveryItemController 发货单明细(子表商品明细)管理
|
||||
* 明细挂在 order_delivery_items 表,通过 order_delivery_id 关联发货单头
|
||||
*/
|
||||
class OrderDeliveryItemController extends Controller {
|
||||
/**
|
||||
* @summary 明细列表
|
||||
* @description 按 order_delivery_id 查询明细(必填),按行号升序返回
|
||||
* @router get /api/order-delivery-items
|
||||
* @apikey
|
||||
* @request query integer order_delivery_id 所属发货单ID(必填)
|
||||
* @request query string item_code 商品编码,支持模糊匹配
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 50
|
||||
* @response 200 orderDeliveryItemListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const { page, pageSize, offset, limit } = parsePagination(ctx.query, { defaultPageSize: 50 });
|
||||
const { order_delivery_id: orderDeliveryId, item_code: itemCode } = ctx.query;
|
||||
|
||||
if (!orderDeliveryId) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'order_delivery_id(所属发货单)为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const where = { order_delivery_id: Number(orderDeliveryId), principal_id: ctx.state.principalId };
|
||||
if (itemCode) where.item_code = { [Op.like]: `%${itemCode}%` };
|
||||
|
||||
const { count, rows } = await ctx.model.OrderDeliveryItem.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit,
|
||||
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 明细详情
|
||||
* @router get /api/order-delivery-items/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 明细主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.OrderDeliveryItem.findByPk(ctx.params.id);
|
||||
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '明细不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: item };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 新增明细
|
||||
* @description 明细可随发货单一次性创建(POST /api/order-deliveries 的 items),也可单独追加;
|
||||
* plan_qty 必须大于 0,actual_price(单价)必填,item_id 与 item_code 至少填写一个
|
||||
* @router post /api/order-delivery-items
|
||||
* @apikey
|
||||
* @request body createOrderDeliveryItemRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const orderDeliveryId = body.order_delivery_id;
|
||||
|
||||
if (!orderDeliveryId) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'order_delivery_id(所属发货单)为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
const editable = await assertItemsEditable(ctx, orderDeliveryId);
|
||||
if (!editable.ok) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: editable.message };
|
||||
return;
|
||||
}
|
||||
|
||||
const invalid = validateItems([ body ]);
|
||||
if (!invalid.ok) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: invalid.message };
|
||||
return;
|
||||
}
|
||||
|
||||
const existLine = await ctx.model.OrderDeliveryItem.findOne({
|
||||
where: { order_delivery_id: Number(orderDeliveryId), order_line_no: String(body.order_line_no == null || body.order_line_no === '' ? 1 : body.order_line_no) },
|
||||
});
|
||||
if (existLine) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该发货单下明细行号已存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const item = await ctx.model.OrderDeliveryItem.create(buildItemRow(body, {
|
||||
principalId: editable.order.principal_id,
|
||||
orderDeliveryId: Number(orderDeliveryId),
|
||||
lineIndex: 0,
|
||||
}));
|
||||
|
||||
// 主表商品总数/种类数随之重算
|
||||
await recalcOrderDelivery(ctx, item.order_delivery_id);
|
||||
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 更新明细
|
||||
* @description 未传入的字段保持原值;明细仅在发货单「待处理(1)」时可修改
|
||||
* @router put /api/order-delivery-items/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 明细主键ID
|
||||
* @request body updateOrderDeliveryItemRequest *body
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.OrderDeliveryItem.findByPk(ctx.params.id);
|
||||
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '明细不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const editable = await assertItemsEditable(ctx, item.order_delivery_id);
|
||||
if (!editable.ok) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: editable.message };
|
||||
return;
|
||||
}
|
||||
|
||||
const body = { ...(ctx.request.body || {}) };
|
||||
delete body.order_delivery_id;
|
||||
delete body.principal_id;
|
||||
|
||||
if (body.plan_qty !== undefined && !(Number(body.plan_qty) > 0)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'plan_qty(计划数量)必须大于 0' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 单价为必填项:显式传空(null / 空串)视为非法,未传则保持原值
|
||||
if (body.actual_price !== undefined) {
|
||||
const price = body.actual_price;
|
||||
if (price == null || String(price).trim() === '' || !(Number(price) >= 0)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'actual_price(单价)必须为不小于 0 的数字' };
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 行号变更时校验同单据内不重复(有唯一索引兜底,这里提前给出友好提示)
|
||||
if (body.order_line_no !== undefined && String(body.order_line_no) !== String(item.order_line_no)) {
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const dup = await ctx.model.OrderDeliveryItem.findOne({
|
||||
where: {
|
||||
order_delivery_id: item.order_delivery_id,
|
||||
order_line_no: String(body.order_line_no),
|
||||
id: { [Op.ne]: item.id },
|
||||
},
|
||||
});
|
||||
if (dup) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '该发货单下明细行号已存在' };
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const row = buildItemRow({ ...item.get({ plain: true }), ...body }, {
|
||||
principalId: item.principal_id,
|
||||
orderDeliveryId: item.order_delivery_id,
|
||||
lineIndex: 0,
|
||||
});
|
||||
delete row.principal_id;
|
||||
delete row.order_delivery_id;
|
||||
delete row.created_at;
|
||||
|
||||
await item.update(row);
|
||||
await recalcOrderDelivery(ctx, item.order_delivery_id);
|
||||
ctx.body = { code: 0, message: 'success', data: { id: item.id } };
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary 删除明细
|
||||
* @description 物理删除;明细仅在发货单「待处理(1)」时可删除
|
||||
* @router delete /api/order-delivery-items/{id}
|
||||
* @apikey
|
||||
* @request path integer *id 明细主键ID
|
||||
* @response 200 baseResponse success
|
||||
*/
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const item = await ctx.model.OrderDeliveryItem.findByPk(ctx.params.id);
|
||||
|
||||
if (!item) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, message: '明细不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
const editable = await assertItemsEditable(ctx, item.order_delivery_id);
|
||||
if (!editable.ok) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: editable.message };
|
||||
return;
|
||||
}
|
||||
|
||||
const orderDeliveryId = item.order_delivery_id;
|
||||
await item.destroy();
|
||||
await recalcOrderDelivery(ctx, orderDeliveryId);
|
||||
ctx.body = { code: 0, message: 'success' };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderDeliveryItemController;
|
||||
96
backend/app/lib/orderDeliveryItems.js
Normal file
96
backend/app/lib/orderDeliveryItems.js
Normal file
@ -0,0 +1,96 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单明细(order_delivery_items)公共字段口径与校验
|
||||
*
|
||||
* 对应奇门 `deliveryorder.create` 的 `request.orderLines.orderLine`,
|
||||
* 字段口径对齐 WMS 明细落库结构(D:\wms\app\service\systems\delivery_order.js#addOrderLines):
|
||||
* - plan_qty 必须 > 0(WMS:`数量必须大于0`)
|
||||
* - actual_price 必填且不小于 0(手工创建发货单时单价由人工填写)
|
||||
* - item_id / item_code 至少一个(WMS:itemId 主键查不到时降级按 itemCode)
|
||||
* - order_line_no 缺省按行序号(WMS:`${lineIndex + 1}`)
|
||||
* - inventory_type:OMS 落 ZP 正品 / CC 残次,推送 WMS 时映射 ZC / CC
|
||||
*/
|
||||
|
||||
/** 库存类型:OMS 落 ZP 正品 / CC 残次(推送 WMS 时映射 ZC/CC) */
|
||||
const INVENTORY_TYPES = [ 'ZP', 'CC' ];
|
||||
|
||||
/**
|
||||
* 校验明细数组:plan_qty 必须 > 0、actual_price 必填、item_id/item_code 至少一个、行号不重复
|
||||
* @param {Array} items 明细数组
|
||||
* @return {{ok: boolean, message?: string}} 校验结果
|
||||
*/
|
||||
function validateItems(items) {
|
||||
const seenLineNos = new Set();
|
||||
const list = Array.isArray(items) ? items : [];
|
||||
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const item = list[i] || {};
|
||||
|
||||
const planQty = Number(item.plan_qty == null ? 0 : item.plan_qty);
|
||||
if (!(planQty > 0)) {
|
||||
return { ok: false, message: `第${i + 1}行:plan_qty(计划数量)必须大于 0` };
|
||||
}
|
||||
|
||||
const hasItemId = item.item_id != null && item.item_id !== '';
|
||||
const hasItemCode = item.item_code != null && String(item.item_code).trim() !== '';
|
||||
if (!hasItemId && !hasItemCode) {
|
||||
return { ok: false, message: `第${i + 1}行:item_id 与 item_code 至少填写一个` };
|
||||
}
|
||||
|
||||
const price = item.actual_price;
|
||||
if (price == null || String(price).trim() === '') {
|
||||
return { ok: false, message: `第${i + 1}行:actual_price(单价)为必填项` };
|
||||
}
|
||||
if (!(Number(price) >= 0)) {
|
||||
return { ok: false, message: `第${i + 1}行:actual_price(单价)必须为不小于 0 的数字` };
|
||||
}
|
||||
|
||||
const inventoryType = item.inventory_type == null ? '' : String(item.inventory_type).trim().toUpperCase();
|
||||
if (inventoryType && !INVENTORY_TYPES.includes(inventoryType)) {
|
||||
return { ok: false, message: `第${i + 1}行:inventory_type 仅支持 ${INVENTORY_TYPES.join(' / ')}` };
|
||||
}
|
||||
|
||||
const lineNo = String(item.order_line_no == null || item.order_line_no === '' ? i + 1 : item.order_line_no);
|
||||
if (seenLineNos.has(lineNo)) {
|
||||
return { ok: false, message: `第${i + 1}行:order_line_no(${lineNo})重复` };
|
||||
}
|
||||
seenLineNos.add(lineNo);
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化单条明细为可直接入库的行数据
|
||||
* @param {Object} raw 明细原始数据(请求体或明细实例)
|
||||
* @param {Object} opts { principalId, orderDeliveryId, lineIndex }
|
||||
* @return {Object} 行数据
|
||||
*/
|
||||
function buildItemRow(raw, opts = {}) {
|
||||
const body = raw || {};
|
||||
const inventoryType = String(body.inventory_type || '').trim().toUpperCase();
|
||||
const lineIndex = Number(opts.lineIndex) || 0;
|
||||
|
||||
return {
|
||||
principal_id: opts.principalId,
|
||||
order_delivery_id: opts.orderDeliveryId,
|
||||
order_line_no: String(body.order_line_no == null || body.order_line_no === '' ? lineIndex + 1 : body.order_line_no),
|
||||
item_id: body.item_id == null || body.item_id === '' ? null : Number(body.item_id),
|
||||
item_code: body.item_code == null ? null : String(body.item_code).trim(),
|
||||
item_name: body.item_name == null ? null : String(body.item_name).trim(),
|
||||
plan_qty: Number(body.plan_qty == null ? 0 : body.plan_qty),
|
||||
actual_price: body.actual_price == null || body.actual_price === '' ? null : Number(body.actual_price),
|
||||
retail_price: body.retail_price == null || body.retail_price === '' ? null : Number(body.retail_price),
|
||||
ext_code: body.ext_code == null ? null : String(body.ext_code).trim(),
|
||||
// 非 CC 一律落 ZP(正品),与出入库明细 inventory_type 口径一致
|
||||
inventory_type: inventoryType === 'CC' ? 'CC' : 'ZP',
|
||||
owner_code: body.owner_code == null ? null : String(body.owner_code).trim(),
|
||||
source_order_code: body.source_order_code == null ? null : String(body.source_order_code).trim(),
|
||||
sub_source_order_code: body.sub_source_order_code == null ? null : String(body.sub_source_order_code).trim(),
|
||||
stock_id: body.stock_id == null || body.stock_id === '' ? null : Number(body.stock_id),
|
||||
extend_props: body.extend_props == null || body.extend_props === '' ? null : body.extend_props,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { INVENTORY_TYPES, validateItems, buildItemRow };
|
||||
133
backend/app/model/orderDelivery.js
Normal file
133
backend/app/model/orderDelivery.js
Normal file
@ -0,0 +1,133 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单(订单)模型,对应 order_deliveries 表(独立于出库单 outbound_orders)
|
||||
*
|
||||
* 字段口径对齐 WMS `wms_order_delivery` 与奇门 `deliveryorder.create` 的
|
||||
* request.deliveryOrder + receiverInfo(receiverInfo 在 WMS 侧扁平落主表,此处同样扁平):
|
||||
* - delivery_order_code ↔ deliveryOrderCode(必填,去重键的一部分)
|
||||
* - order_type ↔ orderType、operator_name ↔ operatorName
|
||||
* - need_oms_waybill ↔ needOmsWaybill:OMS 走 WMS openapi,WMS 侧按通道自行写入创建渠道(API),OMS 不落该字段
|
||||
* - createTime 不落库(WMS 显式忽略),本地用 created_at
|
||||
* - sourceOrderCode 不单独落列,仅作 pay_no 缺省回退;多来源用 source_order_codes
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderDelivery model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DECIMAL, INTEGER, TEXT, JSON, ENUM, DATE } = app.Sequelize;
|
||||
|
||||
const OrderDelivery = app.model.define('order_delivery', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
|
||||
// ---------- OMS 归属与键 ----------
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(货主,对应 WMS store_id)' },
|
||||
// 历史数据来源:orders.id(仅搬迁数据有值,正常新建为 NULL)
|
||||
legacy_order_id: { type: BIGINT.UNSIGNED, comment: '历史数据来源:orders.id(非搬迁数据为 NULL)' },
|
||||
warehouse_id: { type: BIGINT.UNSIGNED, comment: '仓库ID(关联 warehouses,对应 WMS warehouse_id)' },
|
||||
shop_id: { type: BIGINT.UNSIGNED, comment: '店铺ID(关联 shops)' },
|
||||
warehouse_code: { type: STRING(50), comment: '仓库编码(报文 warehouseCode 快照)' },
|
||||
|
||||
// ---------- 主键 / 类型 / 标记 ----------
|
||||
delivery_order_code: { type: STRING(50), allowNull: false, comment: '发货单号(必填,唯一去重键)' },
|
||||
order_type: {
|
||||
type: STRING(50),
|
||||
defaultValue: 'JYCK',
|
||||
comment: '订单类型(ORDER 组 WMS 编码):JYCK 一般交易出库单 / HHCK 换货出库 / BFCK 补发出库,默认 JYCK',
|
||||
},
|
||||
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: '支付单号(缺省回退取 sourceOrderCode)' },
|
||||
operate_time: { type: DATE, comment: 'ERP 审核时间' },
|
||||
|
||||
// ---------- 金额 ----------
|
||||
total_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '订单总金额' },
|
||||
item_amount: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '商品总金额(Σ 明细 plan_qty × actual_price,明细增删改后自动重算)' },
|
||||
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: '运单号(面单号)' },
|
||||
logistics_area_code: { type: STRING(50), comment: '快递区域编码(大头笔信息)' },
|
||||
|
||||
// ---------- 操作人 / 其他 ----------
|
||||
operator_name: { type: STRING(50), comment: 'ERP 审核人(奇门 operatorName)' },
|
||||
oaid_order_source_code: { type: STRING(50), comment: 'OAID 订单来源编码' },
|
||||
source_order_codes: { type: TEXT, comment: '来源订单号集合(对齐 WMS 列名 source_order_codes)' },
|
||||
extend_props: { type: JSON, comment: '请求级扩展属性(如 ewaybill_order_code)' },
|
||||
|
||||
// ---------- 渠道 / 取号 ----------
|
||||
need_oms_waybill: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否需要回 OMS 取号:0不需要 1需要(OMS 走 WMS openapi,渠道由 WMS 侧写入 API,该开关即生效)',
|
||||
},
|
||||
|
||||
// ---------- 收件人(奇门 receiverInfo 扁平落库,列名与 WMS 一致) ----------
|
||||
name: { type: STRING(100), comment: '收件人姓名(receiverInfo.name)' },
|
||||
tel: { type: STRING(50), comment: '收件人电话(receiverInfo.tel)' },
|
||||
mobile: { type: STRING(50), comment: '收件人移动电话(receiverInfo.mobile)' },
|
||||
email: { type: STRING(100), comment: '收件人邮箱(receiverInfo.email)' },
|
||||
country_code: { type: STRING(50), comment: '国家编码(receiverInfo.countryCode)' },
|
||||
province: { type: STRING(100), comment: '省份(receiverInfo.province)' },
|
||||
city: { type: STRING(100), comment: '城市(receiverInfo.city)' },
|
||||
area: { type: STRING(100), comment: '区县(receiverInfo.area)' },
|
||||
town: { type: STRING(100), comment: '街道/镇(receiverInfo.town)' },
|
||||
detail_address: { type: STRING(500), comment: '详细地址(receiverInfo.detailAddress)' },
|
||||
zip_code: { type: STRING(20), comment: '邮编(receiverInfo.zipCode)' },
|
||||
oaid: { type: STRING(100), comment: 'OAID(receiverInfo.oaid)' },
|
||||
|
||||
// ---------- OMS 站内字段:统计 / 状态流转 / 推送记录 ----------
|
||||
item_total: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '商品总数(明细计划数量合计)' },
|
||||
item_kind: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '商品种类数(不重复商品数)' },
|
||||
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1待处理 2已审核 3已推送 4已完成 5已作废 9已取消' },
|
||||
audit_by: { type: BIGINT.UNSIGNED, comment: '审核人ID(关联 users,待处理→已审核时写入)' },
|
||||
audit_time: { type: DATE, comment: '审核时间' },
|
||||
void_at: { type: DATE, comment: '作废时间(状态 5=已作废)' },
|
||||
void_by: { type: BIGINT.UNSIGNED, comment: '作废人ID(关联 users)' },
|
||||
void_reason: { type: STRING(255), comment: '作废原因' },
|
||||
created_by: { type: BIGINT.UNSIGNED, comment: '创建人ID(关联 users)' },
|
||||
pushed_at: { type: DATE, comment: 'WMS 推送时间' },
|
||||
wms_push_result: { type: JSON, comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)' },
|
||||
|
||||
created_at: { type: DATE, comment: '创建时间(对应 WMS create_at,取服务器时间)' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: 'order_deliveries',
|
||||
comment: '发货单(订单)表',
|
||||
});
|
||||
|
||||
OrderDelivery.associate = () => {
|
||||
app.model.OrderDelivery.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
app.model.OrderDelivery.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' });
|
||||
app.model.OrderDelivery.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' });
|
||||
app.model.OrderDelivery.belongsTo(app.model.User, { foreignKey: 'created_by', as: 'creator' });
|
||||
app.model.OrderDelivery.belongsTo(app.model.User, { foreignKey: 'audit_by', as: 'auditor' });
|
||||
app.model.OrderDelivery.belongsTo(app.model.User, { foreignKey: 'void_by', as: 'voider' });
|
||||
app.model.OrderDelivery.hasMany(app.model.OrderDeliveryItem, { foreignKey: 'order_delivery_id', as: 'items' });
|
||||
};
|
||||
|
||||
return OrderDelivery;
|
||||
};
|
||||
53
backend/app/model/orderDeliveryItem.js
Normal file
53
backend/app/model/orderDeliveryItem.js
Normal file
@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单明细模型(子表商品明细),对应 order_delivery_items 表
|
||||
*
|
||||
* 字段口径对齐奇门 `request.orderLines.orderLine` 与 WMS 侧明细落库结构(见迁移注释):
|
||||
* - plan_qty 必须 > 0;item_id / item_code 至少一个
|
||||
* - order_line_no 缺省按行序号;inventory_type OMS 落 ZP/CC(推送时映射 ZC/CC)
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} orderDeliveryItem model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DECIMAL, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const OrderDeliveryItem = app.model.define('order_delivery_item', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
order_delivery_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属发货单ID(order_deliveries.id)' },
|
||||
// 历史数据来源:order_items.id(仅搬迁数据有值)
|
||||
legacy_order_item_id: { type: BIGINT.UNSIGNED, comment: '历史数据来源:order_items.id(非搬迁数据为 NULL)' },
|
||||
order_line_no: { type: STRING(20), allowNull: false, defaultValue: '', comment: '行号(orderLineNo,缺省按行序号)' },
|
||||
item_id: { type: BIGINT.UNSIGNED, comment: 'WMS 内部商品ID(itemId,取自 warehouse_products.wms_item_id)' },
|
||||
item_code: { type: STRING(100), comment: '商品编码(itemCode)' },
|
||||
item_name: { type: STRING(255), comment: '商品名称(itemName)' },
|
||||
plan_qty: { type: DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '计划数量(planQty,必须 > 0)' },
|
||||
actual_price: { type: DECIMAL(12, 2), comment: '实际单价(actualPrice)' },
|
||||
retail_price: { type: DECIMAL(12, 2), comment: '零售价(retailPrice)' },
|
||||
ext_code: { type: STRING(100), comment: '外部编码(extCode)' },
|
||||
inventory_type: {
|
||||
type: STRING(10),
|
||||
allowNull: false,
|
||||
defaultValue: 'ZP',
|
||||
comment: '库存类型:ZP=正品 CC=残次(对齐 WMS 行级 inventoryType,推送时映射 ZC/CC)',
|
||||
},
|
||||
owner_code: { type: STRING(50), comment: '货主编码(ownerCode)' },
|
||||
source_order_code: { type: STRING(50), comment: '来源订单编码(sourceOrderCode)' },
|
||||
sub_source_order_code: { type: STRING(50), comment: '子来源订单编码(subSourceOrderCode)' },
|
||||
stock_id: { type: BIGINT.UNSIGNED, comment: 'WMS 仓库库存ID(stockId,手工建单直传)' },
|
||||
extend_props: { type: JSON, comment: '扩展属性(extendProps)' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
}, {
|
||||
tableName: 'order_delivery_items',
|
||||
comment: '发货单明细(子表商品明细)',
|
||||
});
|
||||
|
||||
OrderDeliveryItem.associate = () => {
|
||||
app.model.OrderDeliveryItem.belongsTo(app.model.OrderDelivery, { foreignKey: 'order_delivery_id', as: 'order' });
|
||||
app.model.OrderDeliveryItem.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return OrderDeliveryItem;
|
||||
};
|
||||
34
backend/app/schedule/orderDeliveryPush.js
Normal file
34
backend/app/schedule/orderDeliveryPush.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单推送队列:每 30 秒扫描「已审核(2)」的单据并递交 WMS(deliveryorder.create)
|
||||
*
|
||||
* 说明:
|
||||
* - 审核只入队(1→2),由本定时任务异步推送,避免集中审核时把对方服务打满
|
||||
* - 单条失败处理见 app/service/orderDeliveryPush.js:对方明确失败立即退回「待审核(1)」;
|
||||
* 无响应/超时最多尝试 3 次(每次间隔 >= 20s),仍未成功同样退回「待审核(1)」
|
||||
* - 并发安全:服务层用 pushed_at 做乐观锁抢占,多 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.orderDeliveryPush.processPending();
|
||||
if (stat.scanned > 0) {
|
||||
ctx.logger.info(
|
||||
`[delivery-push] 本轮扫描 ${stat.scanned} 条:成功 ${stat.pushed},失败 ${stat.failed},待重试 ${stat.retry},跳过 ${stat.skipped}`
|
||||
);
|
||||
}
|
||||
return stat;
|
||||
},
|
||||
};
|
||||
167
backend/app/service/ai.js
Normal file
167
backend/app/service/ai.js
Normal file
@ -0,0 +1,167 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/** DeepSeek 调用参数:与 WMS inbox/ai.js 保持一致(推理模型需要足够的 max_tokens) */
|
||||
const DEEPSEEK_MODEL = 'deepseek-v4-pro';
|
||||
const DEEPSEEK_TIMEOUT = 30000;
|
||||
const DEEPSEEK_MAX_TOKENS = 3000;
|
||||
|
||||
/** 收件人字段白名单与长度上限(与 order_deliveries 列长对齐,避免超长写入失败) */
|
||||
const RECEIVER_FIELD_LIMITS = {
|
||||
name: 100,
|
||||
tel: 50,
|
||||
mobile: 50,
|
||||
email: 100,
|
||||
country_code: 50,
|
||||
province: 100,
|
||||
city: 100,
|
||||
area: 100,
|
||||
town: 100,
|
||||
detail_address: 500,
|
||||
zip_code: 20,
|
||||
};
|
||||
|
||||
/** 系统提示词:只做抽取,输出纯 JSON(与 WMS 的 JSON 输出约定一致) */
|
||||
const RECEIVER_SYSTEM_PROMPT = [
|
||||
'你是收件人信息抽取助手。从用户提供的文本中提取收件人信息,只输出一个 JSON 对象,不要任何解释或多余文字。',
|
||||
'JSON 字段固定为:name(收件人姓名)、tel(固定电话)、mobile(手机号)、province(省)、city(市)、area(区/县)、town(街道/镇)、',
|
||||
'detail_address(详细地址)、zip_code(邮编)、email(邮箱)。',
|
||||
'规则:',
|
||||
'1) 无法确定的字段返回空字符串,不要编造;',
|
||||
'2) 11 位手机号放 mobile;带区号的固话放 tel;两者都有时都要填;',
|
||||
'3) province/city/area 保留“省/市/区/县”字样,逐级拆分(如“浙江省杭州市西湖区”);',
|
||||
'4) detail_address 只保留街道门牌等详细部分,不要重复省市县;',
|
||||
'5) 只输出 JSON 对象,不要使用 markdown 代码块。',
|
||||
].join('\n');
|
||||
|
||||
/**
|
||||
* AI 服务:当前用于「收件人信息智能识别」
|
||||
* 调用方式与 WMS 保持一致(DeepSeek 兼容的 /v1/chat/completions + 配置项 config.deepseek)
|
||||
*/
|
||||
class AiService extends Service {
|
||||
/**
|
||||
* 从一段自由文本中抽取收件人信息
|
||||
* @param {string} text 用户粘贴的文本(如「张三 13800138000 浙江省杭州市西湖区文三路100号」)
|
||||
* @return {Promise<Object>} 结构化收件人字段(未识别到的字段为空串)
|
||||
*/
|
||||
async parseReceiver(text) {
|
||||
const content = String(text == null ? '' : text).trim();
|
||||
if (!content) throw new Error('待识别的文本不能为空');
|
||||
if (content.length > 2000) throw new Error('待识别的文本过长(最多 2000 字)');
|
||||
|
||||
const raw = await this._chat([
|
||||
{ role: 'system', content: RECEIVER_SYSTEM_PROMPT },
|
||||
{ role: 'user', content },
|
||||
]);
|
||||
|
||||
const parsed = this._extractJson(raw);
|
||||
if (!parsed || typeof parsed !== 'object') {
|
||||
throw new Error('AI 返回内容无法解析为收件人信息,请调整文本后重试');
|
||||
}
|
||||
|
||||
return this._normalizeReceiver(parsed);
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用 DeepSeek 兼容接口(与 WMS inbox/ai.js 的 callDeepSeek 同口径)
|
||||
* @param {Array<{role: string, content: string}>} messages 消息列表
|
||||
* @param {Object} [options] { temperature, maxTokens, timeout }
|
||||
* @return {Promise<string>} 模型返回的文本内容
|
||||
*/
|
||||
async _chat(messages, options = {}) {
|
||||
const { ctx } = this;
|
||||
const apiKey = ctx.app.config.deepseek.apiKey;
|
||||
const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com';
|
||||
|
||||
if (!apiKey) {
|
||||
const err = new Error('DeepSeek API Key 未配置(请在 .env 中设置 DEEPSEEK_API_KEY),无法使用智能识别');
|
||||
err.code = 'AI_NOT_CONFIGURED';
|
||||
throw err;
|
||||
}
|
||||
|
||||
const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
dataType: 'json',
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
data: {
|
||||
model: DEEPSEEK_MODEL,
|
||||
messages,
|
||||
temperature: options.temperature == null ? 0 : options.temperature,
|
||||
max_tokens: options.maxTokens || DEEPSEEK_MAX_TOKENS,
|
||||
},
|
||||
timeout: options.timeout || DEEPSEEK_TIMEOUT,
|
||||
});
|
||||
|
||||
if (result.status !== 200 || !result.data) {
|
||||
const message = result.data && result.data.error && result.data.error.message;
|
||||
throw new Error(`AI 请求失败(HTTP ${result.status})${message ? `:${message}` : ''}`);
|
||||
}
|
||||
|
||||
const choice = (result.data.choices && result.data.choices[0]) || {};
|
||||
const text = (choice.message && choice.message.content) || '';
|
||||
if (!text.trim()) {
|
||||
// 推理模型会把 max_tokens 消耗在推理过程上,导致 content 为空
|
||||
if (choice.finish_reason === 'length') {
|
||||
throw new Error('AI 输出被截断(max_tokens 被推理过程占满),请重试');
|
||||
}
|
||||
throw new Error('AI 未返回内容,请稍后重试或调整文本');
|
||||
}
|
||||
return this._stripCodeFence(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去掉 markdown 代码块包裹(```json ... ```)
|
||||
* @param {string} text 模型原始输出
|
||||
* @return {string} 清理后的文本
|
||||
*/
|
||||
_stripCodeFence(text) {
|
||||
return String(text || '')
|
||||
.replace(/^```json\s*/i, '')
|
||||
.replace(/^```\s*/i, '')
|
||||
.replace(/\s*```$/i, '')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从模型输出中提取 JSON 对象(容忍前后有解释文字)
|
||||
* @param {string} text 模型输出
|
||||
* @return {Object|null} 解析结果
|
||||
*/
|
||||
_extractJson(text) {
|
||||
const cleaned = this._stripCodeFence(text);
|
||||
try {
|
||||
return JSON.parse(cleaned);
|
||||
} catch {
|
||||
// 兜底:截取首个 { 到末个 } 之间的内容
|
||||
const start = cleaned.indexOf('{');
|
||||
const end = cleaned.lastIndexOf('}');
|
||||
if (start >= 0 && end > start) {
|
||||
try {
|
||||
return JSON.parse(cleaned.slice(start, end + 1));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化模型输出:仅保留白名单字段、去空白、按列长截断
|
||||
* @param {Object} data 模型输出的 JSON
|
||||
* @return {Object} 规范化后的收件人字段
|
||||
*/
|
||||
_normalizeReceiver(data) {
|
||||
const result = {};
|
||||
for (const [ key, limit ] of Object.entries(RECEIVER_FIELD_LIMITS)) {
|
||||
const value = data[key];
|
||||
const text = value == null ? '' : String(value).trim();
|
||||
result[key] = text.length > limit ? text.slice(0, limit) : text;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AiService;
|
||||
348
backend/app/service/orderDeliveryPush.js
Normal file
348
backend/app/service/orderDeliveryPush.js
Normal file
@ -0,0 +1,348 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||||
|
||||
/** 单条单据最多推送尝试次数(无响应/超时才算一次可重试的失败;对方明确响应失败不重试) */
|
||||
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_deliveries.status):
|
||||
* - 审核(1→2):仅入队,不推送
|
||||
* - 推送成功(2→3):写 pushed_at / wms_push_result
|
||||
* - 对方服务明确响应失败:判定推送失败,退回「待审核(1)」并记录原因
|
||||
* - 无响应/超时/网络异常:保留「已审核(2)」等待下次重试,最多 3 次;达到 3 次仍失败同样退回「待审核(1)」
|
||||
*
|
||||
* 并发防重:用 pushed_at 做乐观锁(CAS)抢占单据,多 worker 下同一单只会被一个进程推送一次
|
||||
*/
|
||||
class OrderDeliveryPushService 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<{byProduct: Object, byItemCode: Object}>} 两种键的映射(未推送到该仓库的商品不会出现)
|
||||
*/
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取上次推送记录(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 : {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载待推送单据(含仓库)
|
||||
* @param {number|string} id 发货单ID
|
||||
* @return {Promise<Object|null>} 发货单实例
|
||||
*/
|
||||
async loadOrder(id) {
|
||||
return this.ctx.model.OrderDelivery.findByPk(id, {
|
||||
include: [{ model: this.ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送单条发货单(一次尝试)
|
||||
*
|
||||
* 返回 ok=false 时:
|
||||
* - retry=true :无响应/超时,单据保留「已审核(2)」,等下次定时任务重试
|
||||
* - retry=false:对方明确失败或已达重试上限,单据已退回「待审核(1)」
|
||||
* @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, message: '发货单不存在' };
|
||||
if (Number(order.status) !== 2) {
|
||||
return { ok: false, skipped: true, message: `当前状态不可推送(status=${order.status})` };
|
||||
}
|
||||
if (!(Number(order.warehouse_id) > 0)) {
|
||||
return { ok: false, skipped: true, message: '单据未指定仓库,无法推送' };
|
||||
}
|
||||
|
||||
const api = await this.findWarehouseApi(order);
|
||||
if (!api) {
|
||||
return {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
message: `仓库「${order.warehouse ? `${order.warehouse.name}(${order.warehouse.code})` : `#${order.warehouse_id}`}」未配置启用中的类奇门接口`,
|
||||
};
|
||||
}
|
||||
|
||||
// 乐观锁抢占:多 worker / 并发请求下同一单只推一次(同时把本次尝试时间写入 pushed_at)
|
||||
const now = new Date();
|
||||
const throttleBefore = new Date(now.getTime() - PUSH_THROTTLE_MS);
|
||||
const [ claimed ] = await ctx.model.OrderDelivery.update(
|
||||
{ pushed_at: now },
|
||||
{
|
||||
where: {
|
||||
id: order.id,
|
||||
status: 2,
|
||||
[Op.or]: [
|
||||
{ pushed_at: null },
|
||||
{ pushed_at: { [Op.lt]: throttleBefore } },
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
if (!claimed) {
|
||||
return { ok: false, skipped: true, message: '该单据正在推送或处于重试间隔内,已跳过' };
|
||||
}
|
||||
|
||||
const prev = this._prevResult(order);
|
||||
const attempts = Number(prev.attempts || 0) + 1;
|
||||
const base = {
|
||||
deliveryOrderCode: order.delivery_order_code,
|
||||
warehouseApiId: api.id,
|
||||
apiType: api.type,
|
||||
attempts,
|
||||
maxAttempts: PUSH_MAX_ATTEMPTS,
|
||||
source,
|
||||
attemptedAt: now.toISOString(),
|
||||
};
|
||||
|
||||
const items = await ctx.model.OrderDeliveryItem.findAll({
|
||||
where: { order_delivery_id: order.id },
|
||||
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
if (!items.length) {
|
||||
await order.update({
|
||||
wms_push_result: { ...base, success: false, failureKind: 'empty_items', message: '单据无明细,无法推送' },
|
||||
});
|
||||
return { ok: false, retry: false, message: '单据无明细,无法推送', attempts };
|
||||
}
|
||||
|
||||
const client = new QimenWmsClient(api, this.app);
|
||||
const wmsItemIds = await this.resolveWmsItemIds(order, items);
|
||||
|
||||
let resp;
|
||||
try {
|
||||
resp = await client.createDeliveryOrder(order, items, {
|
||||
warehouse: order.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(`[delivery-push] ${order.delivery_order_code} 第 ${attempts}/${PUSH_MAX_ATTEMPTS} 次推送异常(将重试):${err.message}`);
|
||||
return { ok: false, retry: true, message: err.message, attempts };
|
||||
}
|
||||
// 达到上限:冲正外部单据后退回「待审核(1)」
|
||||
const cancelResult = await this.cancelRemote(client, order);
|
||||
await order.update({
|
||||
status: 1,
|
||||
audit_by: null,
|
||||
audit_time: null,
|
||||
wms_push_result: {
|
||||
...base,
|
||||
success: false,
|
||||
failureKind: 'timeout',
|
||||
retryable: false,
|
||||
error: err.message,
|
||||
cancelResult,
|
||||
},
|
||||
});
|
||||
ctx.logger.error(`[delivery-push] ${order.delivery_order_code} 连续 ${attempts} 次推送异常,已退回待审核:${err.message}`);
|
||||
return { ok: false, retry: false, message: `连续 ${attempts} 次无响应/超时,已退回待审核:${err.message}`, attempts };
|
||||
}
|
||||
|
||||
if (client.isSuccess(resp)) {
|
||||
await order.update({
|
||||
status: 3,
|
||||
pushed_at: now,
|
||||
operate_time: now,
|
||||
wms_push_result: { ...base, success: true, response: resp },
|
||||
});
|
||||
ctx.logger.info(`[delivery-push] ${order.delivery_order_code} 推送成功(第 ${attempts} 次)`);
|
||||
return { ok: true, message: '已推送仓库', response: resp, attempts };
|
||||
}
|
||||
|
||||
// 对方明确响应失败:不重试,冲正后退回「待审核(1)」
|
||||
const cancelResult = await this.cancelRemote(client, order);
|
||||
const message = resp && (resp.message || resp.code);
|
||||
await order.update({
|
||||
status: 1,
|
||||
audit_by: null,
|
||||
audit_time: null,
|
||||
wms_push_result: {
|
||||
...base,
|
||||
success: false,
|
||||
failureKind: 'business',
|
||||
retryable: false,
|
||||
code: resp && resp.code,
|
||||
message,
|
||||
response: resp,
|
||||
cancelResult,
|
||||
},
|
||||
});
|
||||
ctx.logger.warn(`[delivery-push] ${order.delivery_order_code} 推送失败(对方明确拒绝),已退回待审核:${message}`);
|
||||
return { ok: false, retry: false, message: `WMS 返回失败:${message}`, response: resp, attempts };
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描「已审核(2)」的单据并推送(定时任务入口)
|
||||
* @param {Object} [options] { limit }
|
||||
* @return {Promise<{scanned: number, pushed: number, failed: number, retry: number, skipped: number}>}
|
||||
*/
|
||||
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.OrderDelivery.findAll({
|
||||
where: {
|
||||
status: 2,
|
||||
warehouse_id: { [Op.ne]: null },
|
||||
[Op.or]: [
|
||||
{ pushed_at: null },
|
||||
{ pushed_at: { [Op.lt]: throttleBefore } },
|
||||
],
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
// pushed_at 为 NULL(从未尝试)优先,其次按尝试时间升序
|
||||
order: [[ 'pushed_at', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
limit,
|
||||
});
|
||||
|
||||
const stat = { scanned: orders.length, pushed: 0, failed: 0, retry: 0, skipped: 0 };
|
||||
for (const row of orders) {
|
||||
const res = await this.pushOne(row.id, { source: 'schedule' });
|
||||
if (res.ok) stat.pushed++;
|
||||
else if (res.skipped) stat.skipped++;
|
||||
else if (res.retry) stat.retry++;
|
||||
else stat.failed++;
|
||||
}
|
||||
return stat;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量推送指定ID列表(限流顺序执行)
|
||||
* @param {number[]} ids 发货单ID列表
|
||||
* @param {Object} [options] { limit, gap }
|
||||
* @return {Promise<{requested: number, processed: number, pendingRest: number, pushed: number, failed: number, retry: number, skipped: number, details: Array}>}
|
||||
*/
|
||||
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,
|
||||
details: [],
|
||||
};
|
||||
|
||||
for (let i = 0; i < targets.length; i++) {
|
||||
const id = targets[i];
|
||||
const res = await this.pushOne(id, { source: 'batch' });
|
||||
if (res.ok) result.pushed++;
|
||||
else if (res.skipped) result.skipped++;
|
||||
else if (res.retry) result.retry++;
|
||||
else result.failed++;
|
||||
|
||||
result.details.push({
|
||||
id: Number(id),
|
||||
ok: res.ok,
|
||||
skipped: !!res.skipped,
|
||||
retry: !!res.retry,
|
||||
message: res.message,
|
||||
});
|
||||
|
||||
if (gap > 0 && i < targets.length - 1) {
|
||||
await new Promise(resolve => setTimeout(resolve, gap));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderDeliveryPushService;
|
||||
37
backend/app/utils/recalcOrderDelivery.js
Normal file
37
backend/app/utils/recalcOrderDelivery.js
Normal file
@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 重算发货单头的商品总数、商品种类数与商品总金额(明细增删改后回写)
|
||||
* 商品总数 = 所有明细 plan_qty 之和;商品种类数 = 不重复商品数;
|
||||
* 商品总金额 = Σ(plan_qty × actual_price)(实际单价,即明细成交金额合计)
|
||||
* 种类判定优先级:item_id(WMS 内部商品ID)> item_code > 明细主键(无法识别商品时按行计)
|
||||
* @param {Egg.Context} ctx egg context(含 model)
|
||||
* @param {number} orderDeliveryId 发货单头ID
|
||||
*/
|
||||
module.exports = async function recalcOrderDelivery(ctx, orderDeliveryId) {
|
||||
const items = await ctx.model.OrderDeliveryItem.findAll({
|
||||
where: { order_delivery_id: orderDeliveryId },
|
||||
attributes: [ 'id', 'item_id', 'item_code', 'plan_qty', 'actual_price' ],
|
||||
});
|
||||
|
||||
let itemTotal = 0;
|
||||
let itemAmount = 0;
|
||||
const kinds = new Set();
|
||||
for (const it of items) {
|
||||
const qty = Number(it.plan_qty || 0);
|
||||
itemTotal += qty;
|
||||
itemAmount += qty * Number(it.actual_price || 0);
|
||||
if (it.item_id) kinds.add(`w${it.item_id}`);
|
||||
else if (it.item_code) kinds.add(`c${it.item_code}`);
|
||||
else kinds.add(`i${it.id}`);
|
||||
}
|
||||
|
||||
await ctx.model.OrderDelivery.update(
|
||||
{
|
||||
item_total: itemTotal,
|
||||
item_kind: kinds.size,
|
||||
item_amount: Number(itemAmount.toFixed(2)),
|
||||
},
|
||||
{ where: { id: orderDeliveryId } }
|
||||
);
|
||||
};
|
||||
@ -0,0 +1,183 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单(订单)表:order_deliveries
|
||||
*
|
||||
* 定位:独立于出库单(outbound_orders)的一张发货单/订单主表,字段口径对齐
|
||||
* WMS 侧 `wms_order_delivery`(模型 D:\wms\app\model\order_delivery.js)
|
||||
* 与奇门 `deliveryorder.create` 的 request.deliveryOrder + request.deliveryOrder.receiverInfo
|
||||
* 落库映射 D:\wms\app\service\systems\delivery_order.js#prepareOrderData
|
||||
*
|
||||
* 口径要点(与 WMS 保持一致,勿改):
|
||||
* - deliveryOrderCode → delivery_order_code,必填;去重键对齐 WMS 的三元唯一
|
||||
* (delivery_order_code, store_id, warehouse_id),OMS 侧为 (delivery_order_code, principal_id, warehouse_id)
|
||||
* - 奇门 camelCase 字段一律 snake_case 落库(WMS 同名):order_flag / pre_delivery_order_code /
|
||||
* pre_delivery_order_id / is_urgency / invoice_flag / source_platform_code / source_platform_name /
|
||||
* shop_nick / seller_nick / buyer_nick / buyer_message / seller_message / place_order_time / pay_time /
|
||||
* pay_no / operate_time / operator_name / total_amount / item_amount / discount_amount / freight /
|
||||
* ar_amount / got_amount / logistics_code / express_code / logistics_area_code /
|
||||
* oaid_order_source_code / create_channel / need_oms_waybill / extend_props
|
||||
* - receiverInfo 在 WMS 侧是**扁平落主表**(不单独建表),此处同样扁平为 12 列,列名与 WMS 相同
|
||||
* - createTime **不落库**(WMS 显式忽略,取服务器时间),OMS 用 created_at
|
||||
* - sourceOrderCode 不单独落 WMS 的 source_order_code,仅作 pay_no 缺省回退;
|
||||
* 东侧多来源场景用 source_order_codes(对齐 WMS 列名)存来源订单号集合
|
||||
* - create_channel:MANUAL 人工 / QM 奇门 / API 开放接口(OMS 调用 WMS openapi 时即 API)
|
||||
* - need_oms_waybill:仅 createChannel=API 时生效,其余渠道恒 0
|
||||
*
|
||||
* OMS 自有字段:principal_id(货主,对应 WMS store_id)、warehouse_id、shop_id、warehouse_code
|
||||
* 快照、status、created_by、pushed_at、wms_push_result(对齐出入库单的推送记录口径)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'order_deliveries',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, autoIncrement: true, primaryKey: true },
|
||||
|
||||
// ---------- OMS 归属与键 ----------
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID(货主,对应 WMS store_id)',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库ID(关联 warehouses,对应 WMS warehouse_id)',
|
||||
references: { model: 'warehouses', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
shop_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '店铺ID(关联 shops)',
|
||||
references: { model: 'shops', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
warehouse_code: { type: Sequelize.STRING(50), allowNull: true, comment: '仓库编码(报文 warehouseCode 快照)' },
|
||||
|
||||
// ---------- 主键 / 类型 / 标记 ----------
|
||||
delivery_order_code: { type: Sequelize.STRING(50), allowNull: false, comment: '发货单号(必填,唯一去重键)' },
|
||||
order_type: { type: Sequelize.STRING(50), allowNull: true, comment: '订单类型(WMS 编码,如 JYCK/HHCK/BFCK/PTCK...)' },
|
||||
order_flag: { type: Sequelize.TEXT, allowNull: true, comment: '订单标记' },
|
||||
pre_delivery_order_code: { type: Sequelize.STRING(50), allowNull: true, comment: '预发货单号' },
|
||||
pre_delivery_order_id: { type: Sequelize.STRING(50), allowNull: true, comment: '预发货单ID' },
|
||||
is_urgency: { type: Sequelize.ENUM('Y', 'N'), allowNull: true, defaultValue: 'N', comment: '是否紧急:Y是 N否(默认 N)' },
|
||||
invoice_flag: { type: Sequelize.ENUM('Y', 'N'), allowNull: true, defaultValue: 'N', comment: '是否需要发票:Y是 N否(默认 N)' },
|
||||
|
||||
// ---------- 平台 / 店铺 ----------
|
||||
source_platform_code: { type: Sequelize.STRING(50), allowNull: true, comment: '来源平台编码' },
|
||||
source_platform_name: { type: Sequelize.STRING(200), allowNull: true, comment: '来源平台名称' },
|
||||
shop_nick: { type: Sequelize.STRING(200), allowNull: true, comment: '店铺名称' },
|
||||
seller_nick: { type: Sequelize.STRING(200), allowNull: true, comment: '卖家名称' },
|
||||
buyer_nick: { type: Sequelize.STRING(200), allowNull: true, comment: '买家名称' },
|
||||
|
||||
// ---------- 留言 / 备注 ----------
|
||||
buyer_message: { type: Sequelize.STRING(500), allowNull: true, comment: '买家留言' },
|
||||
seller_message: { type: Sequelize.STRING(500), allowNull: true, comment: '卖家留言' },
|
||||
remark: { type: Sequelize.STRING(500), allowNull: true, comment: '备注' },
|
||||
|
||||
// ---------- 时间(createTime 被 WMS 显式忽略,此处不设列) ----------
|
||||
place_order_time: { type: Sequelize.DATE, allowNull: true, comment: '店铺创建订单时间' },
|
||||
pay_time: { type: Sequelize.DATE, allowNull: true, comment: '支付时间' },
|
||||
pay_no: { type: Sequelize.STRING(50), allowNull: true, comment: '支付单号(缺省回退取 sourceOrderCode)' },
|
||||
operate_time: { type: Sequelize.DATE, allowNull: true, comment: 'ERP 审核时间' },
|
||||
|
||||
// ---------- 金额 ----------
|
||||
total_amount: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '订单总金额' },
|
||||
item_amount: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '商品总金额' },
|
||||
discount_amount: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '订单折扣金额' },
|
||||
freight: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '快递费用' },
|
||||
ar_amount: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '应收金额' },
|
||||
got_amount: { type: Sequelize.DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '已收金额' },
|
||||
|
||||
// ---------- 快递 ----------
|
||||
logistics_code: { type: Sequelize.STRING(50), allowNull: true, comment: '物流公司编码(WMS 标准编码,如 SF/YTO)' },
|
||||
logistics_name: { type: Sequelize.STRING(200), allowNull: true, comment: '物流公司名称' },
|
||||
express_code: { type: Sequelize.STRING(50), allowNull: true, comment: '运单号(面单号)' },
|
||||
logistics_area_code: { type: Sequelize.STRING(50), allowNull: true, comment: '快递区域编码(大头笔信息)' },
|
||||
|
||||
// ---------- 操作人 / 其他 ----------
|
||||
operator_name: { type: Sequelize.STRING(50), allowNull: true, comment: 'ERP 审核人(奇门 operatorName)' },
|
||||
oaid_order_source_code: { type: Sequelize.STRING(50), allowNull: true, comment: 'OAID 订单来源编码' },
|
||||
source_order_codes: { type: Sequelize.TEXT, allowNull: true, comment: '来源订单号集合(对齐 WMS 列名 source_order_codes)' },
|
||||
extend_props: { type: Sequelize.JSON, allowNull: true, comment: '请求级扩展属性(如 ewaybill_order_code)' },
|
||||
|
||||
// ---------- 渠道 / 取号 ----------
|
||||
create_channel: {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'MANUAL',
|
||||
comment: '创建渠道:MANUAL 人工 / QM 奇门 / API 开放接口',
|
||||
},
|
||||
need_oms_waybill: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否需要回 OMS 取号:0不需要 1需要(仅 create_channel=API 生效)',
|
||||
},
|
||||
|
||||
// ---------- 收件人(奇门 receiverInfo 扁平落库,列名与 WMS 一致) ----------
|
||||
name: { type: Sequelize.STRING(100), allowNull: true, comment: '收件人姓名(receiverInfo.name)' },
|
||||
tel: { type: Sequelize.STRING(50), allowNull: true, comment: '收件人电话(receiverInfo.tel)' },
|
||||
mobile: { type: Sequelize.STRING(50), allowNull: true, comment: '收件人移动电话(receiverInfo.mobile)' },
|
||||
email: { type: Sequelize.STRING(100), allowNull: true, comment: '收件人邮箱(receiverInfo.email)' },
|
||||
country_code: { type: Sequelize.STRING(50), allowNull: true, comment: '国家编码(receiverInfo.countryCode)' },
|
||||
province: { type: Sequelize.STRING(100), allowNull: true, comment: '省份(receiverInfo.province)' },
|
||||
city: { type: Sequelize.STRING(100), allowNull: true, comment: '城市(receiverInfo.city)' },
|
||||
area: { type: Sequelize.STRING(100), allowNull: true, comment: '区县(receiverInfo.area)' },
|
||||
town: { type: Sequelize.STRING(100), allowNull: true, comment: '街道/镇(receiverInfo.town)' },
|
||||
detail_address: { type: Sequelize.STRING(500), allowNull: true, comment: '详细地址(receiverInfo.detailAddress)' },
|
||||
zip_code: { type: Sequelize.STRING(20), allowNull: true, comment: '邮编(receiverInfo.zipCode)' },
|
||||
oaid: { type: Sequelize.STRING(100), allowNull: true, comment: 'OAID(receiverInfo.oaid)' },
|
||||
|
||||
// ---------- OMS 状态与推送记录 ----------
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:1待处理 2已审核 3已推送 4已完成 5已作废 9已取消',
|
||||
},
|
||||
created_by: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '创建人ID(关联 users)',
|
||||
references: { model: 'users', key: 'id' },
|
||||
onDelete: 'SET NULL',
|
||||
},
|
||||
pushed_at: { type: Sequelize.DATE, allowNull: true, comment: 'WMS 推送时间' },
|
||||
wms_push_result: { type: Sequelize.JSON, allowNull: true, comment: 'WMS 推送结果(外部单号/返回码/消息/原始报文)' },
|
||||
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间(对应 WMS create_at,取服务器时间)',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '发货单(订单)表' }
|
||||
);
|
||||
|
||||
// 去重键:对齐 WMS (delivery_order_code, store_id, warehouse_id) 唯一索引
|
||||
await queryInterface.addIndex('order_deliveries', {
|
||||
fields: [ 'delivery_order_code', 'principal_id', 'warehouse_id' ],
|
||||
unique: true,
|
||||
name: 'uk_order_deliveries_code',
|
||||
});
|
||||
await queryInterface.addIndex('order_deliveries', { fields: [ 'principal_id' ], name: 'idx_order_deliveries_principal' });
|
||||
await queryInterface.addIndex('order_deliveries', { fields: [ 'warehouse_id' ], name: 'idx_order_deliveries_warehouse' });
|
||||
await queryInterface.addIndex('order_deliveries', { fields: [ 'shop_id' ], name: 'idx_order_deliveries_shop' });
|
||||
await queryInterface.addIndex('order_deliveries', { fields: [ 'status' ], name: 'idx_order_deliveries_status' });
|
||||
await queryInterface.addIndex('order_deliveries', { fields: [ 'place_order_time' ], name: 'idx_order_deliveries_place_time' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('order_deliveries');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单明细子表:order_delivery_items
|
||||
*
|
||||
* 对应奇门 `deliveryorder.create` 的 `request.orderLines.orderLine`(子表商品明细),
|
||||
* 字段口径对齐 WMS 侧明细落库结构
|
||||
* (D:\wms\app\service\systems\delivery_order.js#addOrderLines 的 lineData):
|
||||
* order_line_no / item_id / item_code / item_name / plan_qty / actual_price / retail_price /
|
||||
* ext_code / inventory_type / owner_code / source_order_code / sub_source_order_code /
|
||||
* extend_props / stock_id
|
||||
*
|
||||
* 口径要点(与 WMS 保持一致):
|
||||
* - plan_qty 必须 > 0(WMS 侧 `数量必须大于0`)
|
||||
* - item_id(WMS 内部商品ID,取自 warehouse_products.wms_item_id)与 item_code 至少给一个;
|
||||
* WMS 侧 itemId 主键查不到时会降级按 itemCode 查找
|
||||
* - order_line_no 缺省按行序号(WMS 为 `${lineIndex + 1}`)
|
||||
* - inventory_type:OMS 落 ZP 正品 / CC 残次,推送 WMS 时映射为 ZC / CC
|
||||
* - stock_id:WMS 仓库库存ID(手工建单直传场景,WMS 会校验库存归属货主)
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'order_delivery_items',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, autoIncrement: true, primaryKey: true },
|
||||
principal_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属主体ID',
|
||||
references: { model: 'principals', key: 'id' },
|
||||
},
|
||||
order_delivery_id: {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属发货单ID(order_deliveries.id)',
|
||||
references: { model: 'order_deliveries', key: 'id' },
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
order_line_no: { type: Sequelize.STRING(20), allowNull: false, defaultValue: '', comment: '行号(orderLineNo,缺省按行序号)' },
|
||||
item_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: 'WMS 内部商品ID(itemId,取自 warehouse_products.wms_item_id)' },
|
||||
item_code: { type: Sequelize.STRING(100), allowNull: true, comment: '商品编码(itemCode)' },
|
||||
item_name: { type: Sequelize.STRING(255), allowNull: true, comment: '商品名称(itemName)' },
|
||||
plan_qty: { type: Sequelize.DECIMAL(12, 3), allowNull: false, defaultValue: 0, comment: '计划数量(planQty,必须 > 0)' },
|
||||
actual_price: { type: Sequelize.DECIMAL(12, 2), allowNull: true, comment: '实际单价(actualPrice)' },
|
||||
retail_price: { type: Sequelize.DECIMAL(12, 2), allowNull: true, comment: '零售价(retailPrice)' },
|
||||
ext_code: { type: Sequelize.STRING(100), allowNull: true, comment: '外部编码(extCode)' },
|
||||
inventory_type: {
|
||||
type: Sequelize.STRING(10),
|
||||
allowNull: false,
|
||||
defaultValue: 'ZP',
|
||||
comment: '库存类型:ZP=正品 CC=残次(对齐 WMS 行级 inventoryType,推送时映射 ZC/CC)',
|
||||
},
|
||||
owner_code: { type: Sequelize.STRING(50), allowNull: true, comment: '货主编码(ownerCode)' },
|
||||
source_order_code: { type: Sequelize.STRING(50), allowNull: true, comment: '来源订单编码(sourceOrderCode)' },
|
||||
sub_source_order_code: { type: Sequelize.STRING(50), allowNull: true, comment: '子来源订单编码(subSourceOrderCode)' },
|
||||
stock_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: 'WMS 仓库库存ID(stockId,手工建单直传)' },
|
||||
extend_props: { type: Sequelize.JSON, allowNull: true, comment: '扩展属性(extendProps)' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '发货单明细(子表商品明细)' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('order_delivery_items', { fields: [ 'order_delivery_id' ], name: 'idx_od_items_order' });
|
||||
await queryInterface.addIndex('order_delivery_items', { fields: [ 'principal_id' ], name: 'idx_od_items_principal' });
|
||||
await queryInterface.addIndex('order_delivery_items', { fields: [ 'item_code' ], name: 'idx_od_items_item_code' });
|
||||
// 同一发货单内行号唯一,避免明细重复或覆盖
|
||||
await queryInterface.addIndex('order_delivery_items', {
|
||||
fields: [ 'order_delivery_id', 'order_line_no' ],
|
||||
unique: true,
|
||||
name: 'uk_od_items_line',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('order_delivery_items');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单表补充「历史数据来源」列:
|
||||
* - order_deliveries.legacy_order_id 来源 orders.id(仅历史搬迁数据有值,正常新建为 NULL)
|
||||
* - order_delivery_items.legacy_order_item_id 来源 order_items.id
|
||||
*
|
||||
* 用途:
|
||||
* 1) 数据搬迁幂等:INSERT ... WHERE NOT EXISTS (legacy_*_id = ...) 可重复执行不产生重复数据;
|
||||
* 2) 可精确回滚:迁移 down() 只删 legacy_* 非空的行,不误删迁移后新建的单据;
|
||||
* 3) 可追溯:历史单据仍能反查原 orders / order_items 记录(原表保留启用,不删除)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const headerCols = await queryInterface.describeTable('order_deliveries');
|
||||
if (!headerCols.legacy_order_id) {
|
||||
await queryInterface.addColumn('order_deliveries', 'legacy_order_id', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '历史数据来源:orders.id(非搬迁数据为 NULL)',
|
||||
});
|
||||
await queryInterface.addIndex('order_deliveries', {
|
||||
fields: [ 'legacy_order_id' ],
|
||||
unique: true,
|
||||
name: 'uk_order_deliveries_legacy',
|
||||
});
|
||||
}
|
||||
|
||||
const itemCols = await queryInterface.describeTable('order_delivery_items');
|
||||
if (!itemCols.legacy_order_item_id) {
|
||||
await queryInterface.addColumn('order_delivery_items', 'legacy_order_item_id', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '历史数据来源:order_items.id(非搬迁数据为 NULL)',
|
||||
});
|
||||
await queryInterface.addIndex('order_delivery_items', {
|
||||
fields: [ 'legacy_order_item_id' ],
|
||||
unique: true,
|
||||
name: 'uk_od_items_legacy',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const itemCols = await queryInterface.describeTable('order_delivery_items');
|
||||
if (itemCols.legacy_order_item_id) {
|
||||
await queryInterface.removeIndex('order_delivery_items', 'uk_od_items_legacy').catch(() => {});
|
||||
await queryInterface.removeColumn('order_delivery_items', 'legacy_order_item_id');
|
||||
}
|
||||
|
||||
const headerCols = await queryInterface.describeTable('order_deliveries');
|
||||
if (headerCols.legacy_order_id) {
|
||||
await queryInterface.removeIndex('order_deliveries', 'uk_order_deliveries_legacy').catch(() => {});
|
||||
await queryInterface.removeColumn('order_deliveries', 'legacy_order_id');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,110 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 历史订单数据搬迁:orders / order_items → order_deliveries / order_delivery_items
|
||||
*
|
||||
* 背景:原「订单表」(orders + order_items) 继续保留启用(不删不改),
|
||||
* 本次把存量数据「转入」新的发货单表,供「订单」菜单对应的页面直接读写新表。
|
||||
*
|
||||
* 幂等:依赖 legacy_order_id / legacy_order_item_id 判重(见 20260915000200 迁移),
|
||||
* 重复执行不会产生重复数据,也不会覆盖搬迁后新建/编辑过的行。
|
||||
* 回滚:只删除 legacy_* 非空的行,不影响迁移后新建的单据。
|
||||
*
|
||||
* 字段映射(无法确定的语义一律不做猜测,原表保留可回溯):
|
||||
* orders → order_deliveries
|
||||
* order_no → delivery_order_code
|
||||
* principal_id / shop_id → principal_id / shop_id
|
||||
* order_type(TINYINT,内部数字枚举) → 'JYCK'(一般交易出库单,历史来源无类型语义,按默认归档)
|
||||
* total_amount / pay_amount → total_amount / got_amount(实付金额 → 已收金额)
|
||||
* receiver{name,phone,address} → name / mobile / detail_address(扁平列,口径同 WMS receiverInfo)
|
||||
* status → status:1→1 待处理,2→2 已审核,3→4 已完成,4→9 已取消,其它→1
|
||||
* 注:备注(remark)已从 order_deliveries 移除(见 20260915000900),历史备注不回迁,原表保留可回湖
|
||||
* created_at / updated_at → created_at / updated_at
|
||||
* 不搬迁(原表保留,可回溯):wms_status / wms_order_no / wms_synced_at / submit_*
|
||||
*
|
||||
* order_items → order_delivery_items
|
||||
* sku_code(商家编码) → item_code(对齐 WMS itemCode)
|
||||
* name → item_name
|
||||
* quantity / price → plan_qty / actual_price
|
||||
* outer_item_id(平台商品ID) → ext_code(外部编码 extCode)
|
||||
* order_line_no → 按订单内 order_items.id 升序生成行号(同 WMS `${lineIndex + 1}`)
|
||||
* inventory_type → 'ZP'(历史明细无残次标记)
|
||||
* 不搬迁:outer_sku_id / spec / image / parse_* / product_id 等(原表保留)
|
||||
*
|
||||
* 搬迁后按 recalcOrderDelivery 同口径回填统计:item_total(计划数量合计)、
|
||||
* item_amount(Σ 计划数量 × 实际单价)、item_kind(按 item_code 去重的商品种类数)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
const headerSql = `
|
||||
INSERT INTO order_deliveries (
|
||||
legacy_order_id, principal_id, shop_id, delivery_order_code, order_type,
|
||||
is_urgency, invoice_flag, total_amount, got_amount,
|
||||
name, mobile, detail_address,
|
||||
status, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
o.id, o.principal_id, o.shop_id, o.order_no, 'JYCK',
|
||||
'N', 'N', COALESCE(o.total_amount, 0), COALESCE(o.pay_amount, 0),
|
||||
JSON_UNQUOTE(JSON_EXTRACT(o.receiver, '$.name')),
|
||||
JSON_UNQUOTE(JSON_EXTRACT(o.receiver, '$.phone')),
|
||||
JSON_UNQUOTE(JSON_EXTRACT(o.receiver, '$.address')),
|
||||
CASE o.status WHEN 2 THEN 2 WHEN 3 THEN 4 WHEN 4 THEN 9 ELSE 1 END,
|
||||
o.created_at, o.updated_at
|
||||
FROM orders o
|
||||
WHERE NOT EXISTS (SELECT 1 FROM order_deliveries d WHERE d.legacy_order_id = o.id)
|
||||
`;
|
||||
|
||||
const itemSql = `
|
||||
INSERT INTO order_delivery_items (
|
||||
legacy_order_item_id, principal_id, order_delivery_id, order_line_no,
|
||||
item_code, item_name, plan_qty, actual_price, ext_code, inventory_type,
|
||||
created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
oi.id, oi.principal_id, d.id,
|
||||
(SELECT COUNT(*) FROM order_items x WHERE x.order_id = oi.order_id AND x.id <= oi.id),
|
||||
NULLIF(oi.sku_code, ''), oi.name, COALESCE(oi.quantity, 0), oi.price,
|
||||
NULLIF(oi.outer_item_id, ''), 'ZP',
|
||||
oi.created_at, oi.updated_at
|
||||
FROM order_items oi
|
||||
JOIN order_deliveries d ON d.legacy_order_id = oi.order_id
|
||||
WHERE NOT EXISTS (SELECT 1 FROM order_delivery_items t WHERE t.legacy_order_item_id = oi.id)
|
||||
`;
|
||||
|
||||
const statsSql = `
|
||||
UPDATE order_deliveries d
|
||||
JOIN (
|
||||
SELECT
|
||||
order_delivery_id,
|
||||
SUM(plan_qty) AS qty,
|
||||
SUM(plan_qty * COALESCE(actual_price, 0)) AS amount,
|
||||
COUNT(DISTINCT COALESCE(NULLIF(item_code, ''), CONCAT('#', id))) AS kinds
|
||||
FROM order_delivery_items
|
||||
GROUP BY order_delivery_id
|
||||
) t ON t.order_delivery_id = d.id
|
||||
SET
|
||||
d.item_total = t.qty,
|
||||
d.item_amount = ROUND(t.amount, 2),
|
||||
d.item_kind = t.kinds
|
||||
WHERE d.legacy_order_id IS NOT NULL
|
||||
`;
|
||||
|
||||
await sequelize.transaction(async transaction => {
|
||||
await sequelize.query(headerSql, { transaction });
|
||||
await sequelize.query(itemSql, { transaction });
|
||||
// 统计口径与 recalcOrderDelivery 保持一致:商品总数 / 商品总金额(Σ 计划数量 × 实际单价)/ 商品种类数
|
||||
await sequelize.query(statsSql, { transaction });
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
await sequelize.transaction(async transaction => {
|
||||
// 明细先删,避免依赖外键级联的行为差异
|
||||
await sequelize.query('DELETE FROM order_delivery_items WHERE legacy_order_item_id IS NOT NULL', { transaction });
|
||||
await sequelize.query('DELETE FROM order_deliveries WHERE legacy_order_id IS NOT NULL', { transaction });
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,86 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单表补充「站内字段」(OMS 自用,不参与对外报文):
|
||||
* - 统计:item_total 商品总数(明细 plan_qty 合计)、item_kind 商品种类数
|
||||
* —— 对应 WMS 发货单 items_total / items_count,口径对齐出入库单
|
||||
* - 状态流转:
|
||||
* audit_by / audit_time 审核(待处理 1 → 已审核 2)
|
||||
* void_at / void_by / void_reason 作废(已审核 2 → 已作废 5),与出入库单约定一致
|
||||
* - 主体隔离:principal_id / shop_id / warehouse_id 已在建表时具备,此处仅补组合索引
|
||||
* (列表默认按主体 + 状态过滤;warehouse_id/shop_id 的归属校验在控制器实现)
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const cols = await queryInterface.describeTable('order_deliveries');
|
||||
|
||||
if (!cols.item_total) {
|
||||
await queryInterface.addColumn('order_deliveries', 'item_total', {
|
||||
type: Sequelize.DECIMAL(12, 3),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '商品总数(明细计划数量合计)',
|
||||
});
|
||||
}
|
||||
if (!cols.item_kind) {
|
||||
await queryInterface.addColumn('order_deliveries', 'item_kind', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '商品种类数(不重复商品数)',
|
||||
});
|
||||
}
|
||||
if (!cols.audit_by) {
|
||||
await queryInterface.addColumn('order_deliveries', 'audit_by', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '审核人ID(关联 users,状态流转:待处理→已审核时写入)',
|
||||
});
|
||||
}
|
||||
if (!cols.audit_time) {
|
||||
await queryInterface.addColumn('order_deliveries', 'audit_time', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '审核时间',
|
||||
});
|
||||
}
|
||||
if (!cols.void_at) {
|
||||
await queryInterface.addColumn('order_deliveries', 'void_at', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '作废时间(状态 5=已作废)',
|
||||
});
|
||||
}
|
||||
if (!cols.void_by) {
|
||||
await queryInterface.addColumn('order_deliveries', 'void_by', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '作废人ID(关联 users)',
|
||||
});
|
||||
}
|
||||
if (!cols.void_reason) {
|
||||
await queryInterface.addColumn('order_deliveries', 'void_reason', {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '作废原因',
|
||||
});
|
||||
}
|
||||
|
||||
const indexes = await queryInterface.showIndex('order_deliveries').catch(() => []);
|
||||
const hasIndex = name => Array.isArray(indexes) && indexes.some(idx => idx.name === name);
|
||||
if (!hasIndex('idx_od_principal_status')) {
|
||||
await queryInterface.addIndex('order_deliveries', {
|
||||
fields: [ 'principal_id', 'status' ],
|
||||
name: 'idx_od_principal_status',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const cols = await queryInterface.describeTable('order_deliveries');
|
||||
for (const c of [ 'void_reason', 'void_by', 'void_at', 'audit_time', 'audit_by', 'item_kind', 'item_total' ]) {
|
||||
if (cols[c]) await queryInterface.removeColumn('order_deliveries', c);
|
||||
}
|
||||
await queryInterface.removeIndex('order_deliveries', 'idx_od_principal_status').catch(() => {});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 移除发货单的「创建渠道」字段(order_deliveries.create_channel)
|
||||
*
|
||||
* 原因:该字段是 WMS 侧自己的口径 —— WMS 按调用通道自动写入
|
||||
* - 奇门通道固定 'QM'
|
||||
* - openapi 通道固定 'API'
|
||||
* OMS 一律通过 WMS openapi 调用,渠道由 WMS 侧落库,OMS 保存无意义,故整体移除。
|
||||
*
|
||||
* 连带影响(已同步代码):
|
||||
* - `need_oms_waybill` 不再按渠道判断(OMS 即 API 通道,WMS 侧该开关即生效)
|
||||
* - 历史搬迁迁移 20260915000300 的 INSERT 列表已同步去掉该列,保证可重复执行
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const cols = await queryInterface.describeTable('order_deliveries');
|
||||
if (cols.create_channel) {
|
||||
await queryInterface.removeColumn('order_deliveries', 'create_channel');
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
const cols = await queryInterface.describeTable('order_deliveries');
|
||||
if (!cols.create_channel) {
|
||||
await queryInterface.addColumn('order_deliveries', 'create_channel', {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'MANUAL',
|
||||
comment: '创建渠道:MANUAL 人工 / QM 奇门 / API 开放接口(已废弃,渠道由 WMS 侧写入)',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 发货单「订单类型」(order_deliveries.order_type)改为 ORDER 组枚举并设默认值:
|
||||
* JYCK 一般交易出库单(默认) / HHCK 换货出库 / BFCK 补发出库
|
||||
*
|
||||
* 口径依据(D:\wms\methods):
|
||||
* - qimen.json `order.cancel`:ORDER 组(JYCK/HHCK/BFCK)取消发货单(wms_order_delivery)
|
||||
* - openapi `order.cancel`:orderType 默认 JYCK(一般交易出库单)
|
||||
* 注:PTCK/DBCK/B2BCK/QTCK/CGTH 属 CK 组出库单(wms_order_stockout),不是发货单类型,此处不收。
|
||||
*
|
||||
* 历史搬迁数据的 order_type 原为 digits(orders.order_type 内部数字枚举,语义不明),
|
||||
* 迁移 20260915000300 已统一按默认 JYCK 归档(该列现收窄为上述 3 值)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const cols = await queryInterface.describeTable('order_deliveries');
|
||||
if (cols.order_type) {
|
||||
await queryInterface.changeColumn('order_deliveries', 'order_type', {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
defaultValue: 'JYCK',
|
||||
comment: '订单类型(ORDER 组 WMS 编码):JYCK 一般交易出库单 / HHCK 换货出库 / BFCK 补发出库,默认 JYCK',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
const cols = await queryInterface.describeTable('order_deliveries');
|
||||
if (cols.order_type) {
|
||||
await queryInterface.changeColumn('order_deliveries', 'order_type', {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '订单类型(WMS 编码,如 JYCK/HHCK/BFCK/PTCK...)',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 快递公司字典表:express_companies
|
||||
*
|
||||
* 定位:通用字典(**不区分主体**,与 menus / warehouse-api-fields 同类),
|
||||
* 供发货单等单据选择「物流公司」,避免手输编码。
|
||||
*
|
||||
* 编码口径:`code` 使用行业通用/WMS `express_code` 标准编码(如 SF/YTO/ZTO),
|
||||
* WMS 侧 `wms_order_delivery.logistics_code` 接收同口径编码,再由其策略漏斗解析快递接口。
|
||||
*
|
||||
* 注:WMS 侧字典表为 `wms_express`(字段含各平台编码 KS/PDD/DY/CAINIAO...),
|
||||
* 当前本地 WMS 库未建该表,故 OMS 侧先以常用快递种子维护,后续如需可与 WMS 对齐/同步。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable(
|
||||
'express_companies',
|
||||
{
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, autoIncrement: true, primaryKey: true },
|
||||
code: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: false,
|
||||
comment: '快递公司编码(行业/WMS 标准编码,如 SF/YTO/ZTO)',
|
||||
},
|
||||
name: { type: Sequelize.STRING(100), allowNull: false, comment: '快递公司名称(如 顺丰速运)' },
|
||||
status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
sort: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '排序(下拉展示顺序,越小越靠前)' },
|
||||
remark: { type: Sequelize.STRING(255), allowNull: true, comment: '备注' },
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
},
|
||||
},
|
||||
{ charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '快递公司字典' }
|
||||
);
|
||||
|
||||
await queryInterface.addIndex('express_companies', {
|
||||
fields: [ 'code' ],
|
||||
unique: true,
|
||||
name: 'uk_express_companies_code',
|
||||
});
|
||||
await queryInterface.addIndex('express_companies', { fields: [ 'status', 'sort' ], name: 'idx_express_companies_status_sort' });
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('express_companies');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 快递公司字典种子数据:常用快递公司与编码
|
||||
*
|
||||
* 幂等:依赖唯一索引 uk_express_companies_code + ignoreDuplicates(INSERT IGNORE),
|
||||
* 已存在的编码不会被覆盖(便于后续人工调整名称/排序/启用状态)。
|
||||
*
|
||||
* 编码口径:采用行业通用短码(与 WMS express_code 同口径)。
|
||||
* 如需扩展:直接通过接口/后台新增,无需改迁移。
|
||||
*/
|
||||
const EXPRESS_COMPANIES = [
|
||||
{ code: 'SF', name: '顺丰速运', sort: 10 },
|
||||
{ code: 'JD', name: '京东物流', sort: 20 },
|
||||
{ code: 'YTO', name: '圆通速递', sort: 30 },
|
||||
{ code: 'ZTO', name: '中通快递', sort: 40 },
|
||||
{ code: 'STO', name: '申通快递', sort: 50 },
|
||||
{ code: 'YD', name: '韵达速递', sort: 60 },
|
||||
{ code: 'JT', name: '极兔速递', sort: 70 },
|
||||
{ code: 'EMS', name: '中国邮政EMS', sort: 80 },
|
||||
{ code: 'YZPY', name: '邮政快递包裹', sort: 90 },
|
||||
{ code: 'DBL', name: '德邦快递', sort: 100 },
|
||||
{ code: 'HTKY', name: '百世快递', sort: 110 },
|
||||
{ code: 'ZJS', name: '宅急送', sort: 120 },
|
||||
];
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const now = new Date();
|
||||
await queryInterface.bulkInsert(
|
||||
'express_companies',
|
||||
EXPRESS_COMPANIES.map(c => ({
|
||||
code: c.code,
|
||||
name: c.name,
|
||||
sort: c.sort,
|
||||
status: 1,
|
||||
remark: null,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
})),
|
||||
{ ignoreDuplicates: true }
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.bulkDelete('express_companies', {
|
||||
code: { [Sequelize.Op.in]: EXPRESS_COMPANIES.map(c => c.code) },
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 从发货单表移除「备注」字段(order_deliveries.remark)
|
||||
*
|
||||
* 原因:手工单只需一个留言字段,统一写入 `seller_message`(奇门 sellerMessage/卖家留言),
|
||||
* 备注不再维护,故整列移除。历史搬迁数据中的原 orders.remark 不再回迁(原表保留可回溯)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const cols = await queryInterface.describeTable('order_deliveries');
|
||||
if (cols.remark) {
|
||||
await queryInterface.removeColumn('order_deliveries', 'remark');
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
const cols = await queryInterface.describeTable('order_deliveries');
|
||||
if (!cols.remark) {
|
||||
await queryInterface.addColumn('order_deliveries', 'remark', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注(已废弃:留言统一写 seller_message)',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,65 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 新增「创建发货单」菜单:挂在「订单管理」目录下,指向独立创建页 views/Order/Create.vue
|
||||
*
|
||||
* 背景:创建发货单改为独立整页(订单信息 + 商品明细内联,不再使用弹窗),
|
||||
* 便于与「订单」列表页区分。菜单按 name + parent_id 判重,可重复执行。
|
||||
*/
|
||||
const PARENT_NAME = '订单管理';
|
||||
const MENU = {
|
||||
name: '创建发货单',
|
||||
type: 2,
|
||||
path: '/order-create',
|
||||
icon: 'Plus',
|
||||
permission: 'orderDelivery:create',
|
||||
component: 'views/Order/Create.vue',
|
||||
sort: 80,
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
|
||||
const [ parent ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE name = ? AND parent_id = 0 LIMIT 1',
|
||||
{ replacements: [ PARENT_NAME ], type: sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (!parent) {
|
||||
// 父菜单不存在(异常数据)时跳过,避免挂错层级
|
||||
return;
|
||||
}
|
||||
const parentId = Number(parent.id);
|
||||
|
||||
const [ exist ] = await sequelize.query(
|
||||
'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1',
|
||||
{ replacements: [ MENU.name, parentId ], 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: [
|
||||
parentId,
|
||||
MENU.name,
|
||||
MENU.type,
|
||||
MENU.path,
|
||||
MENU.icon,
|
||||
MENU.permission,
|
||||
MENU.component,
|
||||
MENU.sort,
|
||||
],
|
||||
}
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const sequelize = queryInterface.sequelize;
|
||||
await sequelize.query('DELETE FROM menus WHERE name = ? AND path = ?', {
|
||||
replacements: [ MENU.name, MENU.path ],
|
||||
});
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user