- 新增 groupScope 中间件:接口配置、字段、快递映射、调用日志仅集团权限可用,仓库维护只读放行 - 仓库列表/下拉/详情限定为自己所属公司(货主),越权访问返回 403 - 仓库商品与库存仅展示、推送、同步该仓库所属货主的商品,越界商品直接拒绝 - 「外部仓库」页在所在公司范围下收起新增/导出/接口配置/操作列与无关标签页,默认进入商品页 - 所属公司文案统一为「货主」 - 库存同步结果按商品统计(skipped/skipped_kinds/invalid_count),提示改为「N 个商品数量一致无需同步」 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
608 lines
25 KiB
JavaScript
608 lines
25 KiB
JavaScript
'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 };
|
||
|
||
// 所在公司权限:仅可操作自己所属公司的仓库
|
||
const access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
const warehouse = await this.findAccessibleWarehouse(warehouseId, principalId, access);
|
||
if (!warehouse) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, message: '仅可操作自己所属公司的仓库' };
|
||
return;
|
||
}
|
||
// 仓库下的商品只能是该仓库所属货主(下属公司)的商品
|
||
if (warehouse.subsidiary_id != null) {
|
||
where.subsidiary_id = Number(warehouse.subsidiary_id);
|
||
} else if (!access.isGroup) {
|
||
where.subsidiary_id = { [Op.in]: access.ownCompanyIds };
|
||
}
|
||
|
||
// 库存标签页:仅返回已推送到该仓库(已同步)的商品
|
||
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 access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
const warehouse = await this.findAccessibleWarehouse(warehouseId, principalId, access);
|
||
if (!warehouse) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, message: '仅可操作自己所属公司的仓库' };
|
||
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;
|
||
}
|
||
if (!access.isGroup && !access.ownCompanyIds.includes(Number(product.subsidiary_id))) {
|
||
results.push({ product_id: product.id, item_code: product.item_code, success: false, message: '只能推送自己所属公司(货主)的商品' });
|
||
continue;
|
||
}
|
||
// 仓库只能推送该仓库所属货主(下属公司)的商品
|
||
if (warehouse.subsidiary_id != null && Number(product.subsidiary_id) !== Number(warehouse.subsidiary_id)) {
|
||
results.push({ product_id: product.id, item_code: product.item_code, 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 access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
const warehouse = await this.findAccessibleWarehouse(warehouseId, principalId, access);
|
||
if (!warehouse) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, message: '仅可操作自己所属公司的仓库' };
|
||
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 productWhere = { principal_id: principalId };
|
||
if (warehouse.subsidiary_id != null) {
|
||
productWhere.subsidiary_id = Number(warehouse.subsidiary_id);
|
||
} else if (!access.isGroup) {
|
||
productWhere.subsidiary_id = { [Op.in]: access.ownCompanyIds };
|
||
}
|
||
const allowedProducts = await ctx.model.Product.findAll({
|
||
where: productWhere,
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
const allowedIds = allowedProducts.map(row => Number(row.id));
|
||
const requestedIds = Array.isArray(productIds) && productIds.length ? productIds.map(Number) : null;
|
||
|
||
// 取已推送的关联记录(wms_item_id 可能为空:推送发生在字段上线之前)
|
||
const where = { warehouse_id: warehouseId, principal_id: principalId, pushed: 1 };
|
||
where.product_id = {
|
||
[Op.in]: requestedIds ? allowedIds.filter(id => requestedIds.includes(id)) : allowedIds,
|
||
};
|
||
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 access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
const warehouse = await this.findAccessibleWarehouse(warehouseId, principalId, access);
|
||
if (!warehouse) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, message: '仅可操作自己所属公司的仓库' };
|
||
return;
|
||
}
|
||
const productWhere = { id: { [ctx.app.Sequelize.Op.in]: productIds }, principal_id: principalId, status: 1 };
|
||
// 只能同步该仓库所属货主(下属公司)的商品库存
|
||
if (warehouse.subsidiary_id != null) {
|
||
productWhere.subsidiary_id = Number(warehouse.subsidiary_id);
|
||
} else if (!access.isGroup) {
|
||
productWhere.subsidiary_id = { [ctx.app.Sequelize.Op.in]: access.ownCompanyIds };
|
||
}
|
||
const products = await ctx.model.Product.findAll({
|
||
where: productWhere,
|
||
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
|
||
});
|
||
const productMap = new Map(products.map(p => [ Number(p.id), p ]));
|
||
if (!products.length) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '所选商品不属于该仓库的货主,无法同步' };
|
||
return;
|
||
}
|
||
|
||
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;
|
||
// skipped:正品/残次品数量都与系统一致、无需处理的商品数
|
||
let skippedProducts = 0;
|
||
// skipped_kinds:跳过的库存维度数(每个商品含正品、残次品两个维度)
|
||
let skippedKinds = 0;
|
||
// invalid_count:不存在 / 已禁用 / 不属于该仓库货主的商品数
|
||
let invalidCount = 0;
|
||
const created = [];
|
||
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
// 对单个维度(正品 / 残次品)做一次同步:各自生成入/出库单,并写一条出入库记录
|
||
// @return {Promise<boolean>} 是否产生了库存变动(数量一致返回 false)
|
||
const syncPair = async (product, systemQty, wmsQty, kindLabel, itemType) => {
|
||
const diff = wmsQty - systemQty;
|
||
if (Math.abs(diff) < 1e-9) { skippedKinds += 1; return false; } // 相同不处理
|
||
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 });
|
||
return true;
|
||
}
|
||
|
||
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 });
|
||
return true;
|
||
};
|
||
|
||
for (const it of valid) {
|
||
const product = productMap.get(it.product_id);
|
||
if (!product) { invalidCount += 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;
|
||
// 正品维度
|
||
const goodChanged = await syncPair(product, systemGood, it.wms_good_quantity, '正品', 'ZC');
|
||
// 残次品维度
|
||
const defectChanged = await syncPair(product, systemDefect, it.wms_defect_quantity, '残次品', 'CC');
|
||
// 两个维度都没有变动,记为「数量一致」
|
||
if (!goodChanged && !defectChanged) skippedProducts += 1;
|
||
}
|
||
await transaction.commit();
|
||
ctx.body = {
|
||
code: 0,
|
||
message: 'success',
|
||
data: {
|
||
inbound_count: inboundCount,
|
||
outbound_count: outboundCount,
|
||
skipped: skippedProducts,
|
||
skipped_kinds: skippedKinds,
|
||
invalid_count: invalidCount,
|
||
created,
|
||
},
|
||
};
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.logger.error('[syncInventory] 失败', err);
|
||
ctx.status = 500;
|
||
ctx.body = { code: 500, message: '库存同步失败,请稍后重试' };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 所在公司权限:校验仓库是否可访问(不存在或不属于自己所属公司返回 null)
|
||
* @param {number} warehouseId 仓库ID
|
||
* @param {number} principalId 主体ID
|
||
* @param {Object} access 权限上下文
|
||
* @return {Promise<Object|null>} 仓库 model 实例
|
||
*/
|
||
async findAccessibleWarehouse(warehouseId, principalId, access) {
|
||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) return null;
|
||
const warehouse = await this.ctx.model.Warehouse.findOne({
|
||
where: { id: warehouseId, principal_id: principalId },
|
||
attributes: [ 'id', 'subsidiary_id' ],
|
||
});
|
||
if (!warehouse) return null;
|
||
if (!access.isGroup && !access.ownCompanyIds.includes(Number(warehouse.subsidiary_id))) return null;
|
||
return warehouse;
|
||
}
|
||
|
||
/**
|
||
* 生成同步专用单号,保证唯一(重试)
|
||
* @param principalId
|
||
*/
|
||
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;
|