From 11e7b26ced32e8f4c0ebd0810382a1b29c22e88a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 13 Sep 2026 02:23:47 +0800 Subject: [PATCH] =?UTF-8?q?feat(backend):=20=E5=8F=91=E8=B4=A7=E5=8D=95?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E4=B8=8E=20WMS=20=E5=AE=9A=E6=97=B6=E6=8E=A8?= =?UTF-8?q?=E9=80=81=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 发货单主表/明细表(order_deliveries / order_delivery_items)控制器与模型 - 表头金额与明细派生字段重算(utils/recalcOrderDelivery.js) - 状态流转:审核/驳回/取消/恢复/作废、批量审核、批量切换仓库 - 审核入队 + 定时推送:service/orderDeliveryPush.js(乐观锁 CAS 防重、失败重试上限 3 次、业务失败退回待审核)+ schedule/orderDeliveryPush.js - 收件人 AI 智能识别(service/ai.js,DeepSeek) - 相关迁移:建表、站内字段、明细表、订单类型默认值、快递字典、菜单种子、历史数据搬迁 --- backend/app/controller/orderDelivery.js | 1042 +++++++++++++++++ backend/app/controller/orderDeliveryItem.js | 249 ++++ backend/app/lib/orderDeliveryItems.js | 96 ++ backend/app/model/orderDelivery.js | 133 +++ backend/app/model/orderDeliveryItem.js | 53 + backend/app/schedule/orderDeliveryPush.js | 34 + backend/app/service/ai.js | 167 +++ backend/app/service/orderDeliveryPush.js | 348 ++++++ backend/app/utils/recalcOrderDelivery.js | 37 + .../20260915000000-create-order-deliveries.js | 183 +++ ...60915000100-create-order-delivery-items.js | 87 ++ ...15000200-order-deliveries-legacy-source.js | 57 + ...0300-migrate-orders-to-order-deliveries.js | 110 ++ ...5000400-order-deliveries-station-fields.js | 86 ++ ...op-create-channel-from-order-deliveries.js | 34 + .../20260915000600-order-type-default-enum.js | 38 + ...20260915000700-create-express-companies.js | 55 + .../20260915000800-seed-express-companies.js | 50 + ...00900-drop-remark-from-order-deliveries.js | 27 + .../20260915001000-seed-order-create-menu.js | 65 + 20 files changed, 2951 insertions(+) create mode 100644 backend/app/controller/orderDelivery.js create mode 100644 backend/app/controller/orderDeliveryItem.js create mode 100644 backend/app/lib/orderDeliveryItems.js create mode 100644 backend/app/model/orderDelivery.js create mode 100644 backend/app/model/orderDeliveryItem.js create mode 100644 backend/app/schedule/orderDeliveryPush.js create mode 100644 backend/app/service/ai.js create mode 100644 backend/app/service/orderDeliveryPush.js create mode 100644 backend/app/utils/recalcOrderDelivery.js create mode 100644 backend/database/migrations/20260915000000-create-order-deliveries.js create mode 100644 backend/database/migrations/20260915000100-create-order-delivery-items.js create mode 100644 backend/database/migrations/20260915000200-order-deliveries-legacy-source.js create mode 100644 backend/database/migrations/20260915000300-migrate-orders-to-order-deliveries.js create mode 100644 backend/database/migrations/20260915000400-order-deliveries-station-fields.js create mode 100644 backend/database/migrations/20260915000500-drop-create-channel-from-order-deliveries.js create mode 100644 backend/database/migrations/20260915000600-order-type-default-enum.js create mode 100644 backend/database/migrations/20260915000700-create-express-companies.js create mode 100644 backend/database/migrations/20260915000800-seed-express-companies.js create mode 100644 backend/database/migrations/20260915000900-drop-remark-from-order-deliveries.js create mode 100644 backend/database/migrations/20260915001000-seed-order-create-menu.js diff --git a/backend/app/controller/orderDelivery.js b/backend/app/controller/orderDelivery.js new file mode 100644 index 0000000..0a31b1b --- /dev/null +++ b/backend/app/controller/orderDelivery.js @@ -0,0 +1,1042 @@ +'use strict'; + +const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); +const { validateItems, buildItemRow } = require('../lib/orderDeliveryItems'); +const recalcOrderDelivery = require('../utils/recalcOrderDelivery'); +const QimenWmsClient = require('../lib/wms/qimenClient'); +const { + DELIVERY_ORDER_TYPE_LIST, + DEFAULT_DELIVERY_ORDER_TYPE, + normalizeDeliveryOrderType, +} = require('../lib/wms/orderTypes'); + +/** + * 发货单号前缀:单号一律由系统生成 `FH_{自增id}`,前端与接口均不可传入(对齐入库 RK_/出库 CK_ 约定) + * 注:历史搬迁数据保留原 orders.order_no 作为单号(见 20260915000300 迁移) + */ +const DELIVERY_BILL_PREFIX = 'FH'; + +/** 手工创建订单在扩展字段(extend_props)中写入的标记 */ +const HANDMADE_ORDER_LABEL = '手工单'; + +/** 收件人必填字段(对齐取号硬依赖):姓名 / 省 / 市 / 区 / 镇 */ +const RECEIVER_REQUIRED_FIELDS = [ + [ 'name', '收件人姓名' ], + [ 'province', '省份' ], + [ 'city', '城市' ], + [ 'area', '区县' ], + [ 'town', '街道/镇' ], +]; + +/** + * 收件人信息校验:姓名/省/市/区/镇 必填;电话(tel)与手机(mobile)至少填写一个 + * @param {Object} data 待校验数据(可为记录 + 本次变更合并后的结果) + * @return {string} 错误信息,校验通过返回空串 + */ +function validateReceiver(data) { + const source = data || {}; + for (const [ key, label ] of RECEIVER_REQUIRED_FIELDS) { + const value = source[key] == null ? '' : String(source[key]).trim(); + if (!value) return `收件人信息不完整:${label}为必填项`; + } + const tel = source.tel == null ? '' : String(source.tel).trim(); + const mobile = source.mobile == null ? '' : String(source.mobile).trim(); + if (!tel && !mobile) return '收件人信息不完整:电话(tel)与手机(mobile)至少填写一个'; + return ''; +} + +/** + * 由系统与业务事务推动,禁止通过通用新增/更新接口写入: + * - 单号(delivery_order_code):一律系统生成 FH_{自增id} + * - 状态与推送记录:避免绕过状态机或篡改推送结果 + * - 统计(item_total/item_kind/item_amount):由明细增删改后统一重算(商品总金额由明细金额合计得出) + * - 审核/作废痕迹:只能由 audit / void 接口写入 + * - 取号开关(need_oms_waybill):手工创建的订单恒为 0,该字段留给其他来源订单使用(暂不处理) + * - 运单号(express_code)/ 快递区域编码(logistics_area_code):手工不填写,由取号/快递策略或回写链路服务端写入 + * - 手工单不填写:下单时间(取创建时间)、店铺名称(取所选店铺)、支付单号/支付时间/审核时间、 + * 来源平台/卖家名称/买家名称、买家留言(只保留卖家留言作为「留言」)、预发货单号/ID、订单标记、 + * 来源订单号集合、OAID 来源编码与收件人 OAID、扩展字段 + * (扩展字段由服务端固定写 `labels: "手工单"`) + * (对齐出入库单的 MANAGED_FIELDS 约定) + */ +const MANAGED_FIELDS = [ + 'delivery_order_code', + 'need_oms_waybill', + 'express_code', 'logistics_area_code', + 'status', 'pushed_at', 'wms_push_result', 'created_by', + 'item_total', 'item_kind', 'item_amount', + 'audit_by', 'audit_time', + 'void_at', 'void_by', 'void_reason', + 'place_order_time', 'pay_time', 'pay_no', 'operate_time', + 'shop_nick', 'seller_nick', 'buyer_nick', 'buyer_message', + 'source_platform_code', 'source_platform_name', + 'pre_delivery_order_code', 'pre_delivery_order_id', + 'order_flag', 'source_order_codes', 'oaid_order_source_code', 'oaid', + 'extend_props', +]; + +/** 可编辑明细/单据头的状态:仅「待处理(1)」 */ +const EDITABLE_STATUS = 1; + +/** + * 可切换发货仓库的状态:待处理(1) 与 已审核(2) + * - 已推送(3) / 已完成(4):warehouseCode 已递交 WMS,切换会与仓库侧不一致 + * - 已作废(5) / 已取消(9):切换无业务意义 + */ +const SWITCHABLE_WAREHOUSE_STATUS = [ 1, 2 ]; + +/** + * @controller OrderDeliveryController 发货单(订单)管理 + * 单据头 order_deliveries;字段口径对齐 WMS wms_order_delivery 与奇门 deliveryOrder/receiverInfo + * 推送链路(接口配置、报文映射、重试与定时任务)见 app/service/orderDeliveryPush.js、app/schedule/orderDeliveryPush.js + */ +class OrderDeliveryController extends Controller { + /** + * @summary 发货单列表 + * @description 分页查询发货单,支持按发货单号、状态、订单类型、店铺与仓库过滤 + * @router get /api/order-deliveries + * @apikey + * @request query integer page 页码,默认 1 + * @request query integer pageSize 每页条数,默认 20 + * @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) + * @request query string delivery_order_code 发货单号,支持模糊匹配 + * @request query integer status 状态:1待处理 2已审核 3已推送 4已完成 5已作废 9已取消 + * @request query string order_type 订单类型(ORDER 组枚举):JYCK 一般交易出库单 / HHCK 换货出库 / BFCK 补发出库 + * @request query integer shop_id 店铺ID + * @request query integer warehouse_id 仓库ID + * @response 200 orderDeliveryListResponse success + */ + async index() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const { page, pageSize, offset, limit } = parsePagination(ctx.query); + const { + delivery_order_code: deliveryOrderCode, + status, + order_type: orderType, + shop_id: shopId, + warehouse_id: warehouseId, + } = ctx.query; + const principalId = ctx.state.principalId; + + const where = { principal_id: principalId }; + if (deliveryOrderCode) where.delivery_order_code = { [Op.like]: `%${deliveryOrderCode}%` }; + if (status !== undefined && status !== '') where.status = Number(status); + if (orderType) where.order_type = String(orderType).trim().toUpperCase(); + if (shopId) where.shop_id = Number(shopId); + if (warehouseId) where.warehouse_id = Number(warehouseId); + + const { count, rows } = await ctx.model.OrderDelivery.findAndCountAll({ + where, + offset, + limit, + order: [[ 'id', 'DESC' ]], + include: [ + { model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name' ] }, + { model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }, + { model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] }, + ], + }); + + ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + } + + /** + * @summary 发货单详情 + * @description 按主键查询发货单,含所属主体、店铺、仓库与创建人 + * @router get /api/order-deliveries/{id} + * @apikey + * @request path integer *id 发货单主键ID + * @response 200 baseResponse success + */ + async show() { + const { ctx } = this; + const order = await ctx.model.OrderDelivery.findByPk(ctx.params.id, { + include: [ + { model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name' ] }, + { model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }, + { model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] }, + // 子表商品明细(orderLines),按行号升序 + { model: ctx.model.OrderDeliveryItem, as: 'items', separate: true, order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]] }, + ], + }); + + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + + ctx.body = { code: 0, message: 'success', data: order }; + } + + /** + * @summary 收件人信息智能识别 + * @description 传入一段文本(如从聊天工具复制的姓名/电话/地址),调用 AI 抽取收件人字段并返回; + * 仅返回识别结果不落库,由前端回填表单;未配置 AI 密钥(DEEPSEEK_API_KEY)时返回 400 提示 + * @router post /api/order-deliveries/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) { + ctx.status = 400; + ctx.body = { code: 400, message: err.message || '智能识别失败,请稍后重试' }; + } + } + + /** + * @summary 新增发货单 + * @description 发货单号由系统生成(`FH_{自增id}`),不接受传入; + * 状态由服务端固定为 1(待处理);取号开关 need_oms_waybill 恒为 0(该字段留给其他来源订单,暂不处理); + * 下单时间取创建时间、店铺名称取所选店铺、扩展字段固定写 `labels: 手工单`; + * 收件人必填:姓名/省/市/区/镇,电话与手机至少填一个; + * 仓库必填(推送仓库需要 warehouseCode 与仓库接口配置); + * 仓库/店铺需属于当前主体;items 为子表商品明细(奇门 orderLines),随单在同一事务内创建 + * @router post /api/order-deliveries + * @apikey + * @request body createOrderDeliveryRequest *body + * @response 200 baseResponse success + */ + async create() { + const { ctx } = this; + const body = ctx.request.body || {}; + const principalId = ctx.state.principalId; + + const warehouseId = body.warehouse_id != null && body.warehouse_id !== '' ? Number(body.warehouse_id) : null; + // 仓库必填:推送 WMS 需要 warehouseCode,且仓库接口配置(app_key/base_url)挂在仓库维度 + if (!warehouseId) { + ctx.status = 400; + ctx.body = { code: 400, message: 'warehouse_id(仓库)为必填项:推送仓库需要仓库编码与仓库接口配置' }; + return; + } + + // 订单类型:ORDER 组枚举(JYCK/HHCK/BFCK),非法值拒绝,不传时默认 JYCK(一般交易出库单) + const orderType = normalizeDeliveryOrderType(body.order_type); + if (body.order_type != null && String(body.order_type).trim() !== '' && !orderType) { + ctx.status = 400; + ctx.body = { code: 400, message: `order_type(订单类型)不合法,支持:${DELIVERY_ORDER_TYPE_LIST.join(' / ')}` }; + return; + } + + // 主体隔离:仓库/店铺必须属于当前主体(防止跨主体挂单) + const ownerCheck = await this.assertOwnerBelongsToPrincipal(warehouseId, body.shop_id); + if (!ownerCheck.ok) { + ctx.status = 404; + ctx.body = { code: 404, message: ownerCheck.message }; + return; + } + + // 明细校验:plan_qty 必须 > 0、item_id/item_code 至少一个、行号不重复(对齐 WMS addOrderLines 口径) + const items = Array.isArray(body.items) ? body.items : []; + if (items.length) { + const invalid = validateItems(items); + if (!invalid.ok) { + ctx.status = 400; + ctx.body = { code: 400, message: invalid.message }; + return; + } + } + + const payload = { ...body }; + // 归属主体一律取中间件校验过的 principalId,防止请求体篡改越权 + delete payload.principal_id; + delete payload.items; + // remark 列已删除(见迁移 20260915000900,留言统一写 seller_message) + delete payload.remark; + for (const f of MANAGED_FIELDS) delete payload[f]; + + // 收件人校验:姓名/省/市/区/镇 必填,电话与手机至少填一个 + const receiverError = validateReceiver(payload); + if (receiverError) { + ctx.status = 400; + ctx.body = { code: 400, message: receiverError }; + return; + } + + // 仓库编码快照:未显式传入时按 warehouse_id 取 warehouses.code(推送时使用该编码) + if (warehouseId && !payload.warehouse_code) { + const warehouse = await ctx.model.Warehouse.findByPk(warehouseId, { attributes: [ 'id', 'code' ] }); + if (warehouse) payload.warehouse_code = warehouse.code; + } + + // 店铺名称(shop_nick)取所选店铺名称,无需手工填写 + const shopId = body.shop_id != null && body.shop_id !== '' ? Number(body.shop_id) : null; + let shopNick = null; + if (shopId) { + const shop = await ctx.model.Shop.findByPk(shopId, { attributes: [ 'id', 'name' ] }); + if (shop) shopNick = shop.name; + } + + // 取号开关:手工创建的订单恒为 0(need_oms_waybill 在 MANAGED_FIELDS 中,不接受传入) + + const transaction = await ctx.model.transaction(); + try { + const order = await ctx.model.OrderDelivery.create({ + principal_id: principalId, + status: 1, + order_type: orderType || DEFAULT_DELIVERY_ORDER_TYPE, + need_oms_waybill: 0, + created_by: ctx.userId, + ...payload, + warehouse_id: warehouseId, + // 手工单系统派生字段:店铺名称取所选店铺;下单时间取创建时间;扩展字段固定标记手工单 + shop_nick: shopNick, + place_order_time: new Date(), + extend_props: { labels: HANDMADE_ORDER_LABEL }, + // 单号不接受传入:先用临时号占位,拿到自增 id 后回写 FH_{id} + delivery_order_code: `${DELIVERY_BILL_PREFIX}_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`, + }, { transaction }); + + if (items.length) { + await ctx.model.OrderDeliveryItem.bulkCreate(items.map((item, idx) => buildItemRow(item, { + principalId, + orderDeliveryId: order.id, + lineIndex: idx, + })), { transaction }); + } + + // 系统生成发货单号:FH_{自增id} + await order.update({ delivery_order_code: `${DELIVERY_BILL_PREFIX}_${order.id}` }, { transaction }); + + await transaction.commit(); + // 商品总数/种类数:由明细统一重算(同出入库单口径) + if (items.length) await recalcOrderDelivery(ctx, order.id); + ctx.body = { code: 0, message: 'success', data: { id: order.id, delivery_order_code: order.delivery_order_code } }; + } catch (err) { + await transaction.rollback(); + ctx.status = 500; + ctx.body = { code: 500, message: '新增发货单失败,请稍后重试' }; + } + } + + /** + * @summary 更新发货单 + * @description 未传入的字段保持原值;发货单号与状态/推送记录不可通过本接口修改 + * @router put /api/order-deliveries/{id} + * @apikey + * @request path integer *id 发货单主键ID + * @request body updateOrderDeliveryRequest *body + * @response 200 baseResponse success + */ + async update() { + const { ctx } = this; + const order = await ctx.model.OrderDelivery.findByPk(ctx.params.id); + + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + + const body = { ...(ctx.request.body || {}) }; + delete body.principal_id; + delete body.delivery_order_code; + // remark 列已删除(见迁移 20260915000900) + delete body.remark; + for (const f of MANAGED_FIELDS) delete body[f]; + + // 订单类型:ORDER 组枚举校验(不传则保持原值) + if (body.order_type !== undefined && body.order_type !== null && String(body.order_type).trim() !== '') { + const orderType = normalizeDeliveryOrderType(body.order_type); + if (!orderType) { + ctx.status = 400; + ctx.body = { code: 400, message: `order_type(订单类型)不合法,支持:${DELIVERY_ORDER_TYPE_LIST.join(' / ')}` }; + return; + } + body.order_type = orderType; + } + + // 仅「待处理(1)」可编辑单据头(对齐出入库单的编辑锁定约定) + if (Number(order.status) !== EDITABLE_STATUS) { + ctx.status = 400; + ctx.body = { code: 400, message: '发货单已审核或已结束,不允许编辑' }; + return; + } + + // 主体隔离:仓库/店铺必须属于当前主体 + const ownerCheck = await this.assertOwnerBelongsToPrincipal( + body.warehouse_id === undefined ? order.warehouse_id : body.warehouse_id, + body.shop_id === undefined ? order.shop_id : body.shop_id + ); + if (!ownerCheck.ok) { + ctx.status = 404; + ctx.body = { code: 404, message: ownerCheck.message }; + return; + } + + // 仓库必填:不允许清空(推送 WMS 需要 warehouseCode 与仓库接口配置) + const mergedWarehouseId = body.warehouse_id === undefined ? order.warehouse_id : body.warehouse_id; + if (!(Number(mergedWarehouseId) > 0)) { + ctx.status = 400; + ctx.body = { code: 400, message: 'warehouse_id(仓库)为必填项:推送仓库需要仓库编码与仓库接口配置' }; + return; + } + + if (body.warehouse_id !== undefined && body.warehouse_id !== null && body.warehouse_id !== '') { + body.warehouse_id = Number(body.warehouse_id); + // 仓库变更时同步刷新仓库编码快照 + const warehouse = await ctx.model.Warehouse.findByPk(body.warehouse_id, { attributes: [ 'id', 'code' ] }); + if (warehouse) body.warehouse_code = warehouse.code; + } else if (body.warehouse_id === '' || body.warehouse_id === null) { + body.warehouse_id = null; + body.warehouse_code = null; + } + + // 店铺变更时同步刷新店铺名称(shop_nick 只读派生) + if (body.shop_id !== undefined) { + const shopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id); + body.shop_id = shopId; + if (shopId) { + const shop = await ctx.model.Shop.findByPk(shopId, { attributes: [ 'id', 'name' ] }); + body.shop_nick = shop ? shop.name : null; + } else { + body.shop_nick = null; + } + } + + // 收件人校验:按「记录现值 + 本次变更」合并后的结果校验(姓名/省/市/区/镇 必填,电话与手机至少一个) + const merged = { ...order.get({ plain: true }), ...body }; + const receiverError = validateReceiver(merged); + if (receiverError) { + ctx.status = 400; + ctx.body = { code: 400, message: receiverError }; + return; + } + + await order.update(body); + ctx.body = { code: 0, message: 'success', data: { id: order.id } }; + } + + /** + * @summary 批量切换发货仓库 + * @description 按「选中单据(ids)」或「筛选条件」把发货单切换到目标仓库(同时刷新 warehouse_code 快照); + * 范围用 scope_by 显式指定:ids=按勾选(ids 必传),filter=按条件(忽略 ids); + * 仅「待处理(1)」「已审核(2)」可切换(已推送/已完成已递交 WMS,切换会与仓库侧不一致); + * 传 dry_run=true 时只返回影响范围(命中/可切换/不可切换数量与原因、样例单据),用于前端弹窗确认 + * @router post /api/order-deliveries/change-warehouse + * @apikey + * @request body changeDeliveryWarehouseRequest *body + * @response 200 orderDeliveryWarehouseChangeResult success + */ + async changeWarehouse() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const body = ctx.request.body || {}; + const Model = ctx.model.OrderDelivery; + + // 目标仓库:必填且需属于当前主体 + const targetWarehouseId = body.warehouse_id != null && body.warehouse_id !== '' ? Number(body.warehouse_id) : null; + if (!targetWarehouseId) { + ctx.status = 400; + ctx.body = { code: 400, message: 'warehouse_id(目标仓库)为必填项' }; + return; + } + const ownerCheck = await this.assertOwnerBelongsToPrincipal(targetWarehouseId, null); + if (!ownerCheck.ok) { + ctx.status = 404; + ctx.body = { code: 404, message: ownerCheck.message }; + return; + } + const target = await ctx.model.Warehouse.findByPk(targetWarehouseId, { attributes: [ 'id', 'code', 'name' ] }); + + // 切换范围:scope_by 显式指定(ids 按勾选 / filter 按条件),传 filter 时忽略 ids + const built = this._buildScope(ctx, body); + if (!built.ok) { + ctx.status = 400; + ctx.body = { code: 400, message: built.message }; + return; + } + const { scopeBy, ids, where: scope, dryRun } = built; + + // 已是目标仓库的单据无需切换:命中范围里排除掉; + // 注意未指定仓库(warehouse_id IS NULL)的历史/脏数据要算作可切换,否则这类单据永远补不上仓库 + const notTarget = { [Op.or]: [{ warehouse_id: { [Op.ne]: targetWarehouseId } }, { warehouse_id: null }] }; + const matchedWhere = { [Op.and]: [ scope, notTarget ] }; + const switchableWhere = { [Op.and]: [ matchedWhere, { status: { [Op.in]: SWITCHABLE_WAREHOUSE_STATUS } }] }; + + const matched = await Model.count({ where: matchedWhere }); + const switchable = await Model.count({ where: switchableWhere }); + const blocked = matched - switchable; + + // 不可切换的原因分布(按状态聚合),供前端提示影响范围 + const blockedRows = blocked > 0 + ? await Model.findAll({ + where: { [Op.and]: [ matchedWhere, { status: { [Op.notIn]: SWITCHABLE_WAREHOUSE_STATUS } }] }, + attributes: [ 'status', [ Model.sequelize.fn('COUNT', Model.sequelize.col('id')), 'count' ]], + group: [ 'status' ], + raw: true, + }) + : []; + const blockedReason = {}; + for (const row of blockedRows) blockedReason[row.status] = Number(row.count); + + // 目标仓库与原仓库相同的命中行:已在 matchedWhere 中排除,这里额外统计被排除的条数以便提示 + const sameWarehouse = await Model.count({ + where: { [Op.and]: [ scope, { warehouse_id: targetWarehouseId }] }, + }); + + const result = { + target_warehouse: { id: target.id, code: target.code, name: target.name }, + matched, + switchable, + blocked, + blocked_reason: blockedReason, + same_warehouse: sameWarehouse, + scope: { by: scopeBy, ids: scopeBy === 'ids' ? ids : [] }, + }; + + // 预览:返回样例单据 + 各数量,不写库 + if (dryRun) { + const samples = matched > 0 + ? await Model.findAll({ + where: matchedWhere, + attributes: [ 'id', 'delivery_order_code', 'status', 'warehouse_code' ], + include: [{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'name', 'code' ] }], + order: [[ 'id', 'ASC' ]], + limit: 5, + }) + : []; + ctx.body = { + code: 0, + message: 'success', + data: { + ...result, + samples: samples.map(s => ({ + id: Number(s.id), + delivery_order_code: s.delivery_order_code, + status: Number(s.status), + warehouse_name: s.warehouse ? s.warehouse.name : (s.warehouse_code || null), + })), + }, + }; + return; + } + + if (!switchable) { + ctx.body = { code: 0, message: 'success', data: { ...result, updated: 0 } }; + return; + } + + const [ updated ] = await Model.update( + { warehouse_id: targetWarehouseId, warehouse_code: target.code }, + { where: switchableWhere } + ); + ctx.body = { code: 0, message: 'success', data: { ...result, updated } }; + } + + /** + * 主体隔离辅助:校验仓库/店铺是否属于当前主体(为空则跳过) + * @param {Number|null} warehouseId 仓库ID + * @param {Number|null|undefined} shopId 店铺ID + * @return {Promise<{ok: boolean, message?: string}>} 校验结果 + */ + async assertOwnerBelongsToPrincipal(warehouseId, shopId) { + const { ctx } = this; + const principalId = ctx.state.principalId; + + if (warehouseId != null && warehouseId !== '') { + const warehouse = await ctx.model.Warehouse.findOne({ + where: { id: Number(warehouseId), principal_id: principalId }, + attributes: [ 'id' ], + }); + if (!warehouse) return { ok: false, message: '仓库不存在或不属于当前主体' }; + } + + if (shopId != null && shopId !== '') { + const shop = await ctx.model.Shop.findOne({ + where: { id: Number(shopId), principal_id: principalId }, + attributes: [ 'id' ], + }); + if (!shop) return { ok: false, message: '店铺不存在或不属于当前主体' }; + } + + return { ok: true }; + } + + /** + * @summary 删除发货单 + * @description 仅「待处理(1)」「已取消(9)」可删除;已审核及之后(含已作废 5)禁止删除,避免绕过状态机 + * @router delete /api/order-deliveries/{id} + * @apikey + * @request path integer *id 发货单主键ID + * @response 200 baseResponse success + */ + async destroy() { + const { ctx } = this; + const order = await ctx.model.OrderDelivery.findByPk(ctx.params.id); + + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + + if (![ 1, 9 ].includes(Number(order.status))) { + ctx.status = 400; + ctx.body = { code: 400, message: '已审核及之后的单据禁止删除,可改为作废' }; + return; + } + + const transaction = await ctx.model.transaction(); + try { + await ctx.model.OrderDeliveryItem.destroy({ where: { order_delivery_id: order.id }, transaction }); + await order.destroy({ transaction }); + await transaction.commit(); + ctx.body = { code: 0, message: 'success' }; + } catch (err) { + await transaction.rollback(); + ctx.status = 500; + ctx.body = { code: 500, message: '删除失败,请稍后重试' }; + } + } + + /** + * @summary 审核发货单 + * @description 状态流转:待处理(1) → 已审核(2);需先录入明细;写入审核人与审核时间。 + * **审核只入队不推送**:由定时任务(app/schedule/orderDeliveryPush.js)异步递交 WMS,避免集中审核打满对方服务; + * 也可用「批量推送」或单条「推送」接口立即推送 + * @router post /api/order-deliveries/{id}/audit + * @apikey + * @request path integer *id 发货单主键ID + * @response 200 baseResponse success + */ + async audit() { + const { ctx } = this; + const order = await ctx.model.OrderDelivery.findByPk(ctx.params.id); + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + if (Number(order.status) !== 1) { + ctx.status = 400; + ctx.body = { code: 400, message: '只有「待处理」状态的单据可以审核' }; + return; + } + + const itemCount = await ctx.model.OrderDeliveryItem.count({ where: { order_delivery_id: order.id } }); + if (!itemCount) { + ctx.status = 400; + ctx.body = { code: 400, message: '单据无明细,无法审核' }; + return; + } + + // 清空上一轮推送记录(重试次数从 0 开始),状态置「已审核(2)」等待定时任务推送 + await order.update({ + status: 2, + audit_by: ctx.userId, + audit_time: new Date(), + pushed_at: null, + wms_push_result: null, + }); + ctx.body = { code: 0, message: '审核成功,已进入推送队列,稍后自动推送仓库', data: { id: order.id, status: 2 } }; + } + + /** + * @summary 批量审核发货单 + * @description 按「选中单据(ids)」或「筛选条件」批量审核(1→2,只入队不推送); + * 传 dry_run=true 只返回影响范围(命中/可审核/跳过数量与样例) + * @router post /api/order-deliveries/audit-batch + * @apikey + * @request body orderDeliveryBatchRequest *body + * @response 200 orderDeliveryBatchResult success + */ + async auditBatch() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const built = this._buildScope(ctx, ctx.request.body || {}); + if (!built.ok) { + ctx.status = 400; + ctx.body = { code: 400, message: built.message }; + return; + } + + const matchedWhere = built.where; + const auditableWhere = { [Op.and]: [ matchedWhere, { status: 1 }] }; + + const matched = await ctx.model.OrderDelivery.count({ where: matchedWhere }); + const auditable = await ctx.model.OrderDelivery.count({ where: auditableWhere }); + + const result = { + matched, + affected: 0, + auditable, + skipped: matched - auditable, + scope: { by: built.scopeBy, ids: built.scopeBy === 'ids' ? built.ids : [] }, + }; + + if (built.dryRun) { + const samples = matched > 0 + ? await ctx.model.OrderDelivery.findAll({ + where: matchedWhere, + attributes: [ 'id', 'delivery_order_code', 'status' ], + order: [[ 'id', 'ASC' ]], + limit: 10, + }) + : []; + result.samples = samples.map(s => ({ + id: Number(s.id), + delivery_order_code: s.delivery_order_code, + status: Number(s.status), + })); + ctx.body = { code: 0, message: 'success', data: result }; + return; + } + + if (!auditable) { + ctx.body = { code: 0, message: 'success', data: result }; + return; + } + + const [ affected ] = await ctx.model.OrderDelivery.update( + { status: 2, audit_by: ctx.userId, audit_time: new Date(), pushed_at: null, wms_push_result: null }, + { where: auditableWhere } + ); + result.affected = affected; + ctx.body = { code: 0, message: 'success', data: result }; + } + + /** + * @summary 推送发货单到仓库(WMS) + * @description 已审核(2) → 已推送(3):立即按 deliveryorder.create(ORDER 组)递交 WMS 一次; + * 对方明确响应失败会退回「待审核(1)」;无响应/超时保留「已审核(2)」等定时任务重试(最多 3 次) + * @router post /api/order-deliveries/{id}/push + * @apikey + * @request path integer *id 发货单主键ID + * @response 200 baseResponse success + */ + async push() { + const { ctx } = this; + const order = await ctx.model.OrderDelivery.findByPk(ctx.params.id, { attributes: [ 'id', 'status' ] }); + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + if (Number(order.status) !== 2) { + ctx.status = 400; + ctx.body = { code: 400, message: '只有「已审核」状态的单据可以推送' }; + return; + } + + const pushResult = await ctx.service.orderDeliveryPush.pushOne(order.id, { source: 'manual' }); + if (!pushResult.ok) { + ctx.status = pushResult.skipped ? 400 : 502; + ctx.body = { code: ctx.status, message: pushResult.message }; + return; + } + ctx.body = { + code: 0, + message: 'success', + data: { id: order.id, status: 3, attempts: pushResult.attempts, wms_response: pushResult.response }, + }; + } + + /** + * @summary 批量推送发货单到仓库 + * @description 按「选中单据(ids)」或「筛选条件」批量推送「已审核(2)」的单据; + * 顺序限流执行(每次最多 50 条,其余由定时任务继续推送);传 dry_run=true 只返回影响范围 + * @router post /api/order-deliveries/push-batch + * @apikey + * @request body orderDeliveryBatchRequest *body + * @response 200 orderDeliveryBatchResult success + */ + async pushBatch() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const body = ctx.request.body || {}; + const built = this._buildScope(ctx, body); + if (!built.ok) { + ctx.status = 400; + ctx.body = { code: 400, message: built.message }; + return; + } + + const pushableWhere = { [Op.and]: [ built.where, { status: 2 }] }; + const matched = await ctx.model.OrderDelivery.count({ where: built.where }); + const pushable = await ctx.model.OrderDelivery.count({ where: pushableWhere }); + + const result = { + matched, + affected: 0, + pushable, + skipped: matched - pushable, + scope: { by: built.scopeBy, ids: built.scopeBy === 'ids' ? built.ids : [] }, + }; + + if (built.dryRun) { + const samples = matched > 0 + ? await ctx.model.OrderDelivery.findAll({ + where: built.where, + attributes: [ 'id', 'delivery_order_code', 'status' ], + order: [[ 'id', 'ASC' ]], + limit: 10, + }) + : []; + result.samples = samples.map(s => ({ + id: Number(s.id), + delivery_order_code: s.delivery_order_code, + status: Number(s.status), + })); + ctx.body = { code: 0, message: 'success', data: result }; + return; + } + + if (!pushable) { + ctx.body = { code: 0, message: 'success', data: result }; + return; + } + + const rows = await ctx.model.OrderDelivery.findAll({ + where: pushableWhere, + attributes: [ 'id' ], + order: [[ 'id', 'ASC' ]], + }); + const stat = await ctx.service.orderDeliveryPush.pushMany(rows.map(r => Number(r.id))); + ctx.body = { + code: 0, + message: 'success', + data: { + ...result, + affected: stat.processed, + pending_rest: stat.pendingRest, + pushed: stat.pushed, + failed: stat.failed, + retry: stat.retry, + skipped_push: stat.skipped, + details: stat.details, + }, + }; + } + + /** + * @summary 驳回发货单 + * @description 审核的反向操作:已审核(2) → 待处理(1); + * 单号(delivery_order_code)来自外部/人工且是唯一去重键,驳回不换号(与出入库单驳回换号不同) + * @router post /api/order-deliveries/{id}/reject + * @apikey + * @request path integer *id 发货单主键ID + * @response 200 baseResponse success + */ + async reject() { + const { ctx } = this; + const order = await ctx.model.OrderDelivery.findByPk(ctx.params.id); + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + if (Number(order.status) !== 2) { + ctx.status = 400; + ctx.body = { code: 400, message: '只有「已审核」状态的单据可以驳回' }; + return; + } + + // 已提交过 WMS 但推送失败的单据:驳回前冲正外部单据,避免 WMS 残留(未推送成功时该调用返回失败,忽略即可) + const pushedResult = order.wms_push_result; + if (pushedResult && pushedResult.success === false) { + const pushService = ctx.service.orderDeliveryPush; + const api = await pushService.findWarehouseApi(order); + if (api) { + const client = new QimenWmsClient(api, this.app); + await pushService.cancelRemote(client, order); + } + } + + await order.update({ status: 1, audit_by: null, audit_time: null, pushed_at: null, wms_push_result: null }); + ctx.body = { code: 0, message: 'success', data: { id: order.id } }; + } + + /** + * @summary 取消发货单 + * @description 状态流转:待处理(1)/已审核(2)/已推送(3) → 已取消(9); + * 已完成(4)与已作废(5)不可取消;已推送(3)的单据会先调用 WMS order.cancel(ORDER 组)取消外部发货单, + * 取消失败(如仓库已开始配货)时不流转状态并返回失败原因 + * @router post /api/order-deliveries/{id}/cancel + * @apikey + * @request path integer *id 发货单主键ID + * @response 200 baseResponse success + */ + async cancel() { + const { ctx } = this; + const order = await this._findOrderWithWarehouse(ctx, ctx.params.id); + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + if (![ 1, 2, 3 ].includes(Number(order.status))) { + ctx.status = 400; + ctx.body = { code: 400, message: '已完成或已作废的单据不能取消' }; + return; + } + + // 已推送:先同步取消 WMS 侧发货单(释放库存锁定、置 CANCELLED) + if (Number(order.status) === 3) { + const api = await ctx.service.orderDeliveryPush.findWarehouseApi(order); + if (!api) { + ctx.status = 400; + ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口,无法取消已推送的外部发货单' }; + return; + } + const client = new QimenWmsClient(api, this.app); + let resp = null; + try { + resp = await client.cancelDeliveryOrder(order); + } catch (err) { + ctx.status = 502; + ctx.body = { code: 502, message: `取消仓库发货单失败:${err.message}` }; + return; + } + if (!client.isSuccess(resp)) { + ctx.status = 502; + ctx.body = { code: 502, message: `取消仓库发货单失败:${resp && (resp.message || resp.code)}` }; + return; + } + const pushedResult = order.wms_push_result && typeof order.wms_push_result === 'object' + ? order.wms_push_result + : {}; + await order.update({ + status: 9, + wms_push_result: { ...pushedResult, cancelResult: resp, cancelledAt: new Date().toISOString() }, + }); + ctx.body = { code: 0, message: 'success', data: { id: order.id, wms_response: resp } }; + return; + } + + await order.update({ status: 9 }); + ctx.body = { code: 0, message: 'success', data: { id: order.id } }; + } + + /** + * @summary 恢复发货单 + * @description 状态流转:已取消(9) → 待处理(1) + * @router post /api/order-deliveries/{id}/restore + * @apikey + * @request path integer *id 发货单主键ID + * @response 200 baseResponse success + */ + async restore() { + const { ctx } = this; + const order = await ctx.model.OrderDelivery.findByPk(ctx.params.id); + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + if (Number(order.status) !== 9) { + ctx.status = 400; + ctx.body = { code: 400, message: '只有「已取消」的单据可以恢复' }; + return; + } + + await order.update({ status: 1 }); + ctx.body = { code: 0, message: 'success', data: { id: order.id } }; + } + + /** + * @summary 作废发货单 + * @description 仅「已审核(2)」可作废;状态置为已作废(5),记录作废人/时间/原因,不可恢复也禁止删除 + * @router post /api/order-deliveries/{id}/void + * @apikey + * @request path integer *id 发货单主键ID + * @request body voidOrderDeliveryRequest *body + * @response 200 baseResponse success + */ + async voidOrder() { + const { ctx } = this; + const order = await ctx.model.OrderDelivery.findByPk(ctx.params.id); + if (!order) { + ctx.status = 404; + ctx.body = { code: 404, message: '发货单不存在' }; + return; + } + if (Number(order.status) !== 2) { + ctx.status = 400; + ctx.body = { code: 400, message: '只有「已审核」状态的单据可以作废' }; + return; + } + + const body = ctx.request.body || {}; + const reason = body.void_reason ? String(body.void_reason).trim() : ''; + await order.update({ + status: 5, + void_at: new Date(), + void_by: ctx.userId, + void_reason: reason || null, + }); + ctx.body = { code: 0, message: 'success', data: { id: order.id } }; + } + + /** + * 查发货单(含仓库,推送需要 warehouses.code 作为 warehouseCode) + * @param {Object} ctx + * @param {number|string} id 发货单主键ID + * @return {Promise} 发货单实例 + */ + async _findOrderWithWarehouse(ctx, id) { + return ctx.model.OrderDelivery.findByPk(id, { + include: [{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }], + }); + } + + /** + * 解析批量操作范围(勾选 ids / 筛选条件),供批量审核、批量推送、切换仓库复用 + * - scope_by 显式指定范围:ids=按勾选(ids 必传)/ filter=按条件(忽略 ids) + * - 未传 scope_by 时兜底为「有 ids 走 ids,否则走条件」 + * @param {Object} ctx egg context + * @param {Object} body 请求体 + * @return {{ok: boolean, message?: string, scopeBy?: string, ids?: number[], where?: Object, dryRun?: boolean}} 解析结果 + */ + _buildScope(ctx, body) { + const Op = this.app.Sequelize.Op; + const principalId = ctx.state.principalId; + const ids = Array.isArray(body.ids) + ? [ ...new Set(body.ids.map(v => Number(v)).filter(v => Number.isFinite(v) && v > 0)) ] + : []; + const scopeBy = body.scope_by === 'ids' || body.scope_by === 'filter' + ? body.scope_by + : (ids.length ? 'ids' : 'filter'); + + const where = { principal_id: principalId }; + if (scopeBy === 'ids') { + if (!ids.length) return { ok: false, message: '按选中操作时请至少勾选一条单据(ids 不能为空)' }; + where.id = { [Op.in]: ids }; + } else { + const code = body.delivery_order_code ? String(body.delivery_order_code).trim() : ''; + const status = body.status === undefined || body.status === null || body.status === '' ? null : Number(body.status); + const orderType = body.order_type ? String(body.order_type).trim().toUpperCase() : ''; + const shopId = body.shop_id ? Number(body.shop_id) : null; + const fromWarehouseId = body.from_warehouse_id ? Number(body.from_warehouse_id) : null; + if (!code && status === null && !orderType && !shopId && !fromWarehouseId) { + return { ok: false, message: '请指定操作范围:勾选单据(ids)或至少传一个筛选条件' }; + } + if (code) where.delivery_order_code = { [Op.like]: `%${code}%` }; + if (status !== null) where.status = status; + if (orderType) where.order_type = orderType; + if (shopId) where.shop_id = shopId; + if (fromWarehouseId) where.warehouse_id = fromWarehouseId; + } + + const dryRun = body.dry_run === true || body.dry_run === 'true' || body.dry_run === 1; + return { ok: true, scopeBy, ids, where, dryRun }; + } + +} + +module.exports = OrderDeliveryController; diff --git a/backend/app/controller/orderDeliveryItem.js b/backend/app/controller/orderDeliveryItem.js new file mode 100644 index 0000000..900e8b3 --- /dev/null +++ b/backend/app/controller/orderDeliveryItem.js @@ -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; diff --git a/backend/app/lib/orderDeliveryItems.js b/backend/app/lib/orderDeliveryItems.js new file mode 100644 index 0000000..8e297cc --- /dev/null +++ b/backend/app/lib/orderDeliveryItems.js @@ -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 }; diff --git a/backend/app/model/orderDelivery.js b/backend/app/model/orderDelivery.js new file mode 100644 index 0000000..071ea45 --- /dev/null +++ b/backend/app/model/orderDelivery.js @@ -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; +}; diff --git a/backend/app/model/orderDeliveryItem.js b/backend/app/model/orderDeliveryItem.js new file mode 100644 index 0000000..7994b0e --- /dev/null +++ b/backend/app/model/orderDeliveryItem.js @@ -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; +}; diff --git a/backend/app/schedule/orderDeliveryPush.js b/backend/app/schedule/orderDeliveryPush.js new file mode 100644 index 0000000..79bab57 --- /dev/null +++ b/backend/app/schedule/orderDeliveryPush.js @@ -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} 本轮统计 + */ + 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; + }, +}; diff --git a/backend/app/service/ai.js b/backend/app/service/ai.js new file mode 100644 index 0000000..07ebf3a --- /dev/null +++ b/backend/app/service/ai.js @@ -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} 结构化收件人字段(未识别到的字段为空串) + */ + 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} 模型返回的文本内容 + */ + 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; diff --git a/backend/app/service/orderDeliveryPush.js b/backend/app/service/orderDeliveryPush.js new file mode 100644 index 0000000..8484cbd --- /dev/null +++ b/backend/app/service/orderDeliveryPush.js @@ -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} 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} 冲正返回或异常信息 + */ + 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} 发货单实例 + */ + 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; diff --git a/backend/app/utils/recalcOrderDelivery.js b/backend/app/utils/recalcOrderDelivery.js new file mode 100644 index 0000000..a96fdd0 --- /dev/null +++ b/backend/app/utils/recalcOrderDelivery.js @@ -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 } } + ); +}; diff --git a/backend/database/migrations/20260915000000-create-order-deliveries.js b/backend/database/migrations/20260915000000-create-order-deliveries.js new file mode 100644 index 0000000..aff9b80 --- /dev/null +++ b/backend/database/migrations/20260915000000-create-order-deliveries.js @@ -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'); + }, +}; diff --git a/backend/database/migrations/20260915000100-create-order-delivery-items.js b/backend/database/migrations/20260915000100-create-order-delivery-items.js new file mode 100644 index 0000000..6b71464 --- /dev/null +++ b/backend/database/migrations/20260915000100-create-order-delivery-items.js @@ -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'); + }, +}; diff --git a/backend/database/migrations/20260915000200-order-deliveries-legacy-source.js b/backend/database/migrations/20260915000200-order-deliveries-legacy-source.js new file mode 100644 index 0000000..81f8557 --- /dev/null +++ b/backend/database/migrations/20260915000200-order-deliveries-legacy-source.js @@ -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'); + } + }, +}; diff --git a/backend/database/migrations/20260915000300-migrate-orders-to-order-deliveries.js b/backend/database/migrations/20260915000300-migrate-orders-to-order-deliveries.js new file mode 100644 index 0000000..d345e5a --- /dev/null +++ b/backend/database/migrations/20260915000300-migrate-orders-to-order-deliveries.js @@ -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 }); + }); + }, +}; diff --git a/backend/database/migrations/20260915000400-order-deliveries-station-fields.js b/backend/database/migrations/20260915000400-order-deliveries-station-fields.js new file mode 100644 index 0000000..0ed4338 --- /dev/null +++ b/backend/database/migrations/20260915000400-order-deliveries-station-fields.js @@ -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(() => {}); + }, +}; diff --git a/backend/database/migrations/20260915000500-drop-create-channel-from-order-deliveries.js b/backend/database/migrations/20260915000500-drop-create-channel-from-order-deliveries.js new file mode 100644 index 0000000..b4b6bb8 --- /dev/null +++ b/backend/database/migrations/20260915000500-drop-create-channel-from-order-deliveries.js @@ -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 侧写入)', + }); + } + }, +}; diff --git a/backend/database/migrations/20260915000600-order-type-default-enum.js b/backend/database/migrations/20260915000600-order-type-default-enum.js new file mode 100644 index 0000000..5b085b1 --- /dev/null +++ b/backend/database/migrations/20260915000600-order-type-default-enum.js @@ -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...)', + }); + } + }, +}; diff --git a/backend/database/migrations/20260915000700-create-express-companies.js b/backend/database/migrations/20260915000700-create-express-companies.js new file mode 100644 index 0000000..b985b40 --- /dev/null +++ b/backend/database/migrations/20260915000700-create-express-companies.js @@ -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'); + }, +}; diff --git a/backend/database/migrations/20260915000800-seed-express-companies.js b/backend/database/migrations/20260915000800-seed-express-companies.js new file mode 100644 index 0000000..b9c6ca5 --- /dev/null +++ b/backend/database/migrations/20260915000800-seed-express-companies.js @@ -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) }, + }); + }, +}; diff --git a/backend/database/migrations/20260915000900-drop-remark-from-order-deliveries.js b/backend/database/migrations/20260915000900-drop-remark-from-order-deliveries.js new file mode 100644 index 0000000..e7d1f6f --- /dev/null +++ b/backend/database/migrations/20260915000900-drop-remark-from-order-deliveries.js @@ -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)', + }); + } + }, +}; diff --git a/backend/database/migrations/20260915001000-seed-order-create-menu.js b/backend/database/migrations/20260915001000-seed-order-create-menu.js new file mode 100644 index 0000000..5fa73d9 --- /dev/null +++ b/backend/database/migrations/20260915001000-seed-order-create-menu.js @@ -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 ], + }); + }, +};