'use strict'; const { Controller } = require('egg'); const recalcStock = require('../utils/recalcStock'); const completeInbound = require('../utils/completeInbound'); const nextRejectedBillNo = require('../utils/rejectBillNo'); const { parsePagination, buildPageResult } = require('../lib/pagination'); const { resolveAccountName, resolveAccountNameMap } = require('../lib/accountProfile'); const { resolveWarehouse, assertItemsOwner, resolveAccess, ownSubsidiaryIds, isVisible } = require('../lib/billOwnerScope'); const QimenWmsClient = require('../lib/wms/qimenClient'); const { DEFAULT_INBOUND_ORDER_TYPE, INBOUND_ORDER_TYPE_LIST, normalizeInboundOrderType } = require('../lib/wms/orderTypes'); /** 仓库接口类型:当前系统仅对接类奇门JSON接口 */ const API_TYPE_QIMEN = 'qimen'; /** 入库单单号前缀,未提供单据号时由系统按 {前缀}_{自增id} 自动生成(如 RK_123) */ const INBOUND_BILL_PREFIX = 'RK'; /** 把可能为 JSON 字符串的字段归一化为对象(已为对象则原样返回),便于写入 JSON 列 */ function toJson(val) { if (val == null) return val; if (typeof val === 'string') { try { return JSON.parse(val); } catch { return val; } } return val; } /** 入库单上以 JSON 列承载的扩展字段 */ const INBOUND_JSON_FIELDS = [ 'sender_info', 'receiver_info', 'extend_props' ]; /** * WMS 返回的「外部入库单已存在」判定(重复推送) * 典型报文:`创建入库单失败,失败原因:\n入库单已存在,状态: CREATED` * 场景:已推送(3) 的单据被驳回(本地回退到待入库)后重新审核再推送, * 而 openapi 渠道没有入库单取消接口(entryorder.* 只有 create/query), * 外部单据仍占用同一个 entryOrderCode,重复 create 必然被拒。 * @param {Object} resp WMS 响应报文 * @return {boolean} 是否为「外部单据已存在」 */ function isDuplicateOrderResponse(resp) { const message = resp && resp.message != null ? String(resp.message) : ''; return /已存在/.test(message); } /** * WMS 明确反馈「该单据类型不支持取消」的判定 * 典型报文:openapi 渠道 `order.cancel` 对 RK 组返回「暂不支持该订单类型的取消操作」 * (openapiMethods/order.js 只实现 ORDER/CK 组);奇门渠道对未开发类型返回「…未开发完成」。 * 命中时按「渠道不支持取消」降级处理:仍允许驳回,但需人工在仓库侧处理外部单据。 * @param {Object} resp WMS 响应报文 * @return {boolean} 是否为渠道不支持取消 */ function isUnsupportedCancelResponse(resp) { const message = resp && resp.message != null ? String(resp.message) : ''; return /暂不支持该订单类型的取消操作|未开发完成/.test(message); } /** * 单号与状态/生命周期字段由系统与业务事务(创建 / 审核 / 推送 / 完成 / 驳回 / 作废 / 取消 / 库存回调)推动, * 禁止通过新增、更新等通用接口直接写入,避免破坏单据对外标识(WMS entryOrderCode=bill_no)或绕过状态机。 */ const MANAGED_FIELDS = [ 'bill_no', 'status', 'audit_by', 'audit_time', 'pushed_at', 'wms_push_result', 'void_at', 'void_by', 'void_reason', 'item_total', 'item_kind', // 操作人与操作员编码由审核流程写入(操作人=审核人,编码=审核人用户ID),不接受接口传入 'operator', 'operator_code', ]; /** * @controller InboundOrderController 入库单管理 * 单据头 inbound_orders;明细由 stock_items(bill_type=1)承载,随单据在同一事务内创建 */ class InboundOrderController extends Controller { /** * 越界保护:所在公司权限只能查看/操作自己所属公司(货主)的单据 * @param {Object} order 单据实例(未取 subsidiary_id 时会补查一次) * @return {Promise} true 有权;false 时已写入 403 响应 */ async _assertAccess(order) { const { ctx } = this; let subsidiaryId = order.subsidiary_id; if (subsidiaryId === undefined) { const fresh = await ctx.model.InboundOrder.findByPk(order.id, { attributes: [ 'subsidiary_id' ] }); subsidiaryId = fresh ? fresh.subsidiary_id : null; } const access = await resolveAccess(ctx); if (isVisible(access, subsidiaryId)) return true; ctx.status = 403; ctx.body = { code: 403, message: '该入库单不属于自己所属公司(货主),无权操作' }; return false; } /** * @summary 入库单列表 * @router get /api/inbound-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 inbound_type 入库类型(WMS 编码):B2BRK B2B入库 / SCRK 生产入库 / LYRK 领用入库 / CCRK 残次品入库 / CGRK 采购入库 / DBRK 调拨入库 / QTRK 其他入库 * @request query integer shop_id 店铺/仓库ID * @request query integer subsidiary_id 货主(下属公司ID),集团账号可按货主筛选 * @response 200 inboundOrderListResponse 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, inbound_type: inboundType, shop_id: shopId, subsidiary_id: subsidiaryId } = 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 (inboundType !== undefined && inboundType !== '') where.inbound_type = String(inboundType).trim().toUpperCase(); if (shopId) where.shop_id = Number(shopId); // 货主口径:所在公司权限只能看自己所属公司的单据 const access = await resolveAccess(ctx); const ownIds = ownSubsidiaryIds(access); if (ownIds) { if (!ownIds.length) { ctx.body = { code: 0, message: 'success', data: buildPageResult([], 0, { page, pageSize }) }; return; } where.subsidiary_id = subsidiaryId && ownIds.includes(Number(subsidiaryId)) ? Number(subsidiaryId) : { [Op.in]: ownIds }; } else if (subsidiaryId) { where.subsidiary_id = Number(subsidiaryId); } const { count, rows } = await ctx.model.InboundOrder.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.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }, { model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] }, { model: ctx.model.User, as: 'auditor', attributes: [ 'id', 'nickname', 'username' ] }, ], }); // 创建人 / 审核人展示员工名称(principal_users.name),避免昵称为空时回退成邮箱账号 const nameMap = await resolveAccountNameMap( ctx, rows.flatMap(row => [ row.created_by, row.audit_by ]), principalId ); const list = rows.map(row => { const plain = row.get({ plain: true }); plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : ''; plain.creator_name = nameMap.get(Number(plain.created_by)) || ''; plain.auditor_name = nameMap.get(Number(plain.audit_by)) || ''; return plain; }); ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; } /** * @summary 入库单详情 * @router get /api/inbound-orders/{id} * @apikey * @request path integer *id 入库单主键ID * @response 200 baseResponse success */ async show() { const { ctx } = this; const order = await ctx.model.InboundOrder.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.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }, { model: ctx.model.User, as: 'creator', attributes: [ 'id', 'nickname', 'username' ] }, { model: ctx.model.User, as: 'auditor', 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; } if (!await this._assertAccess(order)) return; const items = await ctx.model.StockItem.findAll({ where: { bill_type: 1, 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; // 创建人 / 审核人 / 作废人展示员工名称(principal_users.name),避免昵称为空时回退成邮箱账号 const nameMap = await resolveAccountNameMap(ctx, [ data.created_by, data.audit_by, data.void_by ], order.principal_id); data.subsidiary_name = data.subsidiary ? data.subsidiary.name : ''; data.creator_name = nameMap.get(Number(data.created_by)) || ''; data.auditor_name = nameMap.get(Number(data.audit_by)) || ''; data.voider_name = nameMap.get(Number(data.void_by)) || ''; ctx.body = { code: 0, message: 'success', data }; } /** * @summary 新增入库单 * @description 单号由系统按 RK_{自增id} 自动生成(不接受传入);仓库必填;可同时传入 items(stock_items, bill_type=1)一次性写入明细。 * 单据货主由仓库决定(warehouses.subsidiary_id),明细商品/组合必须与仓库同货主,否则拒绝创建 * @router post /api/inbound-orders * @apikey * @request body createInboundOrderRequest *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]; for (const f of INBOUND_JSON_FIELDS) payload[f] = toJson(payload[f]); // 入库单类型:直接落库 WMS 编码(RK 组),非法值拒绝;不传时默认 CGRK(采购入库) const inboundType = normalizeInboundOrderType(payload.inbound_type); if (payload.inbound_type != null && String(payload.inbound_type).trim() !== '' && !inboundType) { ctx.status = 400; ctx.body = { code: 400, message: `inbound_type(入库类型)不合法,支持:${INBOUND_ORDER_TYPE_LIST.join(' / ')}` }; return; } payload.inbound_type = inboundType || DEFAULT_INBOUND_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; const order = await ctx.model.InboundOrder.create({ status: 1, ...payload, bill_no: `RK_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`, principal_id: principalId, subsidiary_id: warehouseScope.subsidiaryId, 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: 1, 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_in_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 }); } // 系统生成单据号:RK_{自增id} await order.update({ bill_no: `${INBOUND_BILL_PREFIX}_${order.id}` }, { transaction }); await transaction.commit(); await recalcStock(ctx, 1, 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/inbound-orders/{id} * @apikey * @request path integer *id 入库单主键ID * @request body updateInboundOrderRequest *body * @response 200 baseResponse success */ async update() { const { ctx } = this; const order = await ctx.model.InboundOrder.findByPk(ctx.params.id); if (!order) { ctx.status = 404; ctx.body = { code: 404, message: '入库单不存在' }; return; } if (!await this._assertAccess(order)) 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; // 货主由仓库推导,不接受接口直接写入 delete ctx.request.body.subsidiary_id; for (const f of MANAGED_FIELDS) delete ctx.request.body[f]; for (const f of INBOUND_JSON_FIELDS) ctx.request.body[f] = toJson(ctx.request.body[f]); // 入库单类型:同样存储 WMS 编码(RK 组),非法值拒绝(影响后续推送与取消的口径一致) if (ctx.request.body.inbound_type != null && String(ctx.request.body.inbound_type).trim() !== '') { const inboundType = normalizeInboundOrderType(ctx.request.body.inbound_type); if (!inboundType) { ctx.status = 400; ctx.body = { code: 400, message: `inbound_type(入库类型)不合法,支持:${INBOUND_ORDER_TYPE_LIST.join(' / ')}` }; return; } ctx.request.body.inbound_type = inboundType; } else { delete ctx.request.body.inbound_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: 1, 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; } // 换仓库后单据货主跟随新仓库 ctx.request.body.subsidiary_id = warehouseScope.subsidiaryId; } await order.update(ctx.request.body); ctx.body = { code: 0, message: 'success', data: { id: order.id } }; } /** * @summary 删除入库单 * @description 物理删除单据,并级联删除其明细(stock_items, bill_type=1)。仅「待入库(1)」「已取消(9)」可删除; * 已审核(2) 及之后的单据禁止删除,请使用作废接口 * @router delete /api/inbound-orders/{id} * @apikey * @request path integer *id 入库单主键ID * @response 200 baseResponse success */ async destroy() { const { ctx } = this; const order = await ctx.model.InboundOrder.findByPk(ctx.params.id); if (!order) { ctx.status = 404; ctx.body = { code: 404, message: '入库单不存在' }; return; } if (!await this._assertAccess(order)) 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: 1, 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: '删除失败,请稍后重试' }; } } /* -------------------- 状态流转(按序校验) -------------------- */ async _transit(from, to, failMsg) { const { ctx } = this; const order = await ctx.model.InboundOrder.findByPk(ctx.params.id); if (!order) { ctx.status = 404; ctx.body = { code: 404, message: '入库单不存在' }; return; } if (!await this._assertAccess(order)) return; if (order.status !== from) { ctx.status = 400; ctx.body = { code: 400, message: failMsg }; return; } await order.update({ status: to }); ctx.body = { code: 0, message: 'success', data: { id: order.id } }; } /** * 审核:已创建(1) -> 已审核(2),并记录审核人与审核时间 * * **操作人 = 审核人**(无需表单传入,已入 MANAGED_FIELDS 接口不可写): * - `operator` 取审核人在**本主体下的账号名称**(`principal_users.name`,未配置时回退 users.nickname/username), * 推送时为 `entryOrder.operatorName` * - `operator_code` 直接取用户ID 字符串(WMS 入库单报文不支持该字段,仅本地留存) * @router post /api/inbound-orders/{id}/audit * @apikey * @request path integer *id 入库单主键ID * @response 200 baseResponse success */ async audit() { const { ctx } = this; const id = Number(ctx.params.id); const order = await ctx.model.InboundOrder.findByPk(id); if (!order) { ctx.status = 404; ctx.body = { code: 404, message: '入库单不存在' }; return; } if (!await this._assertAccess(order)) return; if (order.status !== 1) { ctx.status = 400; ctx.body = { code: 400, message: '只有「待入库」状态的单据可以审核' }; return; } const itemCount = await ctx.model.StockItem.count({ where: { bill_type: 1, 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); await order.update({ status: 2, audit_by: ctx.userId, audit_time: new Date(), operator: operatorName, operator_code: String(ctx.userId), }); ctx.body = { code: 0, message: 'success', data: { id: order.id, operator: operatorName, operator_code: String(ctx.userId) } }; } /** * 推送:已审核(2) -> 已推送(3),并将入库单递交 WMS(entryorder.create) * 失败时不流转状态,直接返回 WMS 错误信息; * 例外:WMS 返回「入库单已存在」时视为外部已建单,按已推送(3)补状态(`reused=true`), * 避免单据因外部单号被占用而卡在已审核(入库单无取消/更新接口) */ async push() { const { ctx } = this; const orderId = Number(ctx.params.id); const principalId = ctx.state.principalId; const order = await ctx.model.InboundOrder.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 (!await this._assertAccess(order)) 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: 1, bill_id: order.id }, include: [ { model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'retail_price' ] } ], order: [[ 'id', 'ASC' ]], }); // 无明细不允许推送(否则即使推送成功,完成时也不会产生任何库存) if (!items.length) { ctx.status = 400; ctx.body = { code: 400, message: '单据无明细,无法推送' }; return; } const client = new QimenWmsClient(api, this.app); const externalOrderCode = order.bill_no; // 明细行 itemId(WMS 商品主键):取该仓库已推送商品的 wms_item_id,未建档的商品不带该字段(WMS 降级按 itemCode 匹配) const Op = this.app.Sequelize.Op; const productIds = items.map(i => (i.product_id != null ? Number(i.product_id) : null)).filter(Boolean); const links = productIds.length ? await ctx.model.WarehouseProduct.findAll({ where: { principal_id: principalId, warehouse_id: order.warehouse_id, product_id: { [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); } try { const resp = await client.createEntryOrder(order, items, { warehouse: order.warehouse, creator: order.creator, wmsItemIdByProduct, }); const success = client.isSuccess(resp); const pushResult = { success, code: resp && resp.code, message: resp && resp.message, flag: resp && resp.flag, entryOrderCode: externalOrderCode, warehouseApiId: api.id, apiType: api.type, response: resp, pushedAt: new Date().toISOString(), inboundType: order.inbound_type, }; if (!success) { // 外部单据已存在(驳回后重推):入库单无取消接口,外部单据无法冲正、也不能重复创建, // 按「已推送」补状态,避免单据因单号被占用而永久卡在已审核(内容以仓库侧单据为准) if (isDuplicateOrderResponse(resp)) { const reusedResult = { ...pushResult, success: true, reused: true, reusedReason: '外部入库单已存在,已按「已推送」处理(明细以仓库侧单据为准)', }; await order.update({ status: 3, operate_time: new Date(), pushed_at: new Date(), wms_push_result: reusedResult, }); ctx.body = { code: 0, message: 'success', data: { id: order.id, reused: true, wms_response: resp }, }; return; } // 推送失败:保留失败结果供排查,不流转状态让用户可重试 // (WMS 未提供入库单取消接口,无法冲正外部单据) 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) { // 请求异常:记录失败结果与时间,状态保持「已审核」可重试(入库无外部取消接口) const failResult = { success: false, entryOrderCode: externalOrderCode, warehouseApiId: api.id, apiType: api.type, error: err.message, 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 }; } } /** 完成入库:已推送(3) -> 完成(4),并按明细增加系统库存(与 WMS entryorder.confirm 回调共用同一实现) */ async complete() { const { ctx } = this; const order = await ctx.model.InboundOrder.findByPk(ctx.params.id); if (!order) { ctx.status = 404; ctx.body = { code: 404, message: '入库单不存在' }; return; } if (!await this._assertAccess(order)) return; let result; try { result = await completeInbound(ctx, order); } catch (err) { ctx.status = 500; ctx.body = { code: 500, message: '完成入库失败,请稍后重试' }; return; } if (!result.ok) { ctx.status = result.code; ctx.body = { code: result.code, message: result.message }; return; } ctx.body = { code: 0, message: 'success', data: { id: order.id } }; } /** 取消:任意非完成态 -> 已取消(9) */ async cancel() { const { ctx } = this; const order = await ctx.model.InboundOrder.findByPk(ctx.params.id); if (!order) { ctx.status = 404; ctx.body = { code: 404, message: '入库单不存在' }; return; } if (!await this._assertAccess(order)) return; if (order.status === 4) { ctx.status = 400; ctx.body = { code: 400, 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.InboundOrder.findByPk(ctx.params.id); if (!order) { ctx.status = 404; ctx.body = { code: 404, message: '入库单不存在' }; return; } if (!await this._assertAccess(order)) 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/inbound-orders/{id}/void * @apikey * @request path integer *id 入库单主键ID * @request body voidInboundOrderRequest *body * @response 200 baseResponse success */ async voidOrder() { const { ctx } = this; const order = await ctx.model.InboundOrder.findByPk(ctx.params.id); if (!order) { ctx.status = 404; ctx.body = { code: 404, message: '入库单不存在' }; return; } if (!await this._assertAccess(order)) 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`); * 已推送(3) 的会先调 WMS `order.cancel`(orderCode=bill_no,orderType=落库的入库单类型)取消外部入库单, * **外部取消失败则驳回失败、单据保持原状态**(不在外部仍存在的情况下回退本地单据) * @router post /api/inbound-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.InboundOrder.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 (!await this._assertAccess(order)) 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, INBOUND_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); const cancel = { attempted: true, success: false, orderType: order.inbound_type }; let resp; try { resp = await client.cancelInboundOrder(order); } catch (err) { // 请求异常:无法确认外部单据是否已取消,驳回失败并保持原状态供用户重试(与出库单口径一致) ctx.status = 502; ctx.body = { code: 502, message: `取消外部入库单失败:${err.message}` }; return; } cancel.code = resp && resp.code; cancel.message = resp && resp.message; cancel.success = client.isSuccess(resp); if (!cancel.success) { // 外部取消失败(含渠道不支持该类型取消):不允许驳回,单据保持「已推送」不变 const hint = isUnsupportedCancelResponse(resp) ? '(当前渠道不支持入库单取消,请先在 WMS 侧处理该外部单据)' : ''; ctx.logger.warn(`[inbound-reject] 取消外部入库单失败,入库单 ${order.bill_no}(类型 ${order.inbound_type})保持原状态:${cancel.message}`); ctx.status = 502; ctx.body = { code: 502, message: `取消外部入库单失败:${resp && (resp.message || resp.code)}${hint}` }; return; } // 回到待入库(单号换新,避免再用已被外部占用的单号);清空推送记录(原推送结果不再成立,调用历史见对外 API 日志) const newBillNo = nextRejectedBillNo(order.bill_no, order.id, INBOUND_BILL_PREFIX); 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, cancel } }; } } module.exports = InboundOrderController;