'use strict'; const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); const QimenWmsClient = require('../lib/wms/qimenClient'); const { applyStockChange } = require('../utils/stockRecord'); /** 仓库接口类型:当前系统仅对接类奇门JSON接口 */ const API_TYPE_QIMEN = 'qimen'; /** * @controller WarehouseProductController 仓库-商品关联 * 关联表(warehouse_products)只记录商品是否已推送到某个仓库; * 列表以商品为主体左关联出推送状态,未建立关联的商品即「未推送」 */ class WarehouseProductController extends Controller { /** * @summary 仓库下的商品列表(含是否已推送状态) * @description 以当前主体下的商品为主体,左关联 warehouse_products 得出该仓库的推送状态; * 未建立关联的商品视为未推送;仓库或接口配置被删除时其关联数据会被清空 * @router get /api/warehouses/{id}/products * @apikey * @request path integer *id 仓库主键ID * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 * @request query string keyword 关键词,匹配商品编码/货物编码/条码/商品名称 * @response 200 warehouseProductListResponse success */ async index() { const { ctx } = this; const Op = this.app.Sequelize.Op; const warehouseId = Number(ctx.params.id); const principalId = ctx.state.principalId; const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { keyword, pushed } = ctx.query; const where = { principal_id: principalId }; // 库存标签页:仅返回已推送到该仓库(已同步)的商品 if (pushed === '1' || pushed === 1 || pushed === true || pushed === 'true') { const pushedLinks = await ctx.model.WarehouseProduct.findAll({ where: { warehouse_id: warehouseId, principal_id: principalId, pushed: 1 }, attributes: [ 'product_id' ], }); const pushedIds = pushedLinks.map(l => Number(l.product_id)); where.id = { [Op.in]: pushedIds }; } if (keyword) { where[Op.or] = [ { item_code: { [Op.like]: `%${keyword}%` } }, { goods_code: { [Op.like]: `%${keyword}%` } }, { barcode: { [Op.like]: `%${keyword}%` } }, { item_name: { [Op.like]: `%${keyword}%` } }, ]; } const { count, rows } = await ctx.model.Product.findAndCountAll({ where, offset, limit, order: [[ 'id', 'DESC' ]], }); // 关联数据按当前页商品批量取出再合并:避免 hasMany include 影响分页语义 const productIds = rows.map(row => Number(row.id)); const links = productIds.length ? await ctx.model.WarehouseProduct.findAll({ where: { warehouse_id: warehouseId, product_id: { [Op.in]: productIds } }, attributes: [ 'product_id', 'pushed', 'pushed_at', 'wms_item_id' ], }) : []; const linkMap = new Map(links.map(link => [ Number(link.product_id), link ])); // 一并带出系统库存(副表 product_stocks,按 item_type 分多行:ZC=正品 / CC=残次品) const stocks = productIds.length ? await ctx.model.ProductStock.findAll({ where: { principal_id: principalId, product_id: { [Op.in]: productIds } }, attributes: [ 'product_id', 'item_type', 'quantity', 'lock_quantity', 'available' ], }) : []; const stockMap = new Map(); for (const s of stocks) { const pid = Number(s.product_id); if (!stockMap.has(pid)) stockMap.set(pid, {}); stockMap.get(pid)[s.item_type] = s; } const list = rows.map(row => { const item = row.get({ plain: true }); const link = linkMap.get(Number(item.id)); const stockRows = stockMap.get(Number(item.id)) || {}; const zc = stockRows['ZC']; const cc = stockRows['CC']; return { id: item.id, item_code: item.item_code, goods_code: item.goods_code, item_name: item.item_name, sku_property: item.sku_property, barcode: item.barcode, image: item.image, status: item.status, pushed: link ? Number(link.pushed) === 1 : false, pushed_at: link ? link.pushed_at : null, wms_item_id: link ? link.wms_item_id : null, // 正品库存(ZC) good_quantity: zc ? Number(zc.quantity) : 0, good_lock_quantity: zc ? Number(zc.lock_quantity) : 0, good_available: zc ? Number(zc.available) : 0, // 残次品库存(CC) defect_quantity: cc ? Number(cc.quantity) : 0, defect_lock_quantity: cc ? Number(cc.lock_quantity) : 0, defect_available: cc ? Number(cc.available) : 0, }; }); ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; } /** * @summary 商品资料推送(推送到仓库 WMS) * @description 将指定商品推送到该仓库的 WMS(类奇门JSON接口 singleitem.synchronize); * 推送成功的商品在 warehouse_products 标记 pushed=1;逐个推送并汇总结果 * @router post /api/warehouses/{id}/products/push * @apikey * @request path integer *id 仓库主键ID * @request body warehouseProductPushRequest *body * @response 200 warehouseProductPushResponse success */ async push() { const { ctx } = this; const warehouseId = Number(ctx.params.id); const principalId = ctx.state.principalId; const { product_ids: productIds } = ctx.request.body || {}; if (!Array.isArray(productIds) || productIds.length === 0) { ctx.status = 400; ctx.body = { code: 400, message: 'product_ids 不能为空' }; return; } // 取该仓库下启用的类奇门接口配置(优先第一条) const api = await ctx.model.WarehouseApi.findOne({ where: { warehouse_id: warehouseId, 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 results = []; let success = 0; for (const pid of productIds) { const product = await ctx.model.Product.findOne({ where: { id: Number(pid), principal_id: principalId }, }); if (!product) { results.push({ product_id: Number(pid), success: false, message: '商品不存在或不属于当前主体' }); continue; } try { const resp = await client.pushItem(product); if (client.isSuccess(resp)) { success += 1; const wmsItemId = QimenWmsClient.extractItemId(resp); const [ link, created ] = await ctx.model.WarehouseProduct.findOrCreate({ where: { warehouse_id: warehouseId, product_id: product.id }, defaults: { principal_id: principalId, pushed: 1, pushed_at: new Date(), wms_item_id: wmsItemId }, }); if (!created) await link.update({ pushed: 1, pushed_at: new Date(), wms_item_id: wmsItemId }); results.push({ product_id: product.id, item_code: product.item_code, success: true, message: resp.message || '推送成功' }); } else { results.push({ product_id: product.id, item_code: product.item_code, success: false, message: `WMS 返回失败: ${resp.message || resp.code}` }); } } catch (err) { results.push({ product_id: product.id, item_code: product.item_code, success: false, message: err.message }); } } ctx.body = { code: 0, message: 'success', data: { total: productIds.length, success, failed: productIds.length - success, results }, }; } async wmsInventory() { const { ctx } = this; const warehouseId = Number(ctx.params.id); const principalId = ctx.state.principalId; const Op = this.app.Sequelize.Op; const { product_ids: productIds } = ctx.request.body || {}; // 取该仓库下启用的类奇门接口配置(优先第一条) const api = await ctx.model.WarehouseApi.findOne({ where: { warehouse_id: warehouseId, 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; } // 取已推送的关联记录(wms_item_id 可能为空:推送发生在字段上线之前) const where = { warehouse_id: warehouseId, principal_id: principalId, pushed: 1 }; if (Array.isArray(productIds) && productIds.length) { where.product_id = { [Op.in]: productIds.map(Number) }; } const links = await ctx.model.WarehouseProduct.findAll({ where, attributes: [ 'id', 'product_id', 'wms_item_id' ], }); if (!links.length) { ctx.body = { code: 0, message: 'success', data: { inventories: {} } }; return; } const client = new QimenWmsClient(api, this.app); const itemIdToProductId = {}; const itemIds = []; const needSync = []; for (const link of links) { if (link.wms_item_id != null) { const itemId = Number(link.wms_item_id); itemIdToProductId[itemId] = Number(link.product_id); itemIds.push(itemId); } else { needSync.push(link); } } // 未记录 wms_item_id 的(多为早期推送),用 itemCode 重新同步一次取回 WMS 内部 itemId(幂等,会写 openapi 日志) if (needSync.length) { const pidList = needSync.map(l => Number(l.product_id)); const products = await ctx.model.Product.findAll({ where: { id: { [Op.in]: pidList } } }); const productMap = new Map(products.map(p => [ Number(p.id), p ])); for (const link of needSync) { const product = productMap.get(Number(link.product_id)); if (!product) continue; try { const resp = await client.pushItem(product); const wmsItemId = QimenWmsClient.extractItemId(resp); if (wmsItemId != null) { await link.update({ wms_item_id: wmsItemId }); const itemId = Number(wmsItemId); itemIdToProductId[itemId] = Number(link.product_id); itemIds.push(itemId); } else { ctx.logger.warn(`[wmsInventory] 商品 ${link.product_id} 重新同步未返回 itemId`); } } catch (err) { ctx.logger.warn(`[wmsInventory] 商品 ${link.product_id} 重新同步失败:${err.message}`); } } } if (!itemIds.length) { ctx.body = { code: 0, message: 'success', data: { inventories: {} } }; return; } // 批量查询 WMS 库存(会写 openapi 日志) let items = []; try { items = await client.queryInventory(itemIds); } catch (err) { ctx.status = 502; ctx.body = { code: 502, message: err.message }; return; } const inventories = {}; for (const it of items) { const itemId = Number(it.itemId); const pid = itemIdToProductId[itemId]; if (!pid) continue; const quantity = Number(it.quantity) || 0; const lockQuantity = Number(it.lockQuantity) || 0; const defectQuantity = Number(it.defectQuantity) || 0; const defectLockQuantity = Number(it.defectLockQuantity) || 0; inventories[pid] = { item_id: itemId, good_quantity: quantity, good_lock_quantity: lockQuantity, good_available: Math.max(0, quantity - lockQuantity), defect_quantity: defectQuantity, defect_lock_quantity: defectLockQuantity, defect_available: Math.max(0, defectQuantity - defectLockQuantity), }; } ctx.body = { code: 0, message: 'success', data: { inventories } }; } /** * 库存同步:将系统库存覆盖为「外部 WMS 库存」(按正品 / 残次品两个维度分别比较) * 对每个维度:系统数量 < 外部 => 已完成入库单(增加系统库存)+ 出入库记录(inbound_increase) * 系统数量 > 外部 => 已完成出库单(减少系统库存,仅减总数量不动锁定)+ 出入库记录(inventory_sync_out) * 相等 => 跳过 * 出入库单、出入库明细、库存余量变动与出入库记录在同一事务内完成,保证账实一致 * @router post /api/warehouses/{id}/inventory/sync * @apikey * @request path integer *id 仓库主键ID * @request body warehouseInventorySyncRequest *body * @response 200 baseResponse success */ async syncInventory() { const { ctx } = this; const warehouseId = Number(ctx.params.id); const principalId = ctx.state.principalId; const items = (ctx.request.body && ctx.request.body.items) || []; if (!Array.isArray(items) || items.length === 0) { ctx.status = 400; ctx.body = { code: 400, message: 'items 不能为空' }; return; } // 过滤出合法的「商品ID + 外部WMS 正品/残次数量」 const valid = items .map(it => ({ product_id: Number(it.product_id), wms_good_quantity: Number(it.wms_good_quantity), wms_defect_quantity: Number(it.wms_defect_quantity), })) .filter(it => it.product_id && (!Number.isNaN(it.wms_good_quantity) || !Number.isNaN(it.wms_defect_quantity))); if (!valid.length) { ctx.status = 400; ctx.body = { code: 400, message: '未找到有效的 product_id / wms 数量' }; return; } const productIds = [ ...new Set(valid.map(v => v.product_id)) ]; const products = await ctx.model.Product.findAll({ where: { id: { [ctx.app.Sequelize.Op.in]: productIds }, principal_id: principalId, status: 1 }, attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], }); const productMap = new Map(products.map(p => [ Number(p.id), p ])); const stocks = await ctx.model.ProductStock.findAll({ where: { principal_id: principalId, product_id: { [ctx.app.Sequelize.Op.in]: productIds } }, }); const stockMap = new Map(); for (const s of stocks) { const pid = Number(s.product_id); if (!stockMap.has(pid)) stockMap.set(pid, {}); stockMap.get(pid)[s.item_type] = s; } let inboundCount = 0; let outboundCount = 0; let skipped = 0; const created = []; const transaction = await ctx.model.transaction(); try { // 对单个维度(正品 / 残次品)做一次同步:各自生成入/出库单,并写一条出入库记录 const syncPair = async (product, systemQty, wmsQty, kindLabel, itemType) => { const diff = wmsQty - systemQty; if (Math.abs(diff) < 1e-9) { skipped += 1; return; } // 相同不处理 const billNo = await this.genSyncBillNo(principalId); const qty = Math.abs(diff); const remark = `库存同步(${kindLabel} WMS ${wmsQty} vs 系统 ${systemQty})`; const baseItem = { principal_id: principalId, shop_id: null, product_id: product.id, name: product.item_name, code: product.item_code, spec: product.sku_property, inventory_type: itemType === 'CC' ? 'CC' : 'ZP', quantity: qty, total_amount: 0, }; if (diff > 0) { const order = await ctx.model.InboundOrder.create({ bill_no: billNo, principal_id: principalId, warehouse_id: warehouseId, inbound_type: 'QTRK', status: 4, operator: '库存同步', created_by: ctx.userId, remark, item_total: qty, item_kind: 1, total_amount: 0, }, { transaction }); await ctx.model.StockItem.create({ ...baseItem, bill_type: 1, bill_id: order.id }, { transaction }); // 增加系统库存并写一条「入库确认增加」出入库记录(与库存变动同事务) await applyStockChange(ctx, { bizType: 'inbound_increase', principalId, warehouseId, productId: product.id, itemCode: product.item_code, itemName: product.item_name, itemType, quantity: qty, billId: order.id, billNo: order.bill_no, createdBy: ctx.userId, remark, transaction, }); inboundCount += 1; created.push({ type: 'inbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty }); } else { const order = await ctx.model.OutboundOrder.create({ bill_no: billNo, principal_id: principalId, warehouse_id: warehouseId, outbound_type: 'QTCK', status: 4, customer: '库存同步', operator: '库存同步', created_by: ctx.userId, remark, item_total: qty, item_kind: 1, total_amount: 0, }, { transaction }); await ctx.model.StockItem.create({ ...baseItem, bill_type: 2, bill_id: order.id }, { transaction }); // 仅减少系统库存总数量(不动锁定),并写一条「库存同步出库」出入库记录(与库存变动同事务) await applyStockChange(ctx, { bizType: 'inventory_sync_out', principalId, warehouseId, productId: product.id, itemCode: product.item_code, itemName: product.item_name, itemType, quantity: qty, billId: order.id, billNo: order.bill_no, createdBy: ctx.userId, remark, transaction, }); outboundCount += 1; created.push({ type: 'outbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty }); } }; for (const it of valid) { const product = productMap.get(it.product_id); if (!product) { skipped += 1; continue; } // 商品不存在/禁用,跳过 const stockRows = stockMap.get(it.product_id) || {}; const systemGood = stockRows['ZC'] ? Number(stockRows['ZC'].quantity) : 0; const systemDefect = stockRows['CC'] ? Number(stockRows['CC'].quantity) : 0; // 正品维度 await syncPair(product, systemGood, it.wms_good_quantity, '正品', 'ZC'); // 残次品维度 await syncPair(product, systemDefect, it.wms_defect_quantity, '残次品', 'CC'); } await transaction.commit(); ctx.body = { code: 0, message: 'success', data: { inbound_count: inboundCount, outbound_count: outboundCount, skipped, created }, }; } catch (err) { await transaction.rollback(); ctx.logger.error('[syncInventory] 失败', err); ctx.status = 500; ctx.body = { code: 500, message: '库存同步失败,请稍后重试' }; } } /** 生成同步专用单号,保证唯一(重试) */ async genSyncBillNo(principalId) { const { ctx } = this; const pad = n => String(n).padStart(2, '0'); for (let i = 0; i < 5; i++) { const d = new Date(); const ts = `${pad(d.getFullYear() % 100)}${pad(d.getMonth() + 1)}${pad(d.getDate())}${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`; const rand = Math.floor(1000 + Math.random() * 9000); const billNo = `SYNC${ts}${rand}`; const exist = await ctx.model.InboundOrder.findOne({ where: { bill_no: billNo } }) || await ctx.model.OutboundOrder.findOne({ where: { bill_no: billNo } }); if (!exist) return billNo; } return `SYNC${Date.now()}${Math.floor(Math.random() * 10000)}`; } } module.exports = WarehouseProductController;