- 新增 app/lib/billOwnerScope.js:仓库可访问性(主体 + 所在公司)、明细商品/组合 与仓库同货主校验、按单据仓库取货主 - 入库单/出库单 create:仓库可访问且明细商品必须与仓库同货主 (原明细校验未带 principal_id,一并修正) - 入库单/出库单 update:改仓库时校验新仓库可访问且已有明细同货主 - 明细接口(stock_items create/update):按所属单据仓库货主校验商品,堵住 单据建好后再塞入其它货主商品的路径 - 前端新增 useWarehouseGoodsScope:仓库与商品双向约束(先选仓库限制商品、 先选商品限制仓库、同单明细不得跨货主) - 入库/出库创建页与单据明细编辑区接入该约束并给出提示 - ProductSelect 新增 beforeSelect 前置校验与受控显示值,校验不通过时回滚显示
647 lines
27 KiB
JavaScript
647 lines
27 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 { resolveAccountName } = require('../lib/accountProfile');
|
||
const { resolveWarehouse, assertItemsOwner } = require('../lib/billOwnerScope');
|
||
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',
|
||
// 操作人由审核流程写入(=审核人),与入库单同口径,不接受接口传入
|
||
'operator',
|
||
];
|
||
|
||
/**
|
||
* @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)一次性写入明细。
|
||
* 单据货主由仓库决定(warehouses.subsidiary_id),明细商品/组合必须与仓库同货主,否则拒绝创建
|
||
* @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 warehouseScope = await resolveWarehouse(ctx, warehouseId);
|
||
if (!warehouseScope.ok) {
|
||
ctx.status = warehouseScope.status;
|
||
ctx.body = { code: warehouseScope.status, message: warehouseScope.message };
|
||
return;
|
||
}
|
||
|
||
// 校验明细关联商品均存在、已启用且与仓库同货主
|
||
const itemsOwner = await assertItemsOwner(ctx, items, warehouseScope.subsidiaryId);
|
||
if (!itemsOwner.ok) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: itemsOwner.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;
|
||
}
|
||
|
||
// 换仓库时:仓库需可访问,且单据已有明细必须与新仓库同货主(防止改仓库把单据挪到别的货主)
|
||
if (ctx.request.body.warehouse_id !== undefined
|
||
&& Number(ctx.request.body.warehouse_id) !== Number(order.warehouse_id)) {
|
||
const warehouseScope = await resolveWarehouse(ctx, ctx.request.body.warehouse_id);
|
||
if (!warehouseScope.ok) {
|
||
ctx.status = warehouseScope.status;
|
||
ctx.body = { code: warehouseScope.status, message: warehouseScope.message };
|
||
return;
|
||
}
|
||
const existingItems = await ctx.model.StockItem.findAll({
|
||
where: { bill_type: 2, bill_id: order.id, principal_id: ctx.state.principalId },
|
||
attributes: [ 'product_id', 'combo_product_id' ],
|
||
raw: true,
|
||
});
|
||
const itemsOwner = await assertItemsOwner(ctx, existingItems, warehouseScope.subsidiaryId);
|
||
if (!itemsOwner.ok) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: itemsOwner.message };
|
||
return;
|
||
}
|
||
}
|
||
|
||
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,
|
||
* 避免集中审核时把对方服务打满;也可用「推送」按钮立即推送(状态仍需为已审核)。
|
||
* 审核同时清空上一轮推送记录(重试计数归零)。**操作人 = 审核人**(无需表单传入,已入 MANAGED_FIELDS):
|
||
* `operator` 取审核人在本主体下的账号名称(`principal_users.name`,未配置时回退 users.nickname/username)。
|
||
* 推送失败的处理见 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;
|
||
}
|
||
// 操作人取审核人在本主体下的账号名称(principal_users.name)
|
||
const operatorName = await resolveAccountName(ctx, ctx.userId, order.principal_id);
|
||
// 清空上一轮推送记录(重试次数从 0 开始),进入推送队列等待定时任务自动推送
|
||
await order.update({ status: 2, operator: operatorName, pushed_at: null, wms_push_result: null });
|
||
ctx.body = {
|
||
code: 0,
|
||
message: '审核成功,已进入推送队列,稍后自动推送仓库',
|
||
data: { id: order.id, status: 2, operator: operatorName },
|
||
};
|
||
}
|
||
/**
|
||
* 推送:已审核(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 },
|
||
};
|
||
}
|
||
/**
|
||
* 完成出库:已推送(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)、或推送未成功但已锁定库存(stock_locked=1,如推送超时待重试)的单据:取消时释放锁定库存
|
||
if (order.status === 3 || Number(order.stock_locked) === 1) {
|
||
try {
|
||
await ctx.service.outboundOrderPush.unlockStock(order, null, '出库单取消释放锁定库存');
|
||
await order.update({ status: 9 });
|
||
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
|
||
} catch (err) {
|
||
ctx.logger.error(`[outbound] 取消释放锁定库存失败 id=${order.id}`, err);
|
||
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;
|
||
}
|
||
// 推送未成功但已锁定库存(如超时待重试):作废前释放,避免锁定无人释放
|
||
if (Number(order.stock_locked) === 1) {
|
||
try {
|
||
await ctx.service.outboundOrderPush.unlockStock(order, null, '出库单作废释放锁定库存');
|
||
} catch (err) {
|
||
ctx.logger.error(`[outbound] 作废释放锁定库存失败 id=${order.id}`, err);
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, 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) {
|
||
if (Number(order.stock_locked) === 1) {
|
||
try {
|
||
await ctx.service.outboundOrderPush.unlockStock(order, null, '出库单驳回释放锁定库存');
|
||
} catch (err) {
|
||
ctx.logger.error(`[outbound] 驳回释放锁定库存失败 id=${order.id}`, err);
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '驳回失败,请稍后重试' };
|
||
return;
|
||
}
|
||
}
|
||
const newBillNo = nextRejectedBillNo(order.bill_no, order.id, OUTBOUND_BILL_PREFIX);
|
||
// 清空推送痕迹(重新审核后重试计数从 0 开始)
|
||
await order.update({ status: 1, bill_no: newBillNo, pushed_at: null, wms_push_result: null });
|
||
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,
|
||
stock_locked: 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;
|