- 出入库记录(库存流水):新增 stock_records 表/模型/只读接口(列表 + 业务动作选项)与「出入库记录」菜单; 库存变动统一收敛到 app/utils/stockRecord.js#applyStockChange,与流水写入同事务(含变动前后总/锁定/可用数量) - 发货单:审核(1→2) 按明细锁定库存、发货确认(3→4) 扣减、推送失败退回/驳回/取消/作废释放(新增 stock_locked 列); 恢复(9→1) 时曾推送过的单据换号(WMS 取消后原单号仍被占用,沿用旧号重推会被判「订单已存在」) - 出库单:新增快递(express_code/express_name)、收件人(receiver_*) 与多运单号(express_codes) 字段; 推送报文补齐 logisticsCode/receiverInfo;新增出库单推送服务与定时任务 - 快递:多运单号回填、仓库快递映射(warehouse_express_mappings) 与快递字典补录等迁移 - 契约:补充出入库记录、出库单快递/收件人等定义(swagger.json 为本地生成、不入库)
804 lines
32 KiB
JavaScript
804 lines
32 KiB
JavaScript
'use strict';
|
||
|
||
const { Controller } = require('egg');
|
||
const recalcStock = require('../utils/recalcStock');
|
||
const { applyStockChange } = require('../utils/stockRecord');
|
||
const nextRejectedBillNo = require('../utils/rejectBillNo');
|
||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||
const QimenWmsClient = require('../lib/wms/qimenClient');
|
||
const { DEFAULT_OUTBOUND_ORDER_TYPE, OUTBOUND_ORDER_TYPE_LIST, normalizeOutboundOrderType } = require('../lib/wms/orderTypes');
|
||
|
||
/** 仓库接口类型:当前系统仅对接类奇门JSON接口 */
|
||
const API_TYPE_QIMEN = 'qimen';
|
||
/** 出库单单号前缀,未提供单据号时由系统按 {前缀}_{自增id} 自动生成(如 CK_123) */
|
||
const OUTBOUND_BILL_PREFIX = 'CK';
|
||
|
||
/**
|
||
* 单号与状态/生命周期字段由系统与业务事务(创建 / 审核 / 推送 / 完成 / 驳回 / 作废 / 取消 / 库存回调)推动,
|
||
* 禁止通过新增、更新等通用接口直接写入,避免破坏单据对外标识(WMS deliveryOrderCode=bill_no)或绕过状态机。
|
||
*/
|
||
const MANAGED_FIELDS = [
|
||
'bill_no', 'status', 'pushed_at', 'wms_push_result',
|
||
'void_at', 'void_by', 'void_reason', 'stock_deducted', 'stock_locked', 'item_total', 'item_kind',
|
||
'waybill_codes',
|
||
];
|
||
|
||
/**
|
||
* @controller OutboundOrderController 出库单管理
|
||
* 单据头 outbound_orders;明细由 stock_items(bill_type=2)承载,随单据在同一事务内创建
|
||
*/
|
||
class OutboundOrderController extends Controller {
|
||
/**
|
||
* @summary 出库单列表
|
||
* @router get /api/outbound-orders
|
||
* @apikey
|
||
* @request query integer page 页码,默认 1
|
||
* @request query integer pageSize 每页条数,默认 20
|
||
* @request query string bill_no 出库单号,支持模糊匹配
|
||
* @request query integer status 状态:1待出库 2已出库 3已取消
|
||
* @request query string outbound_type 出库类型(WMS 编码):PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单
|
||
* @request query integer shop_id 店铺/仓库ID
|
||
* @response 200 outboundOrderListResponse success
|
||
*/
|
||
async index() {
|
||
const { ctx } = this;
|
||
const Op = this.app.Sequelize.Op;
|
||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||
const { bill_no: billNo, status, outbound_type: outboundType, shop_id: shopId } = ctx.query;
|
||
const principalId = ctx.state.principalId;
|
||
|
||
const where = { principal_id: principalId };
|
||
if (billNo) where.bill_no = { [Op.like]: `%${billNo}%` };
|
||
if (status !== undefined && status !== '') where.status = Number(status);
|
||
if (outboundType !== undefined && outboundType !== '') where.outbound_type = String(outboundType).trim().toUpperCase();
|
||
if (shopId) where.shop_id = Number(shopId);
|
||
|
||
const { count, rows } = await ctx.model.OutboundOrder.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 出库单详情
|
||
* @router get /api/outbound-orders/{id}
|
||
* @apikey
|
||
* @request path integer *id 出库单主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async show() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id, {
|
||
include: [
|
||
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
|
||
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
|
||
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
|
||
{ model: ctx.model.User, as: 'voider', attributes: [ 'id', 'nickname', 'username' ] },
|
||
],
|
||
});
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
|
||
const items = await ctx.model.StockItem.findAll({
|
||
where: { bill_type: 2, bill_id: order.id },
|
||
include: [
|
||
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ] },
|
||
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
|
||
],
|
||
});
|
||
|
||
const data = order.toJSON();
|
||
data.items = items;
|
||
ctx.body = { code: 0, message: 'success', data };
|
||
}
|
||
|
||
/**
|
||
* @summary 新增出库单
|
||
* @description 单号由系统按 CK_{自增id} 自动生成(不接受传入);可同时传入 items(stock_items, bill_type=2)一次性写入明细
|
||
* @router post /api/outbound-orders
|
||
* @apikey
|
||
* @request body createOutboundOrderRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async create() {
|
||
const { ctx } = this;
|
||
const { items, warehouse_id: warehouseId } = ctx.request.body;
|
||
const principalId = ctx.state.principalId;
|
||
|
||
if (!warehouseId) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: 'warehouse_id(仓库)为必填项' };
|
||
return;
|
||
}
|
||
|
||
const payload = { ...ctx.request.body };
|
||
delete payload.items;
|
||
// 单号(bill_no)在 MANAGED_FIELDS 内被剥离:一律由系统生成,不接受前端传入
|
||
for (const f of MANAGED_FIELDS) delete payload[f];
|
||
|
||
// 出库单类型:直接落库 WMS 编码(CK 组),非法值拒绝;不传时默认 PTCK(普通出库单)
|
||
const outboundType = normalizeOutboundOrderType(payload.outbound_type);
|
||
if (payload.outbound_type != null && String(payload.outbound_type).trim() !== '' && !outboundType) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: `outbound_type(出库类型)不合法,支持:${OUTBOUND_ORDER_TYPE_LIST.join(' / ')}` };
|
||
return;
|
||
}
|
||
payload.outbound_type = outboundType || DEFAULT_OUTBOUND_ORDER_TYPE;
|
||
|
||
// 校验明细关联商品均存在且已启用
|
||
const productIds = (items || []).map((i) => i.product_id).filter(Boolean);
|
||
if (productIds.length) {
|
||
const validProducts = await ctx.model.Product.findAll({
|
||
where: { id: productIds, status: 1 },
|
||
attributes: [ 'id' ],
|
||
});
|
||
const validIds = new Set(validProducts.map((p) => p.id));
|
||
if (productIds.some((id) => !validIds.has(id))) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '明细关联的商品不存在或已禁用,无法创建单据' };
|
||
return;
|
||
}
|
||
}
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
const totalAmount = Number(payload.total_amount) || 0;
|
||
// 先用临时单号落库以取得自增 id,随后更新为 CK_{id}
|
||
const order = await ctx.model.OutboundOrder.create({
|
||
status: 1,
|
||
...payload,
|
||
bill_no: `CK_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`,
|
||
principal_id: principalId,
|
||
warehouse_id: warehouseId,
|
||
created_by: ctx.userId,
|
||
total_amount: totalAmount,
|
||
}, { transaction });
|
||
|
||
if (Array.isArray(items) && items.length) {
|
||
await ctx.model.StockItem.bulkCreate(items.map(item => ({
|
||
principal_id: principalId,
|
||
bill_type: 2,
|
||
bill_id: order.id,
|
||
shop_id: item.shop_id || order.shop_id || null,
|
||
product_id: item.product_id || null,
|
||
combo_product_id: item.combo_product_id || null,
|
||
shop_product_id: item.shop_product_id || null,
|
||
name: item.name || null,
|
||
code: item.code || null,
|
||
inventory_type: item.inventory_type === 'CC' ? 'CC' : 'ZP',
|
||
spec: item.spec || null,
|
||
unit: item.unit || null,
|
||
quantity: item.quantity || 0,
|
||
plan_out_qty: item.quantity || 0,
|
||
price: item.price == null ? null : item.price,
|
||
total_amount: Number((Number(item.quantity || 0) * Number(item.price || 0)).toFixed(2)),
|
||
remark: item.remark || null,
|
||
})), { transaction });
|
||
}
|
||
|
||
// 系统生成单据号:CK_{自增id}
|
||
await order.update({ bill_no: `${OUTBOUND_BILL_PREFIX}_${order.id}` }, { transaction });
|
||
|
||
await transaction.commit();
|
||
await recalcStock(ctx, 2, order.id);
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '新增出库单失败,请稍后重试' };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @summary 更新出库单
|
||
* @description 仅「待出库(1)」可编辑;只更新单据头字段(不含明细与单号/状态等系统托管字段)
|
||
* @router put /api/outbound-orders/{id}
|
||
* @apikey
|
||
* @request path integer *id 出库单主键ID
|
||
* @request body updateOutboundOrderRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async update() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
// 仅「待出库」可编辑:与明细锁定规则一致,已审核及之后禁止改动(可先驳回再修改)
|
||
if (order.status !== 1) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '仅「待出库」状态的单据可以编辑,如需修改请先驳回' };
|
||
return;
|
||
}
|
||
delete ctx.request.body.principal_id;
|
||
delete ctx.request.body.created_by;
|
||
for (const f of MANAGED_FIELDS) delete ctx.request.body[f];
|
||
// 出库单类型:同样存储 WMS 编码(CK 组),非法值拒绝(影响后续推送与取消的口径一致)
|
||
if (ctx.request.body.outbound_type != null && String(ctx.request.body.outbound_type).trim() !== '') {
|
||
const outboundType = normalizeOutboundOrderType(ctx.request.body.outbound_type);
|
||
if (!outboundType) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: `outbound_type(出库类型)不合法,支持:${OUTBOUND_ORDER_TYPE_LIST.join(' / ')}` };
|
||
return;
|
||
}
|
||
ctx.request.body.outbound_type = outboundType;
|
||
} else {
|
||
delete ctx.request.body.outbound_type;
|
||
}
|
||
await order.update(ctx.request.body);
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||
}
|
||
|
||
/**
|
||
* @summary 删除出库单
|
||
* @description 物理删除单据,并级联删除其明细(stock_items, bill_type=2)。仅「待出库(1)」「已取消(9)」可删除;
|
||
* 已审核(2) 及之后的单据禁止删除,请使用作废接口
|
||
* @router delete /api/outbound-orders/{id}
|
||
* @apikey
|
||
* @request path integer *id 出库单主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async destroy() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (order.status !== 1 && order.status !== 9) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '已审核及之后的单据禁止删除,请使用「作废」' };
|
||
return;
|
||
}
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
await ctx.model.StockItem.destroy({ where: { bill_type: 2, bill_id: order.id }, transaction });
|
||
await order.destroy({ transaction });
|
||
await transaction.commit();
|
||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '删除失败,请稍后重试' };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @summary 审核出库单
|
||
* @description 状态流转:待出库(1) → 已审核(2);需先录入明细。
|
||
* **审核只入队不推送**:由定时任务(app/schedule/outboundOrderPush.js)异步递交 WMS stockout.create,
|
||
* 避免集中审核时把对方服务打满;也可用「推送」按钮立即推送(状态仍需为已审核)。
|
||
* 审核同时清空上一轮推送记录(重试次数归零)。推送失败的处理见 app/service/outboundOrderPush.js:
|
||
* 对方明确失败(含库存锁定失败)立即退回「待出库(1)」并释放锁定库存;无响应/超时最多尝试 3 次后同样退回。
|
||
* @router post /api/outbound-orders/{id}/audit
|
||
* @apikey
|
||
* @request path integer *id 出库单主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async audit() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (order.status !== 1) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '只有「已创建」状态的单据可以审核' };
|
||
return;
|
||
}
|
||
const itemCount = await ctx.model.StockItem.count({ where: { bill_type: 2, bill_id: order.id } });
|
||
if (!itemCount) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '单据无明细,无法审核' };
|
||
return;
|
||
}
|
||
// 清空上一轮推送记录(重试次数从 0 开始),进入推送队列等待定时任务自动推送
|
||
await order.update({ status: 2, pushed_at: null, wms_push_result: null });
|
||
ctx.body = {
|
||
code: 0,
|
||
message: '审核成功,已进入推送队列,稍后自动推送仓库',
|
||
data: { id: order.id, status: 2 },
|
||
};
|
||
}
|
||
/**
|
||
* 推送:已审核(2) -> 已推送(3),立即递交 WMS(stockout.create)一次
|
||
*
|
||
* 详细口径(锁定库存、失败冲正与重试)见 app/service/outboundOrderPush.js;
|
||
* 定时任务会自动推送「已审核」单据,此接口用于需要立即推送的场景
|
||
* @router post /api/outbound-orders/{id}/push
|
||
* @apikey
|
||
* @request path integer *id 出库单主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async push() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id, { attributes: [ 'id', 'status' ] });
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (order.status !== 2) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '只有「已审核」状态的单据可以推送' };
|
||
return;
|
||
}
|
||
|
||
const pushResult = await ctx.service.outboundOrderPush.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 },
|
||
};
|
||
}
|
||
/**
|
||
* 推送:已审核(2) -> 已推送(3),锁定库存(占用可用,防超卖)并递交 WMS(stockout.create)
|
||
* 失败时不流转状态,直接返回 WMS 错误信息;推送失败会释放已锁定库存,可重试
|
||
*/
|
||
async push() {
|
||
const { ctx } = this;
|
||
const orderId = Number(ctx.params.id);
|
||
const principalId = ctx.state.principalId;
|
||
|
||
const order = await ctx.model.OutboundOrder.findByPk(orderId, {
|
||
include: [
|
||
{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] },
|
||
{ model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] },
|
||
],
|
||
});
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (order.status !== 2) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '只有「已审核」状态的单据可以推送' };
|
||
return;
|
||
}
|
||
|
||
const api = await ctx.model.WarehouseApi.findOne({
|
||
where: { warehouse_id: order.warehouse_id, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
|
||
order: [[ 'id', 'ASC' ]],
|
||
});
|
||
if (!api) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
|
||
return;
|
||
}
|
||
|
||
const items = await ctx.model.StockItem.findAll({
|
||
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
|
||
include: [ { model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'retail_price' ] } ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
});
|
||
|
||
// 无明细不允许推送(否则既不会锁定库存,也不会向 WMS 发出有效出库单)
|
||
if (!items.length) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '单据无明细,无法推送' };
|
||
return;
|
||
}
|
||
|
||
const productIds = items.map(i => Number(i.product_id));
|
||
const productMap = productIds.length
|
||
? await ctx.model.Product.findAll({ where: { id: { [ctx.app.Sequelize.Op.in]: productIds } }, attributes: [ 'id', 'item_code', 'item_name' ] })
|
||
: [];
|
||
const pmap = new Map(productMap.map(p => [ Number(p.id), p ]));
|
||
|
||
// stockout.create 的明细行 itemId 为必填:取该仓库已推送商品的 WMS 商品ID
|
||
const links = productIds.length
|
||
? await ctx.model.WarehouseProduct.findAll({
|
||
where: { principal_id: principalId, warehouse_id: order.warehouse_id, product_id: { [ctx.app.Sequelize.Op.in]: productIds } },
|
||
attributes: [ 'product_id', 'wms_item_id' ],
|
||
})
|
||
: [];
|
||
const wmsItemIdByProduct = {};
|
||
for (const l of links) {
|
||
if (l.wms_item_id != null) wmsItemIdByProduct[Number(l.product_id)] = Number(l.wms_item_id);
|
||
}
|
||
|
||
// 先锁定库存(占用可用,防止超卖);WMS 推送失败则回滚释放
|
||
const reserveTx = await ctx.model.transaction();
|
||
try {
|
||
for (const it of items) {
|
||
const pid = Number(it.product_id);
|
||
const qty = Number(it.quantity) || 0;
|
||
try {
|
||
// 行级库存类型:CC=残次 -> 锁定残次库存,其余(ZP等)归为正品 ZC
|
||
// 锁定同时写一条「出入库记录」(outbound_lock),记录锁定前后的锁定/可用数量
|
||
await applyStockChange(ctx, {
|
||
bizType: 'outbound_lock',
|
||
principalId: order.principal_id,
|
||
warehouseId: order.warehouse_id,
|
||
productId: pid,
|
||
itemCode: it.code || (pmap.get(pid) && pmap.get(pid).item_code),
|
||
itemName: it.name || (pmap.get(pid) && pmap.get(pid).item_name),
|
||
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
|
||
quantity: qty,
|
||
billId: order.id,
|
||
billNo: order.bill_no,
|
||
createdBy: ctx.userId,
|
||
remark: '出库单推送仓库锁定库存',
|
||
transaction: reserveTx,
|
||
});
|
||
} catch (err) {
|
||
if (err.code === 'INSUFFICIENT_STOCK') {
|
||
const p = pmap.get(pid);
|
||
err.message = `库存不足:${p ? `${p.item_name}(${p.item_code})` : '商品#' + pid},可用 ${err.available},需 ${err.require}`;
|
||
}
|
||
throw err;
|
||
}
|
||
}
|
||
await reserveTx.commit();
|
||
} catch (err) {
|
||
await reserveTx.rollback();
|
||
if (err.code === 'INSUFFICIENT_STOCK') {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: err.message };
|
||
return;
|
||
}
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '库存锁定失败,请稍后重试' };
|
||
return;
|
||
}
|
||
|
||
// 递交外部 WMS(stockout.create)
|
||
const client = new QimenWmsClient(api, this.app);
|
||
const externalOrderCode = order.bill_no;
|
||
try {
|
||
const resp = await client.createStockout(order, items, { warehouse: order.warehouse, wmsItemIdByProduct });
|
||
const success = client.isSuccess(resp);
|
||
const pushResult = {
|
||
success,
|
||
code: resp && resp.code,
|
||
message: resp && resp.message,
|
||
flag: resp && resp.flag,
|
||
deliveryOrderCode: externalOrderCode,
|
||
warehouseApiId: api.id,
|
||
apiType: api.type,
|
||
response: resp,
|
||
pushedAt: new Date().toISOString(),
|
||
};
|
||
if (!success) {
|
||
// 推送失败:释放锁定库存,并调 order.cancel 冲正(外部可能已建单)
|
||
await this._releaseStock(order, items).catch(() => {});
|
||
pushResult.cancelResult = await client.cancelOrder(order)
|
||
.catch(err => ({ code: 'EXCEPTION', message: err.message }));
|
||
await order.update({ wms_push_result: pushResult, pushed_at: new Date() });
|
||
ctx.status = 502;
|
||
ctx.body = { code: 502, message: `WMS 返回失败: ${resp && (resp.message || resp.code)}` };
|
||
return;
|
||
}
|
||
await order.update({
|
||
status: 3,
|
||
operate_time: new Date(),
|
||
pushed_at: new Date(),
|
||
wms_push_result: pushResult,
|
||
});
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id, wms_response: resp } };
|
||
} catch (err) {
|
||
// 请求异常:释放锁定库存,同样调 order.cancel 冲正,状态保持「已审核」可重试
|
||
await this._releaseStock(order, items).catch(() => {});
|
||
const cancelResult = await client.cancelOrder(order)
|
||
.catch(e => ({ code: 'EXCEPTION', message: e.message }));
|
||
const failResult = {
|
||
success: false,
|
||
deliveryOrderCode: externalOrderCode,
|
||
warehouseApiId: api.id,
|
||
apiType: api.type,
|
||
error: err.message,
|
||
cancelResult,
|
||
pushedAt: new Date().toISOString(),
|
||
};
|
||
await order.update({ wms_push_result: failResult, pushed_at: new Date() }).catch(() => {});
|
||
ctx.status = 502;
|
||
ctx.body = { code: 502, message: err.message };
|
||
}
|
||
}
|
||
/** 推送失败时释放已锁定库存(并记一条出库解锁流水) */
|
||
async _releaseStock(order, items) {
|
||
const { ctx } = this;
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
for (const it of items) {
|
||
await applyStockChange(ctx, {
|
||
bizType: 'outbound_unlock',
|
||
principalId: order.principal_id,
|
||
warehouseId: order.warehouse_id,
|
||
productId: Number(it.product_id),
|
||
itemCode: it.code,
|
||
itemName: it.name,
|
||
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
|
||
quantity: Number(it.quantity) || 0,
|
||
billId: order.id,
|
||
billNo: order.bill_no,
|
||
createdBy: ctx.userId,
|
||
remark: '推送失败释放锁定库存',
|
||
transaction,
|
||
});
|
||
}
|
||
await transaction.commit();
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
throw err;
|
||
}
|
||
}
|
||
/** 完成出库:已推送(3) -> 完成(4),需有明细(已推送单必然有,此处兜底) */
|
||
async complete() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (order.status !== 3) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '只有「已推送」状态的单据可以完成出库' };
|
||
return;
|
||
}
|
||
const itemCount = await ctx.model.StockItem.count({ where: { bill_type: 2, bill_id: order.id } });
|
||
if (!itemCount) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '单据无明细,无法完成出库' };
|
||
return;
|
||
}
|
||
await order.update({ status: 4 });
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||
}
|
||
/** 取消:任意非完成态 -> 已取消(9) */
|
||
async cancel() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (order.status === 4) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '已完成单据不能取消' };
|
||
return;
|
||
}
|
||
// 已推送(3)的单据取消时释放已锁定库存
|
||
if (order.status === 3) {
|
||
const items = await ctx.model.StockItem.findAll({
|
||
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
|
||
attributes: [ 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
|
||
order: [[ 'product_id', 'ASC' ]],
|
||
});
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
for (const it of items) {
|
||
await applyStockChange(ctx, {
|
||
bizType: 'outbound_unlock',
|
||
principalId: order.principal_id,
|
||
warehouseId: order.warehouse_id,
|
||
productId: Number(it.product_id),
|
||
itemCode: it.code,
|
||
itemName: it.name,
|
||
itemType: it.inventory_type === 'CC' ? 'CC' : 'ZC',
|
||
quantity: Number(it.quantity) || 0,
|
||
billId: order.id,
|
||
billNo: order.bill_no,
|
||
createdBy: ctx.userId,
|
||
remark: '出库单取消释放锁定库存',
|
||
transaction,
|
||
});
|
||
}
|
||
await order.update({ status: 9 }, { transaction });
|
||
await transaction.commit();
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '取消失败,请稍后重试' };
|
||
}
|
||
return;
|
||
}
|
||
await order.update({ status: 9 });
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||
}
|
||
/** 恢复:已取消(9) -> 已创建(1) */
|
||
async restore() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (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/outbound-orders/{id}/void
|
||
* @apikey
|
||
* @request path integer *id 出库单主键ID
|
||
* @request body voidOutboundOrderRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async voidOrder() {
|
||
const { ctx } = this;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id);
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (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 } };
|
||
}
|
||
/**
|
||
* @summary 驳回出库单
|
||
* @description 审核的反向操作:已审核(2) / 已推送(3) 且未完成(4) 的单据可驳回,驳回后回到「待出库(1)」;
|
||
* 驳回会变更单号(在基础单号后追加/递增 `_N`,首次 `_1`、再次 `_2`);
|
||
* 已推送的会先调用 WMS order.cancel 取消外部出库单,再按是否已被发货通知扣减回滚库存
|
||
* @router post /api/outbound-orders/{id}/reject
|
||
* @apikey
|
||
* @request path integer *id 出库单主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async reject() {
|
||
const { ctx } = this;
|
||
const principalId = ctx.state.principalId;
|
||
const order = await ctx.model.OutboundOrder.findByPk(ctx.params.id, {
|
||
include: [{ model: ctx.model.Warehouse, as: 'warehouse', attributes: [ 'id', 'code', 'name' ] }],
|
||
});
|
||
if (!order) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '出库单不存在' };
|
||
return;
|
||
}
|
||
if (order.status === 4) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '已完成出库的单据不能驳回' };
|
||
return;
|
||
}
|
||
if (order.status !== 2 && order.status !== 3) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '只有「已审核」「已推送」状态的单据可以驳回' };
|
||
return;
|
||
}
|
||
// 仅「已审核」:直接回退,未锁定库存
|
||
if (order.status !== 3) {
|
||
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);
|
||
await order.update({ status: 1, bill_no: newBillNo });
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
|
||
return;
|
||
}
|
||
// 已推送:先走接口取消外部单据,成功后才回滚库存与状态
|
||
const api = await ctx.model.WarehouseApi.findOne({
|
||
where: { warehouse_id: order.warehouse_id, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
|
||
order: [[ 'id', 'ASC' ]],
|
||
});
|
||
if (!api) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '该仓库未配置启用的类奇门接口(缺少 app_key / app_secret / base_url)' };
|
||
return;
|
||
}
|
||
const client = new QimenWmsClient(api, this.app);
|
||
let resp;
|
||
try {
|
||
resp = await client.cancelOrder(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 items = await ctx.model.StockItem.findAll({
|
||
where: { bill_type: 2, bill_id: order.id, product_id: { [ctx.app.Sequelize.Op.ne]: null } },
|
||
attributes: [ 'product_id', 'code', 'name', 'quantity', 'inventory_type' ],
|
||
order: [[ 'product_id', 'ASC' ]],
|
||
});
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
for (const it of items) {
|
||
const pid = Number(it.product_id);
|
||
const qty = Number(it.quantity) || 0;
|
||
// 行级库存类型:CC=残次 -> 残次库存,其余(ZP等)归为正品 ZC
|
||
const itemType = it.inventory_type === 'CC' ? 'CC' : 'ZC';
|
||
if (order.stock_deducted) {
|
||
// 发货通知已按明细扣减总数量(锁定已同步释放):回补总数量(并记一条出库驳回回补流水)
|
||
await applyStockChange(ctx, {
|
||
bizType: 'outbound_restore',
|
||
principalId: order.principal_id,
|
||
warehouseId: order.warehouse_id,
|
||
productId: pid,
|
||
itemCode: it.code,
|
||
itemName: it.name,
|
||
itemType,
|
||
quantity: qty,
|
||
billId: order.id,
|
||
billNo: order.bill_no,
|
||
createdBy: ctx.userId,
|
||
remark: '出库单驳回回补总数量',
|
||
transaction,
|
||
});
|
||
} else {
|
||
// 仅推送锁定、尚未扣减:释放锁定(并记一条出库解锁流水)
|
||
await applyStockChange(ctx, {
|
||
bizType: 'outbound_unlock',
|
||
principalId: order.principal_id,
|
||
warehouseId: order.warehouse_id,
|
||
productId: pid,
|
||
itemCode: it.code,
|
||
itemName: it.name,
|
||
itemType,
|
||
quantity: qty,
|
||
billId: order.id,
|
||
billNo: order.bill_no,
|
||
createdBy: ctx.userId,
|
||
remark: '出库单驳回释放锁定',
|
||
transaction,
|
||
});
|
||
}
|
||
}
|
||
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);
|
||
await order.update({
|
||
status: 1,
|
||
bill_no: newBillNo,
|
||
stock_deducted: 0,
|
||
pushed_at: null,
|
||
wms_push_result: null,
|
||
}, { transaction });
|
||
await transaction.commit();
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id, bill_no: order.bill_no } };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '驳回失败,请稍后重试' };
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = OutboundOrderController;
|