oms/backend/app/controller/orderDelivery.js
liufumingren 77da5e1c69 feat(backend): 发货单批量操作与店铺必填/推送校验
- 新增批量审核 audit-batch、批量推送 push-batch、切换发货仓库 change-warehouse、设置所属店铺 change-shop

  统一由 _buildScope 解析范围(scope_by=ids 按勾选 / filter 按筛选条件),支持 dry_run 预览影响范围

- 手工单必须选店铺:create/update 必填且不允许清空、audit 校验、pushOne 无店铺直接跳过;shop_nick 为空时按 shop_id 兜底补齐并回写快照

- 修复范围解析与「目标店铺」字段重名导致命中 0 条:店铺筛选取 from_shop_id,changeShop 前剔除 shop_id

- 契约新增 changeDeliveryWarehouseRequest/changeDeliveryShopRequest/orderDeliveryBatchRequest 等,createOrderDeliveryRequest 的 warehouse_id/shop_id 改为必填
2026-09-13 02:42:23 +08:00

1181 lines
47 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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 ];
/**
* 可设置所属店铺的状态:待处理(1) / 已审核(2) / 已推送(3)
* - 店铺只影响推送时的快递策略匹配(shopNick)与 OMS 自身记录,不回写 WMS,
* 所以「已推送(3)」也允许修正;已完成(4) / 已作废(5) / 已取消(9) 不再变更
*/
const SHOP_SWITCHABLE_STATUS = [ 1, 2, 3 ];
/**
* @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;
}
// 店铺必填:shopNick 取所选店铺名称,WMS 侧靠它匹配快递策略(缺失时可能匹配不到快递)
const shopId = body.shop_id != null && body.shop_id !== '' ? Number(body.shop_id) : null;
if (!shopId) {
ctx.status = 400;
ctx.body = { code: 400, message: 'shop_id(店铺)为必填项:推送仓库时 shopNick 取所选店铺名称' };
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)取所选店铺名称,无需手工填写(shopId 已在前面必填校验中解析)
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;
}
// 店铺必填:不允许清空(shopNick 取店铺名称,推送时用于匹配快递策略)
const mergedShopId = body.shop_id === undefined ? order.shop_id : body.shop_id;
if (!(Number(mergedShopId) > 0)) {
ctx.status = 400;
ctx.body = { code: 400, message: 'shop_id(店铺)为必填项:推送仓库时 shopNick 取所选店铺名称' };
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 } };
}
/**
* @summary 批量设置所属店铺
* @description 按「选中单据(ids)」或「筛选条件」把发货单的店铺设为目标店铺(同时刷新 shop_nick 名称快照);
* 店铺只影响推送时的快递策略匹配(shopNick)与 OMS 记录、不回写 WMS,因此「已推送(3)」也允许修正;
* 传 dry_run=true 时只返回影响范围
* @router post /api/order-deliveries/change-shop
* @apikey
* @request body changeDeliveryShopRequest *body
* @response 200 orderDeliveryShopChangeResult success
*/
async changeShop() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const body = ctx.request.body || {};
const Model = ctx.model.OrderDelivery;
const targetShopId = body.shop_id != null && body.shop_id !== '' ? Number(body.shop_id) : null;
if (!targetShopId) {
ctx.status = 400;
ctx.body = { code: 400, message: 'shop_id(目标店铺)为必填项' };
return;
}
const ownerCheck = await this.assertOwnerBelongsToPrincipal(null, targetShopId);
if (!ownerCheck.ok) {
ctx.status = 404;
ctx.body = { code: 404, message: ownerCheck.message };
return;
}
const target = await ctx.model.Shop.findByPk(targetShopId, { attributes: [ 'id', 'name' ] });
// shop_id 在本接口是「目标店铺」,不能当作筛选条件(否则 scope 里会出现 shop_id = target 导致命中 0 条)
const scopeBody = { ...body };
delete scopeBody.shop_id;
const built = this._buildScope(ctx, scopeBody);
if (!built.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: built.message };
return;
}
const { scopeBy, ids, where: scope, dryRun } = built;
// 已是目标店铺(含店铺为空)的都要纳入:空店铺正是需要补的
const notTarget = { [Op.or]: [{ shop_id: { [Op.ne]: targetShopId } }, { shop_id: null }] };
const matchedWhere = { [Op.and]: [ scope, notTarget ] };
const switchableWhere = { [Op.and]: [ matchedWhere, { status: { [Op.in]: SHOP_SWITCHABLE_STATUS } }] };
const matched = await Model.count({ where: matchedWhere });
const switchable = await Model.count({ where: switchableWhere });
const blocked = matched - switchable;
const sameShop = await Model.count({ where: { [Op.and]: [ scope, { shop_id: targetShopId }] } });
const blockedRows = blocked > 0
? await Model.findAll({
where: { [Op.and]: [ matchedWhere, { status: { [Op.notIn]: SHOP_SWITCHABLE_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);
const result = {
target_shop: { id: target.id, name: target.name },
matched,
switchable,
blocked,
blocked_reason: blockedReason,
same_shop: sameShop,
scope: { by: scopeBy, ids: scopeBy === 'ids' ? ids : [] },
};
if (dryRun) {
const samples = matched > 0
? await Model.findAll({
where: matchedWhere,
attributes: [ 'id', 'delivery_order_code', 'status', 'shop_id', 'shop_nick' ],
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),
shop_nick: s.shop_nick || null,
})),
},
};
return;
}
if (!switchable) {
ctx.body = { code: 0, message: 'success', data: { ...result, updated: 0 } };
return;
}
const [ updated ] = await Model.update(
{ shop_id: targetShopId, shop_nick: target.name },
{ 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;
}
// 手工单必须选店铺:shopNick 取店铺名称,推送时 WMS 靠它匹配快递策略
if (!(Number(order.shop_id) > 0)) {
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;
// 可审核 = 待处理(1) 且已设置店铺(手工单必须选店铺,推送时 shopNick 取店铺名称)
const auditableWhere = { [Op.and]: [ matchedWhere, { status: 1 }, { shop_id: { [Op.ne]: null } }] };
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<Object|null>} 发货单实例
*/
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() : '';
// 店铺筛选:from_shop_id 为通用写法(shop_id 仅作兼容,设置店铺接口里 shop_id 是「目标店铺」不能当条件)
const fromShopId = body.from_shop_id ? Number(body.from_shop_id) : (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 && !fromShopId && !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 (fromShopId) where.shop_id = fromShopId;
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;