feat(warehouse): 外部仓库货主权限收敛与库存同步口径

- 新增 groupScope 中间件:接口配置、字段、快递映射、调用日志仅集团权限可用,仓库维护只读放行
- 仓库列表/下拉/详情限定为自己所属公司(货主),越权访问返回 403
- 仓库商品与库存仅展示、推送、同步该仓库所属货主的商品,越界商品直接拒绝
- 「外部仓库」页在所在公司范围下收起新增/导出/接口配置/操作列与无关标签页,默认进入商品页
- 所属公司文案统一为「货主」
- 库存同步结果按商品统计(skipped/skipped_kinds/invalid_count),提示改为「N 个商品数量一致无需同步」

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-05 00:50:49 +08:00
parent b4b7c56729
commit b59ca6a0a8
6 changed files with 360 additions and 78 deletions

View File

@ -47,6 +47,19 @@ class WarehouseController extends Controller {
if (status !== undefined && status !== '') where.status = Number(status); if (status !== undefined && status !== '') where.status = Number(status);
if (subsidiaryId !== undefined && subsidiaryId !== '') where.subsidiary_id = Number(subsidiaryId); if (subsidiaryId !== undefined && subsidiaryId !== '') where.subsidiary_id = Number(subsidiaryId);
// 所在公司权限:仓库列表仅展示自己所属公司(货主)的仓库
const access = await ctx.service.access.resolve(ctx.userId, principalId);
if (!access.isGroup) {
if (where.subsidiary_id !== undefined) {
if (!access.ownCompanyIds.includes(Number(where.subsidiary_id))) {
ctx.body = { code: 0, message: 'success', data: buildPageResult([], 0, { page, pageSize }) };
return;
}
} else {
where.subsidiary_id = { [Op.in]: access.ownCompanyIds };
}
}
const { count, rows } = await ctx.model.Warehouse.findAndCountAll({ const { count, rows } = await ctx.model.Warehouse.findAndCountAll({
where, where,
offset, offset,
@ -110,8 +123,14 @@ class WarehouseController extends Controller {
*/ */
async select() { async select() {
const { ctx } = this; const { ctx } = this;
const Op = this.app.Sequelize.Op;
const where = { principal_id: ctx.state.principalId, status: 1, deleted_at: null };
// 所在公司权限:下拉仅展示自己所属公司的仓库
const access = await ctx.service.access.resolve(ctx.userId, ctx.state.principalId);
if (!access.isGroup) where.subsidiary_id = { [Op.in]: access.ownCompanyIds };
const rows = await ctx.model.Warehouse.findAll({ const rows = await ctx.model.Warehouse.findAll({
where: { principal_id: ctx.state.principalId, status: 1, deleted_at: null }, where,
attributes: [ 'id', 'code', 'name', 'subsidiary_id' ], attributes: [ 'id', 'code', 'name', 'subsidiary_id' ],
order: [[ 'id', 'DESC' ]], order: [[ 'id', 'DESC' ]],
}); });
@ -138,6 +157,14 @@ class WarehouseController extends Controller {
ctx.body = { code: 404, message: '仓库不存在' }; ctx.body = { code: 404, message: '仓库不存在' };
return; return;
} }
// 所在公司权限:只能查看自己所属公司的仓库详情
const access = await ctx.service.access.resolve(ctx.userId, ctx.state.principalId);
if (!access.isGroup && !access.ownCompanyIds.includes(Number(w.subsidiary_id))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可查看自己所属公司的仓库' };
return;
}
const warehouseId = w.id; const warehouseId = w.id;
const [ apiCount, apiEnabledCount, inboundCount, outboundCount ] = await Promise.all([ const [ apiCount, apiEnabledCount, inboundCount, outboundCount ] = await Promise.all([
ctx.model.WarehouseApi.count({ where: { warehouse_id: warehouseId } }), ctx.model.WarehouseApi.count({ where: { warehouse_id: warehouseId } }),

View File

@ -36,6 +36,21 @@ class WarehouseProductController extends Controller {
const where = { principal_id: principalId }; 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') { if (pushed === '1' || pushed === 1 || pushed === true || pushed === 'true') {
const pushedLinks = await ctx.model.WarehouseProduct.findAll({ const pushedLinks = await ctx.model.WarehouseProduct.findAll({
@ -89,8 +104,8 @@ class WarehouseProductController extends Controller {
const item = row.get({ plain: true }); const item = row.get({ plain: true });
const link = linkMap.get(Number(item.id)); const link = linkMap.get(Number(item.id));
const stockRows = stockMap.get(Number(item.id)) || {}; const stockRows = stockMap.get(Number(item.id)) || {};
const zc = stockRows['ZC']; const zc = stockRows.ZC;
const cc = stockRows['CC']; const cc = stockRows.CC;
return { return {
id: item.id, id: item.id,
item_code: item.item_code, item_code: item.item_code,
@ -139,6 +154,15 @@ class WarehouseProductController extends Controller {
return; 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({ const api = await ctx.model.WarehouseApi.findOne({
where: { warehouse_id: warehouseId, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 }, where: { warehouse_id: warehouseId, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
@ -162,6 +186,15 @@ class WarehouseProductController extends Controller {
results.push({ product_id: Number(pid), success: false, message: '商品不存在或不属于当前主体' }); results.push({ product_id: Number(pid), success: false, message: '商品不存在或不属于当前主体' });
continue; 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 { try {
const resp = await client.pushItem(product); const resp = await client.pushItem(product);
if (client.isSuccess(resp)) { if (client.isSuccess(resp)) {
@ -195,6 +228,15 @@ class WarehouseProductController extends Controller {
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
const { product_ids: productIds } = ctx.request.body || {}; 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({ const api = await ctx.model.WarehouseApi.findOne({
where: { warehouse_id: warehouseId, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 }, where: { warehouse_id: warehouseId, principal_id: principalId, type: API_TYPE_QIMEN, status: 1 },
@ -206,11 +248,26 @@ class WarehouseProductController extends Controller {
return; 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 可能为空:推送发生在字段上线之前) // 取已推送的关联记录(wms_item_id 可能为空:推送发生在字段上线之前)
const where = { warehouse_id: warehouseId, principal_id: principalId, pushed: 1 }; const where = { warehouse_id: warehouseId, principal_id: principalId, pushed: 1 };
if (Array.isArray(productIds) && productIds.length) { where.product_id = {
where.product_id = { [Op.in]: productIds.map(Number) }; [Op.in]: requestedIds ? allowedIds.filter(id => requestedIds.includes(id)) : allowedIds,
} };
const links = await ctx.model.WarehouseProduct.findAll({ const links = await ctx.model.WarehouseProduct.findAll({
where, where,
attributes: [ 'id', 'product_id', 'wms_item_id' ], attributes: [ 'id', 'product_id', 'wms_item_id' ],
@ -336,11 +393,31 @@ class WarehouseProductController extends Controller {
} }
const productIds = [ ...new Set(valid.map(v => v.product_id)) ]; 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({ const products = await ctx.model.Product.findAll({
where: { id: { [ctx.app.Sequelize.Op.in]: productIds }, principal_id: principalId, status: 1 }, where: productWhere,
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
}); });
const productMap = new Map(products.map(p => [ Number(p.id), p ])); 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({ const stocks = await ctx.model.ProductStock.findAll({
where: { principal_id: principalId, product_id: { [ctx.app.Sequelize.Op.in]: productIds } }, where: { principal_id: principalId, product_id: { [ctx.app.Sequelize.Op.in]: productIds } },
@ -354,15 +431,21 @@ class WarehouseProductController extends Controller {
let inboundCount = 0; let inboundCount = 0;
let outboundCount = 0; let outboundCount = 0;
let skipped = 0; // skipped:正品/残次品数量都与系统一致、无需处理的商品数
let skippedProducts = 0;
// skipped_kinds:跳过的库存维度数(每个商品含正品、残次品两个维度)
let skippedKinds = 0;
// invalid_count:不存在 / 已禁用 / 不属于该仓库货主的商品数
let invalidCount = 0;
const created = []; const created = [];
const transaction = await ctx.model.transaction(); const transaction = await ctx.model.transaction();
try { try {
// 对单个维度(正品 / 残次品)做一次同步:各自生成入/出库单,并写一条出入库记录 // 对单个维度(正品 / 残次品)做一次同步:各自生成入/出库单,并写一条出入库记录
// @return {Promise<boolean>} 是否产生了库存变动(数量一致返回 false)
const syncPair = async (product, systemQty, wmsQty, kindLabel, itemType) => { const syncPair = async (product, systemQty, wmsQty, kindLabel, itemType) => {
const diff = wmsQty - systemQty; const diff = wmsQty - systemQty;
if (Math.abs(diff) < 1e-9) { skipped += 1; return; } // 相同不处理 if (Math.abs(diff) < 1e-9) { skippedKinds += 1; return false; } // 相同不处理
const billNo = await this.genSyncBillNo(principalId); const billNo = await this.genSyncBillNo(principalId);
const qty = Math.abs(diff); const qty = Math.abs(diff);
const remark = `库存同步(${kindLabel} WMS ${wmsQty} vs 系统 ${systemQty})`; const remark = `库存同步(${kindLabel} WMS ${wmsQty} vs 系统 ${systemQty})`;
@ -410,7 +493,9 @@ class WarehouseProductController extends Controller {
}); });
inboundCount += 1; inboundCount += 1;
created.push({ type: 'inbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty }); created.push({ type: 'inbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty });
} else { return true;
}
const order = await ctx.model.OutboundOrder.create({ const order = await ctx.model.OutboundOrder.create({
bill_no: billNo, bill_no: billNo,
principal_id: principalId, principal_id: principalId,
@ -444,25 +529,34 @@ class WarehouseProductController extends Controller {
}); });
outboundCount += 1; outboundCount += 1;
created.push({ type: 'outbound', kind: kindLabel, id: order.id, bill_no: billNo, product_id: product.id, quantity: qty }); 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) { for (const it of valid) {
const product = productMap.get(it.product_id); const product = productMap.get(it.product_id);
if (!product) { skipped += 1; continue; } // 商品不存在/禁用,跳过 if (!product) { invalidCount += 1; continue; } // 商品不存在/禁用/不属于该仓库货主,跳过
const stockRows = stockMap.get(it.product_id) || {}; const stockRows = stockMap.get(it.product_id) || {};
const systemGood = stockRows['ZC'] ? Number(stockRows['ZC'].quantity) : 0; const systemGood = stockRows.ZC ? Number(stockRows.ZC.quantity) : 0;
const systemDefect = stockRows['CC'] ? Number(stockRows['CC'].quantity) : 0; const systemDefect = stockRows.CC ? Number(stockRows.CC.quantity) : 0;
// 正品维度 // 正品维度
await syncPair(product, systemGood, it.wms_good_quantity, '正品', 'ZC'); const goodChanged = await syncPair(product, systemGood, it.wms_good_quantity, '正品', 'ZC');
// 残次品维度 // 残次品维度
await syncPair(product, systemDefect, it.wms_defect_quantity, '残次品', 'CC'); const defectChanged = await syncPair(product, systemDefect, it.wms_defect_quantity, '残次品', 'CC');
// 两个维度都没有变动,记为「数量一致」
if (!goodChanged && !defectChanged) skippedProducts += 1;
} }
await transaction.commit(); await transaction.commit();
ctx.body = { ctx.body = {
code: 0, code: 0,
message: 'success', message: 'success',
data: { inbound_count: inboundCount, outbound_count: outboundCount, skipped, created }, data: {
inbound_count: inboundCount,
outbound_count: outboundCount,
skipped: skippedProducts,
skipped_kinds: skippedKinds,
invalid_count: invalidCount,
created,
},
}; };
} catch (err) { } catch (err) {
await transaction.rollback(); await transaction.rollback();
@ -472,7 +566,28 @@ class WarehouseProductController extends Controller {
} }
} }
/** 生成同步专用单号,保证唯一(重试) */ /**
* 所在公司权限:校验仓库是否可访问(不存在或不属于自己所属公司返回 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) { async genSyncBillNo(principalId) {
const { ctx } = this; const { ctx } = this;
const pad = n => String(n).padStart(2, '0'); const pad = n => String(n).padStart(2, '0');

View File

@ -0,0 +1,28 @@
'use strict';
/**
* 集团权限校验中间件
*
* 「所在公司」权限的账号只能在外部仓库做「推送商品 / 同步库存 / 查询库存」,
* 仓库与接口配置的维护(新增/编辑/删除/接口配置/快递映射/调用日志等)仅集团权限可用。
*
* @param {Object} [options] 配置项
* @param {boolean} [options.allowGet] 是否放行 GET(查询类接口,如仓库列表/详情)
* @return {Function} koa 中间件
*/
module.exports = (options = {}) => {
const allowGet = !!options.allowGet;
return async (ctx, next) => {
const principalId = ctx.state.principalId != null
? ctx.state.principalId
: (ctx.query.principal_id != null ? ctx.query.principal_id : (ctx.request.body || {}).principal_id);
const access = await ctx.service.access.resolve(ctx.userId, principalId);
if (!access.isGroup && !(allowGet && ctx.method === 'GET')) {
ctx.status = 403;
ctx.body = { code: 403, message: '所在公司权限仅支持推送商品、同步库存与查询库存' };
return;
}
await next();
};
};

View File

@ -116,6 +116,7 @@ module.exports = app => {
router.resources('menus', '/api/menus', jwtAuth, controller.menu); router.resources('menus', '/api/menus', jwtAuth, controller.menu);
router.resources('principalExternalApis', '/api/principal-external-apis', jwtAuth, principalCheck({ model: 'PrincipalExternalApi' }), controller.principalExternalApi); router.resources('principalExternalApis', '/api/principal-external-apis', jwtAuth, principalCheck({ model: 'PrincipalExternalApi' }), controller.principalExternalApi);
// 仓库(仅基础信息)与仓库接口配置(一个仓库可有多条接口配置) // 仓库(仅基础信息)与仓库接口配置(一个仓库可有多条接口配置)
const groupScope = app.middleware.groupScope;
router.get('/api/warehouses/select', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouse.select); router.get('/api/warehouses/select', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouse.select);
// 仓库下的商品(是否已推送到该仓库):需在 resources('warehouses') 之前注册,避免 /products 被当作 :id // 仓库下的商品(是否已推送到该仓库):需在 resources('warehouses') 之前注册,避免 /products 被当作 :id
router.get('/api/warehouses/:id/products', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.index); router.get('/api/warehouses/:id/products', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.index);
@ -125,16 +126,18 @@ module.exports = app => {
router.post('/api/warehouses/:id/products/wms-inventory', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.wmsInventory); router.post('/api/warehouses/:id/products/wms-inventory', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.wmsInventory);
// 库存同步:用外部 WMS 库存覆盖系统库存(差异以完成的出入库单平衡) // 库存同步:用外部 WMS 库存覆盖系统库存(差异以完成的出入库单平衡)
router.post('/api/warehouses/:id/inventory/sync', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.syncInventory); router.post('/api/warehouses/:id/inventory/sync', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.syncInventory);
router.resources('warehouses', '/api/warehouses', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouse); // 仓库维护仅集团权限可用(所在公司权限只读:列表/详情放行,写操作拒绝)
router.resources('warehouses', '/api/warehouses', jwtAuth, principalCheck({ model: 'Warehouse' }), groupScope({ allowGet: true }), controller.warehouse);
// 仓库接口配置项:定义(硬编码)与配置项值分开维护,需在 resources('warehouse-apis') 之前注册 // 仓库接口配置项:定义(硬编码)与配置项值分开维护,需在 resources('warehouse-apis') 之前注册
router.get('/api/warehouse-api-fields', jwtAuth, controller.warehouseApiField.index); // 接口配置、快递映射、调用日志均属于集团权限范围
router.get('/api/warehouse-apis/:id/fields', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApiField.show); router.get('/api/warehouse-api-fields', jwtAuth, principalCheck(), groupScope(), controller.warehouseApiField.index);
router.put('/api/warehouse-apis/:id/fields', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApiField.update); router.get('/api/warehouse-apis/:id/fields', jwtAuth, principalCheck({ model: 'WarehouseApi' }), groupScope(), controller.warehouseApiField.show);
router.put('/api/warehouse-apis/:id/fields', jwtAuth, principalCheck({ model: 'WarehouseApi' }), groupScope(), controller.warehouseApiField.update);
// 接口连通性测试(index.ping),需在 resources('warehouseApis') 之前注册 // 接口连通性测试(index.ping),需在 resources('warehouseApis') 之前注册
router.post('/api/warehouse-apis/:id/test', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApi.test); router.post('/api/warehouse-apis/:id/test', jwtAuth, principalCheck({ model: 'WarehouseApi' }), groupScope(), controller.warehouseApi.test);
router.resources('warehouseApis', '/api/warehouse-apis', jwtAuth, principalCheck({ model: 'WarehouseApi' }), controller.warehouseApi); router.resources('warehouseApis', '/api/warehouse-apis', jwtAuth, principalCheck({ model: 'WarehouseApi' }), groupScope(), controller.warehouseApi);
// 对外 API 调用日志(OMS → 外部 WMS 的请求记录),按主体隔离(principal_id 由前端拦截器注入 query) // 对外 API 调用日志(OMS → 外部 WMS 的请求记录),按主体隔离(principal_id 由前端拦截器注入 query)
router.get('/api/outbound-logs', jwtAuth, principalCheck(), controller.apiOutboundLog.index); router.get('/api/outbound-logs', jwtAuth, principalCheck(), groupScope(), controller.apiOutboundLog.index);
// 订单整单解析需在 resources('orders') 之前注册,避免被 /api/orders/:id 误匹配 // 订单整单解析需在 resources('orders') 之前注册,避免被 /api/orders/:id 误匹配
router.post('/api/orders/:id/parse-items', jwtAuth, principalCheck({ model: 'Order' }), controller.order.parseItems); router.post('/api/orders/:id/parse-items', jwtAuth, principalCheck({ model: 'Order' }), controller.order.parseItems);
router.resources('orders', '/api/orders', jwtAuth, principalCheck({ model: 'Order' }), controller.order); router.resources('orders', '/api/orders', jwtAuth, principalCheck({ model: 'Order' }), controller.order);
@ -216,7 +219,8 @@ module.exports = app => {
router.resources('productUnits', '/api/product-units', jwtAuth, principalCheck({ model: 'ProductUnit' }), controller.productUnit); router.resources('productUnits', '/api/product-units', jwtAuth, principalCheck({ model: 'ProductUnit' }), controller.productUnit);
// 仓库快递映射(外部传入的自定义快递编码 → OMS 默认快递编码,按仓库维度;供回传解析与「外部仓库」页配置) // 仓库快递映射(外部传入的自定义快递编码 → OMS 默认快递编码,按仓库维度;供回传解析与「外部仓库」页配置)
router.resources('warehouseExpressMappings', '/api/warehouse-express-mappings', jwtAuth, principalCheck({ model: 'WarehouseExpressMapping' }), controller.warehouseExpressMapping); // 仓库快递映射(按主体隔离):属于仓库/接口配置维护,仅集团权限可用
router.resources('warehouseExpressMappings', '/api/warehouse-express-mappings', jwtAuth, principalCheck({ model: 'WarehouseExpressMapping' }), app.middleware.groupScope(), controller.warehouseExpressMapping);
// 收件人信息智能识别(通用能力,仅需登录):需在 resources 之前注册,避免被 /:id 误匹配 // 收件人信息智能识别(通用能力,仅需登录):需在 resources 之前注册,避免被 /:id 误匹配
router.post('/api/order-deliveries/parse-receiver', jwtAuth, controller.orderDelivery.parseReceiver); router.post('/api/order-deliveries/parse-receiver', jwtAuth, controller.orderDelivery.parseReceiver);

View File

@ -159,8 +159,14 @@ export interface InventorySyncItem {
/** 库存同步:用外部 WMS 库存覆盖系统库存,差异以完成的出入库单平衡 */ /** 库存同步:用外部 WMS 库存覆盖系统库存,差异以完成的出入库单平衡 */
export function syncWarehouseInventory(id: number, items: InventorySyncItem[]) { export function syncWarehouseInventory(id: number, items: InventorySyncItem[]) {
return post<{ inbound_count: number; outbound_count: number; skipped: number }>( return post<{
`/warehouses/${id}/inventory/sync`, inbound_count: number
{ items }, outbound_count: number
) /** 正品/残次品数量都与系统一致、无需同步的商品数 */
skipped: number
/** 跳过的库存维度数(每个商品含正品、残次品两个维度) */
skipped_kinds: number
/** 不存在/已禁用/不属于该仓库货主的商品数 */
invalid_count: number
}>(`/warehouses/${id}/inventory/sync`, { items })
} }

View File

@ -38,6 +38,8 @@ import {
type WarehouseExpressMappingItem, type WarehouseExpressMappingItem,
} from '@/api/warehouseExpressMapping' } from '@/api/warehouseExpressMapping'
import { getExpressCompanyOptions, type ExpressCompanyOption } from '@/api/expressCompany' import { getExpressCompanyOptions, type ExpressCompanyOption } from '@/api/expressCompany'
import { getPrincipalSubsidiaryOptions } from '@/api/principalSubsidiary'
import { getAccessContext } from '@/api/access'
import SplitLayout from '@/components/SplitLayout.vue' import SplitLayout from '@/components/SplitLayout.vue'
import ExportButton from '@/components/ExportButton.vue' import ExportButton from '@/components/ExportButton.vue'
import DataTable from '@/components/DataTable.vue' import DataTable from '@/components/DataTable.vue'
@ -66,13 +68,50 @@ const API_TYPE_QIMEN = 'qimen'
const API_TYPE_LABEL = '类奇门JSON接口' const API_TYPE_LABEL = '类奇门JSON接口'
/* -------------------- 仓库列表 -------------------- */ /* -------------------- 仓库列表 -------------------- */
const query = reactive({ page: 1, pageSize: DEFAULT_PAGE_SIZE, code: '', status: '' as string | number }) const query = reactive({
page: 1,
pageSize: DEFAULT_PAGE_SIZE,
code: '',
subsidiary_id: '' as string | number,
status: '' as string | number,
})
/** 货主下拉(组织架构 → 下属公司) */
const subsidiaryOptions = ref<{ id: number; name: string }[]>([])
async function loadSubsidiaryOptions() {
try {
// mine=1:所在公司权限下只返回自己所属公司
subsidiaryOptions.value = await getPrincipalSubsidiaryOptions({ mine: 1 })
} catch {
subsidiaryOptions.value = []
}
}
/**
* 所在公司权限(货主):仅开放「推送商品 / 同步库存 / 查询库存」,
* 仓库维护、接口配置、快递映射、调用日志等入口一律隐藏
*/
const isCompanyScope = ref(false)
async function fetchAccessContext() {
try {
const ctx = await getAccessContext()
isCompanyScope.value = !ctx.is_group
if (isCompanyScope.value && activeDetailTab.value !== 'products' && activeDetailTab.value !== 'inventory') {
activeDetailTab.value = 'products'
}
} catch {
isCompanyScope.value = false
}
}
const { loading, list, total, elapsed, fetchList, search, handlePageChange, handleSizeChange } = useListPage({ const { loading, list, total, elapsed, fetchList, search, handlePageChange, handleSizeChange } = useListPage({
query, query,
fetcher: () => { fetcher: () => {
const params: Record<string, unknown> = { ...query } const params: Record<string, unknown> = { ...query }
if (!params.code) delete params.code if (!params.code) delete params.code
if (params.subsidiary_id === '') delete params.subsidiary_id
if (params.status === '') delete params.status if (params.status === '') delete params.status
return getWarehouses(params) return getWarehouses(params)
}, },
@ -80,6 +119,7 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand
function reset() { function reset() {
query.code = '' query.code = ''
query.subsidiary_id = ''
query.status = '' query.status = ''
search() search()
} }
@ -87,6 +127,7 @@ function reset() {
/** 导出筛选条件:仓库列表(关键词模糊匹配仓库编码/名称) */ /** 导出筛选条件:仓库列表(关键词模糊匹配仓库编码/名称) */
const warehouseExportFilters = computed(() => ({ const warehouseExportFilters = computed(() => ({
keyword: query.code.trim(), keyword: query.code.trim(),
subsidiary_id: query.subsidiary_id,
status: query.status, status: query.status,
})) }))
@ -155,8 +196,10 @@ async function switchWarehouse(id: number) {
resetProductState() resetProductState()
resetOutboundState() resetOutboundState()
resetInventoryState() resetInventoryState()
activeDetailTab.value = 'detail' // 所在公司权限直接进商品页(其余标签页已隐藏)
activeDetailTab.value = isCompanyScope.value ? 'products' : 'detail'
await fetchDetail(id) await fetchDetail(id)
if (isCompanyScope.value && productLoadedId.value !== id) await fetchProducts()
} }
function handleRowClick(row: WarehouseItem) { function handleRowClick(row: WarehouseItem) {
@ -171,6 +214,11 @@ async function openConfigTab(row: WarehouseItem) {
} }
function handleDetailTabChange(name: string | number) { function handleDetailTabChange(name: string | number) {
// 所在公司权限仅开放商品/库存两个标签页
if (isCompanyScope.value && name !== 'products' && name !== 'inventory') {
activeDetailTab.value = 'products'
return
}
if (name === 'config' && configLoadedId.value !== currentWarehouse.value?.id) fetchConfigs() if (name === 'config' && configLoadedId.value !== currentWarehouse.value?.id) fetchConfigs()
if (name === 'express' && mappingLoadedId.value !== currentWarehouse.value?.id) fetchMappings() if (name === 'express' && mappingLoadedId.value !== currentWarehouse.value?.id) fetchMappings()
if (name === 'products' && productLoadedId.value !== currentWarehouse.value?.id) fetchProducts() if (name === 'products' && productLoadedId.value !== currentWarehouse.value?.id) fetchProducts()
@ -302,6 +350,7 @@ const editId = ref<number | null>(null)
const form = reactive({ const form = reactive({
code: '', code: '',
name: '', name: '',
subsidiary_id: null as number | null,
type: 'wms', type: 'wms',
status: 1, status: 1,
remark: '', remark: '',
@ -309,12 +358,14 @@ const form = reactive({
const rules: FormRules = { const rules: FormRules = {
name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }], name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
subsidiary_id: [{ required: true, message: '请选择货主', trigger: 'change' }],
} }
function openCreate() { function openCreate() {
editId.value = null editId.value = null
form.code = '' form.code = ''
form.name = '' form.name = ''
form.subsidiary_id = null
form.type = 'wms' form.type = 'wms'
form.status = 1 form.status = 1
form.remark = '' form.remark = ''
@ -325,6 +376,7 @@ function openEdit(row: WarehouseItem) {
editId.value = row.id editId.value = row.id
form.code = row.code form.code = row.code
form.name = row.name form.name = row.name
form.subsidiary_id = row.subsidiary_id ?? null
form.type = row.type || '' form.type = row.type || ''
form.status = row.status form.status = row.status
form.remark = row.remark || '' form.remark = row.remark || ''
@ -339,6 +391,7 @@ async function submitForm() {
try { try {
const payload = { const payload = {
name: form.name, name: form.name,
subsidiary_id: Number(form.subsidiary_id),
type: form.type || null, type: form.type || null,
status: form.status, status: form.status,
remark: form.remark, remark: form.remark,
@ -695,8 +748,11 @@ async function handleQueryInventorySelected() {
} }
}) })
const res = await syncWarehouseInventory(warehouseId, items) const res = await syncWarehouseInventory(warehouseId, items)
const { inbound_count, outbound_count, skipped } = res const { inbound_count, outbound_count, skipped, invalid_count } = res
ElMessage.success(`同步完成:生成入库单 ${inbound_count} 个、出库单 ${outbound_count} 个,相同跳过 ${skipped} 个`) const parts = [`生成入库单 ${inbound_count} 个、出库单 ${outbound_count} 个`]
if (skipped > 0) parts.push(`${skipped} 个商品数量一致无需同步`)
if (invalid_count > 0) parts.push(`${invalid_count} 个商品不属于该仓库货主已忽略`)
ElMessage.success(`同步完成:${parts.join(',')}`)
selectedInventory.value = [] selectedInventory.value = []
await fetchInventory() await fetchInventory()
} catch (err: any) { } catch (err: any) {
@ -839,7 +895,10 @@ async function copyText(text?: string | null) {
} }
} }
onMounted(fetchList) onMounted(async () => {
await Promise.all([ loadSubsidiaryOptions(), fetchAccessContext() ])
await fetchList()
})
</script> </script>
<template> <template>
@ -848,8 +907,10 @@ onMounted(fetchList)
<div class="page-header"> <div class="page-header">
<span>外部仓库</span> <span>外部仓库</span>
<div class="header-actions"> <div class="header-actions">
<template v-if="!isCompanyScope">
<el-button type="primary" @click="openCreate">新增仓库</el-button> <el-button type="primary" @click="openCreate">新增仓库</el-button>
<ExportButton type="warehouse" :filters="warehouseExportFilters" /> <ExportButton type="warehouse" :filters="warehouseExportFilters" />
</template>
</div> </div>
</div> </div>
</template> </template>
@ -860,6 +921,18 @@ onMounted(fetchList)
<el-form-item label="仓库编码"> <el-form-item label="仓库编码">
<el-input v-model="query.code" placeholder="仓库编码" clearable @keyup.enter="search" /> <el-input v-model="query.code" placeholder="仓库编码" clearable @keyup.enter="search" />
</el-form-item> </el-form-item>
<el-form-item label="货主">
<el-select
v-model="query.subsidiary_id"
placeholder="全部"
clearable
filterable
style="width: 150px"
@change="search"
>
<el-option v-for="s in subsidiaryOptions" :key="s.id" :label="s.name" :value="s.id" />
</el-select>
</el-form-item>
<el-form-item label="状态"> <el-form-item label="状态">
<el-select v-model="query.status" placeholder="全部" clearable style="width: 140px"> <el-select v-model="query.status" placeholder="全部" clearable style="width: 140px">
<el-option label="启用" :value="1" /> <el-option label="启用" :value="1" />
@ -882,10 +955,13 @@ onMounted(fetchList)
> >
<el-table-column prop="code" label="仓库编码" width="180" /> <el-table-column prop="code" label="仓库编码" width="180" />
<el-table-column prop="name" label="仓库名称" min-width="160" /> <el-table-column prop="name" label="仓库名称" min-width="160" />
<el-table-column label="货主" width="140" show-overflow-tooltip>
<template #default="{ row }">{{ row.subsidiary_name || '-' }}</template>
</el-table-column>
<el-table-column label="类型" width="100"> <el-table-column label="类型" width="100">
<template #default="{ row }">{{ warehouseTypeLabel(row.type) }}</template> <template #default="{ row }">{{ warehouseTypeLabel(row.type) }}</template>
</el-table-column> </el-table-column>
<el-table-column label="接口配置" width="100" align="center"> <el-table-column label="接口配置" width="100" align="center" v-if="!isCompanyScope">
<template #default="{ row }">{{ (row.apis || []).length }}</template> <template #default="{ row }">{{ (row.apis || []).length }}</template>
</el-table-column> </el-table-column>
<el-table-column label="状态" width="90"> <el-table-column label="状态" width="90">
@ -896,7 +972,7 @@ onMounted(fetchList)
</template> </template>
</el-table-column> </el-table-column>
<el-table-column prop="remark" label="备注" min-width="140" show-overflow-tooltip /> <el-table-column prop="remark" label="备注" min-width="140" show-overflow-tooltip />
<el-table-column label="操作" width="200" fixed="right"> <el-table-column label="操作" width="200" fixed="right" v-if="!isCompanyScope">
<template #default="{ row }"> <template #default="{ row }">
<el-button link type="primary" @click.stop="openEdit(row)">编辑</el-button> <el-button link type="primary" @click.stop="openEdit(row)">编辑</el-button>
<el-button link type="success" @click.stop="openConfigTab(row)">接口配置</el-button> <el-button link type="success" @click.stop="openConfigTab(row)">接口配置</el-button>
@ -931,7 +1007,12 @@ onMounted(fetchList)
<el-tag :type="currentWarehouse.status === 1 ? 'success' : 'info'"> <el-tag :type="currentWarehouse.status === 1 ? 'success' : 'info'">
{{ currentWarehouse.status === 1 ? '启用' : '禁用' }} {{ currentWarehouse.status === 1 ? '启用' : '禁用' }}
</el-tag> </el-tag>
<el-button size="small" class="detail-edit" @click="openEdit(currentWarehouse)"> <el-button
v-if="!isCompanyScope"
size="small"
class="detail-edit"
@click="openEdit(currentWarehouse)"
>
编辑 编辑
</el-button> </el-button>
</div> </div>
@ -939,6 +1020,9 @@ onMounted(fetchList)
<el-descriptions :column="3" border size="small" title="基本信息"> <el-descriptions :column="3" border size="small" title="基本信息">
<el-descriptions-item label="仓库编码">{{ currentWarehouse.code }}</el-descriptions-item> <el-descriptions-item label="仓库编码">{{ currentWarehouse.code }}</el-descriptions-item>
<el-descriptions-item label="仓库名称">{{ currentWarehouse.name }}</el-descriptions-item> <el-descriptions-item label="仓库名称">{{ currentWarehouse.name }}</el-descriptions-item>
<el-descriptions-item label="货主">
{{ currentWarehouse.subsidiary_name || '-' }}
</el-descriptions-item>
<el-descriptions-item label="仓库类型"> <el-descriptions-item label="仓库类型">
{{ warehouseTypeLabel(currentWarehouse.type) }} {{ warehouseTypeLabel(currentWarehouse.type) }}
</el-descriptions-item> </el-descriptions-item>
@ -956,7 +1040,7 @@ onMounted(fetchList)
</el-descriptions-item> </el-descriptions-item>
</el-descriptions> </el-descriptions>
<el-descriptions :column="3" border size="small" title="关联统计" class="stat-block"> <el-descriptions v-if="!isCompanyScope" :column="3" border size="small" title="关联统计" class="stat-block">
<el-descriptions-item label="接口配置数"> <el-descriptions-item label="接口配置数">
{{ currentWarehouse.stats?.api_count ?? 0 }} {{ currentWarehouse.stats?.api_count ?? 0 }}
</el-descriptions-item> </el-descriptions-item>
@ -975,7 +1059,7 @@ onMounted(fetchList)
</div> </div>
</el-tab-pane> </el-tab-pane>
<el-tab-pane label="接口配置" name="config"> <el-tab-pane v-if="!isCompanyScope" label="接口配置" name="config">
<div class="detail-body is-config"> <div class="detail-body is-config">
<template v-if="currentWarehouse"> <template v-if="currentWarehouse">
<div class="items-toolbar"> <div class="items-toolbar">
@ -1027,7 +1111,7 @@ onMounted(fetchList)
</div> </div>
</el-tab-pane> </el-tab-pane>
<el-tab-pane label="快递映射" name="express"> <el-tab-pane v-if="!isCompanyScope" label="快递映射" name="express">
<div class="detail-body is-config"> <div class="detail-body is-config">
<template v-if="currentWarehouse"> <template v-if="currentWarehouse">
<div class="items-toolbar"> <div class="items-toolbar">
@ -1096,7 +1180,13 @@ onMounted(fetchList)
@keyup.enter="searchProducts" @keyup.enter="searchProducts"
/> />
<el-button @click="searchProducts">查询</el-button> <el-button @click="searchProducts">查询</el-button>
<ExportButton type="warehouse_product" :filters="productExportFilters" size="small" plain /> <ExportButton
v-if="!isCompanyScope"
type="warehouse_product"
:filters="productExportFilters"
size="small"
plain
/>
</div> </div>
<div class="bottom-table-wrap"> <div class="bottom-table-wrap">
<DataTable :loading="productLoading" :data="productList" height="100%" @selection-change="handleProductSelectionChange"> <DataTable :loading="productLoading" :data="productList" height="100%" @selection-change="handleProductSelectionChange">
@ -1134,6 +1224,7 @@ onMounted(fetchList)
<div class="detail-body is-config"> <div class="detail-body is-config">
<template v-if="currentWarehouse"> <template v-if="currentWarehouse">
<div class="items-toolbar"> <div class="items-toolbar">
<!-- 所在公司权限:仅保留查询库存与同步覆盖,导出等维护入口不展示 -->
<span class="items-title">库存 · {{ currentWarehouse.name }}</span> <span class="items-title">库存 · {{ currentWarehouse.name }}</span>
<el-button <el-button
type="success" type="success"
@ -1160,7 +1251,13 @@ onMounted(fetchList)
@keyup.enter="searchInventory" @keyup.enter="searchInventory"
/> />
<el-button @click="searchInventory">查询</el-button> <el-button @click="searchInventory">查询</el-button>
<ExportButton type="warehouse_product" :filters="inventoryExportFilters" size="small" plain /> <ExportButton
v-if="!isCompanyScope"
type="warehouse_product"
:filters="inventoryExportFilters"
size="small"
plain
/>
</div> </div>
<div class="bottom-table-wrap"> <div class="bottom-table-wrap">
<DataTable :loading="inventoryLoading" :data="displayInventoryList" height="100%" @selection-change="handleInventorySelectionChange"> <DataTable :loading="inventoryLoading" :data="displayInventoryList" height="100%" @selection-change="handleInventorySelectionChange">
@ -1210,7 +1307,7 @@ onMounted(fetchList)
</div> </div>
</el-tab-pane> </el-tab-pane>
<el-tab-pane label="调用日志" name="logs"> <el-tab-pane v-if="!isCompanyScope" label="调用日志" name="logs">
<div class="detail-body is-config"> <div class="detail-body is-config">
<template v-if="currentWarehouse"> <template v-if="currentWarehouse">
<div class="items-toolbar"> <div class="items-toolbar">
@ -1276,6 +1373,11 @@ onMounted(fetchList)
<el-form-item label="仓库名称" prop="name"> <el-form-item label="仓库名称" prop="name">
<el-input v-model="form.name" placeholder="如 上海中心仓" /> <el-input v-model="form.name" placeholder="如 上海中心仓" />
</el-form-item> </el-form-item>
<el-form-item label="货主" prop="subsidiary_id">
<el-select v-model="form.subsidiary_id" placeholder="请选择货主(下属公司)" filterable style="width: 100%">
<el-option v-for="s in subsidiaryOptions" :key="s.id" :label="s.name" :value="s.id" />
</el-select>
</el-form-item>
<el-form-item label="仓库类型" prop="type"> <el-form-item label="仓库类型" prop="type">
<el-select v-model="form.type" clearable placeholder="请选择" style="width: 100%"> <el-select v-model="form.type" clearable placeholder="请选择" style="width: 100%">
<el-option v-for="t in WAREHOUSE_TYPE_OPTIONS" :key="t.value" :label="t.label" :value="t.value" /> <el-option v-for="t in WAREHOUSE_TYPE_OPTIONS" :key="t.value" :label="t.label" :value="t.value" />