From 9774ee1414baa10bbff5f0fc0db9517e1d037ce9 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 5 Nov 2026 15:13:22 +0800 Subject: [PATCH] =?UTF-8?q?feat(stock):=20=E5=87=BA=E5=85=A5=E5=BA=93?= =?UTF-8?q?=E5=8D=95/=E8=AE=B0=E5=BD=95=E5=A2=9E=E5=8A=A0=E8=B4=A7?= =?UTF-8?q?=E4=B8=BB=E5=B9=B6=E6=8C=89=E8=B4=A7=E4=B8=BB=E9=9A=94=E7=A6=BB?= =?UTF-8?q?=EF=BC=8C=E5=88=9B=E5=BB=BA=E4=BA=BA=E6=98=BE=E7=A4=BA=E5=91=98?= =?UTF-8?q?=E5=B7=A5=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 迁移:inbound_orders / outbound_orders 增加 subsidiary_id 与索引,按仓库回填 - 单据货主由仓库决定:创建写入、改仓库同步,接口不接受直写 subsidiary_id - 入库单/出库单列表返回 subsidiary_name 并新增货主筛选;详情/编辑/删除/审核/ 推送/完成/取消/恢复/作废/驳回与明细接口统一加货主越界 403 - 出入库记录按仓库归属货主:列表与导出收窄、返回 subsidiary_id/subsidiary_name、 新增货主列与筛选 - 导出:入库单/出库单/出入库记录新增货主列并按所在公司权限收窄 - 新增 resolveAccountNameMap:列表/详情返回 creator_name/auditor_name/voider_name, 创建人展示员工名称(principal_users.name),不再回退成邮箱账号 - 前端:三个列表新增货主列与筛选,创建人/作废人展示改为员工名称 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- backend/app/contract/index.js | 11 +++ backend/app/controller/inboundOrder.js | 81 ++++++++++++++++++- backend/app/controller/outboundOrder.js | 74 ++++++++++++++++- backend/app/controller/stockItem.js | 59 +++++++++++--- backend/app/controller/stockRecord.js | 64 ++++++++++++++- backend/app/lib/accountProfile.js | 44 +++++++++- backend/app/lib/billOwnerScope.js | 31 ++++++- backend/app/model/inboundOrder.js | 2 + backend/app/model/outboundOrder.js | 2 + backend/app/utils/exportDefs.js | 54 +++++++++++++ ...105070300-add-subsidiary-to-stock-bills.js | 41 ++++++++++ frontend/src/api/inboundOrder.ts | 10 +++ frontend/src/api/outboundOrder.ts | 8 ++ frontend/src/api/stockRecord.ts | 4 + frontend/src/views/InboundOrder/Index.vue | 23 +++++- frontend/src/views/OutboundOrder/Index.vue | 20 ++++- frontend/src/views/StockRecord/Index.vue | 25 ++++++ 17 files changed, 528 insertions(+), 25 deletions(-) create mode 100644 backend/database/migrations/20261105070300-add-subsidiary-to-stock-bills.js diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 34a1df8..dbf38fd 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -1465,6 +1465,11 @@ module.exports = { id: { type: 'integer', description: '主键' }, bill_no: { type: 'string', description: '入库单号,唯一' }, principal_id: { type: 'integer', description: '所属主体ID' }, + subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID),跟随仓库' }, + subsidiary_name: { type: 'string', description: '所属货主名称(列表/详情返回)' }, + creator_name: { type: 'string', description: '创建人展示名(员工名称,按主体账号名称解析)' }, + auditor_name: { type: 'string', description: '审核人展示名(员工名称)' }, + voider_name: { type: 'string', description: '作废人展示名(员工名称)' }, shop_id: { type: 'integer', description: '来源店铺/仓库ID' }, inbound_type: { type: 'string', description: '入库单类型(WMS 编码):B2BRK B2B入库 / SCRK 生产入库 / LYRK 领用入库 / CCRK 残次品入库 / CGRK 采购入库 / DBRK 调拨入库 / QTRK 其他入库' }, status: { type: 'integer', description: '状态:1待入库 2已审核 3已推送 4完成 5已作废 9已取消' }, @@ -1539,6 +1544,10 @@ module.exports = { id: { type: 'integer', description: '主键' }, bill_no: { type: 'string', description: '出库单号,唯一' }, principal_id: { type: 'integer', description: '所属主体ID' }, + subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID),跟随仓库' }, + subsidiary_name: { type: 'string', description: '所属货主名称(列表/详情返回)' }, + creator_name: { type: 'string', description: '创建人展示名(员工名称,按主体账号名称解析)' }, + voider_name: { type: 'string', description: '作废人展示名(员工名称)' }, shop_id: { type: 'integer', description: '目标店铺/仓库ID' }, outbound_type: { type: 'string', description: '出库单类型(WMS 编码):PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单' }, status: { type: 'integer', description: '状态:1待出库 2已审核 3已推送 4完成 5已作废 9已取消' }, @@ -2103,6 +2112,8 @@ module.exports = { id: { type: 'integer', description: '主键' }, principal_id: { type: 'integer', description: '所属主体ID' }, warehouse_id: { type: 'integer', description: '仓库ID' }, + subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID),按仓库归属' }, + subsidiary_name: { type: 'string', description: '所属货主名称' }, product_id: { type: 'integer', description: '系统商品ID' }, item_code: { type: 'string', description: '商品编码(快照)' }, item_name: { type: 'string', description: '商品名称(快照)' }, diff --git a/backend/app/controller/inboundOrder.js b/backend/app/controller/inboundOrder.js index f805b45..7ce153d 100644 --- a/backend/app/controller/inboundOrder.js +++ b/backend/app/controller/inboundOrder.js @@ -5,8 +5,8 @@ const recalcStock = require('../utils/recalcStock'); const completeInbound = require('../utils/completeInbound'); const nextRejectedBillNo = require('../utils/rejectBillNo'); const { parsePagination, buildPageResult } = require('../lib/pagination'); -const { resolveAccountName } = require('../lib/accountProfile'); -const { resolveWarehouse, assertItemsOwner } = require('../lib/billOwnerScope'); +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'); @@ -70,6 +70,25 @@ const MANAGED_FIELDS = [ * 单据头 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 @@ -80,13 +99,14 @@ class InboundOrderController extends Controller { * @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 } = 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 }; @@ -95,6 +115,21 @@ class InboundOrderController extends Controller { 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, @@ -103,12 +138,27 @@ class InboundOrderController extends Controller { 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' ] }, ], }); - ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + // 创建人 / 审核人展示员工名称(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 }) }; } /** @@ -124,6 +174,7 @@ class InboundOrderController extends Controller { 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' ] }, @@ -134,6 +185,7 @@ class InboundOrderController extends Controller { 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 }, @@ -145,6 +197,12 @@ class InboundOrderController extends Controller { 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 }; } @@ -207,6 +265,7 @@ class InboundOrderController extends Controller { ...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, @@ -264,6 +323,7 @@ class InboundOrderController extends Controller { ctx.body = { code: 404, message: '入库单不存在' }; return; } + if (!await this._assertAccess(order)) return; // 仅「待入库」可编辑:与明细锁定规则一致,已审核及之后禁止改动(可先驳回再修改) if (order.status !== 1) { ctx.status = 400; @@ -272,6 +332,8 @@ class InboundOrderController extends Controller { } 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 组),非法值拒绝(影响后续推送与取消的口径一致) @@ -307,6 +369,8 @@ class InboundOrderController extends Controller { ctx.body = { code: 400, message: itemsOwner.message }; return; } + // 换仓库后单据货主跟随新仓库 + ctx.request.body.subsidiary_id = warehouseScope.subsidiaryId; } await order.update(ctx.request.body); @@ -330,6 +394,7 @@ class InboundOrderController extends Controller { 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: '已审核及之后的单据禁止删除,请使用「作废」' }; @@ -357,6 +422,7 @@ class InboundOrderController extends Controller { 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 }; @@ -387,6 +453,7 @@ class InboundOrderController extends Controller { ctx.body = { code: 404, message: '入库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 1) { ctx.status = 400; ctx.body = { code: 400, message: '只有「待入库」状态的单据可以审核' }; @@ -431,6 +498,7 @@ class InboundOrderController extends Controller { ctx.body = { code: 404, message: '入库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 2) { ctx.status = 400; ctx.body = { code: 400, message: '只有「已审核」状态的单据可以推送' }; @@ -555,6 +623,7 @@ class InboundOrderController extends Controller { ctx.body = { code: 404, message: '入库单不存在' }; return; } + if (!await this._assertAccess(order)) return; let result; try { result = await completeInbound(ctx, order); @@ -579,6 +648,7 @@ class InboundOrderController extends Controller { ctx.body = { code: 404, message: '入库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status === 4) { ctx.status = 400; ctx.body = { code: 400, message: '已完成单据不能取消' }; @@ -596,6 +666,7 @@ class InboundOrderController extends Controller { ctx.body = { code: 404, message: '入库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 9) { ctx.status = 400; ctx.body = { code: 400, message: '只有「已取消」的单据可以恢复' }; @@ -621,6 +692,7 @@ class InboundOrderController extends Controller { ctx.body = { code: 404, message: '入库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 2) { ctx.status = 400; ctx.body = { code: 400, message: '只有「已审核」状态的单据可以作废' }; @@ -658,6 +730,7 @@ class InboundOrderController extends Controller { ctx.body = { code: 404, message: '入库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status === 4) { ctx.status = 400; ctx.body = { code: 400, message: '已完成入库的单据不能驳回' }; diff --git a/backend/app/controller/outboundOrder.js b/backend/app/controller/outboundOrder.js index f0ff9be..0337275 100644 --- a/backend/app/controller/outboundOrder.js +++ b/backend/app/controller/outboundOrder.js @@ -5,8 +5,8 @@ const recalcStock = require('../utils/recalcStock'); const { applyStockChange } = require('../utils/stockRecord'); const nextRejectedBillNo = require('../utils/rejectBillNo'); const { parsePagination, buildPageResult } = require('../lib/pagination'); -const { resolveAccountName } = require('../lib/accountProfile'); -const { resolveWarehouse, assertItemsOwner } = require('../lib/billOwnerScope'); +const { resolveAccountName, resolveAccountNameMap } = require('../lib/accountProfile'); +const { resolveWarehouse, assertItemsOwner, resolveAccess, ownSubsidiaryIds, isVisible } = require('../lib/billOwnerScope'); const QimenWmsClient = require('../lib/wms/qimenClient'); const { DEFAULT_OUTBOUND_ORDER_TYPE, OUTBOUND_ORDER_TYPE_LIST, normalizeOutboundOrderType } = require('../lib/wms/orderTypes'); @@ -32,6 +32,25 @@ const MANAGED_FIELDS = [ * 单据头 outbound_orders;明细由 stock_items(bill_type=2)承载,随单据在同一事务内创建 */ class OutboundOrderController 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.OutboundOrder.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/outbound-orders @@ -42,13 +61,14 @@ class OutboundOrderController extends Controller { * @request query integer status 状态:1待出库 2已出库 3已取消 * @request query string outbound_type 出库类型(WMS 编码):PTCK 普通出库单 / DBCK 调拨出库 / B2BCK B2B出库 / QTCK 其他出库 / CGTH 采购退货出库单 * @request query integer shop_id 店铺/仓库ID + * @request query integer subsidiary_id 货主(下属公司ID),集团账号可按货主筛选 * @response 200 outboundOrderListResponse success */ async index() { const { ctx } = this; const Op = this.app.Sequelize.Op; const { page, pageSize, offset, limit } = parsePagination(ctx.query); - const { bill_no: billNo, status, outbound_type: outboundType, shop_id: shopId } = ctx.query; + const { bill_no: billNo, status, outbound_type: outboundType, shop_id: shopId, subsidiary_id: subsidiaryId } = ctx.query; const principalId = ctx.state.principalId; const where = { principal_id: principalId }; @@ -57,6 +77,21 @@ class OutboundOrderController extends Controller { if (outboundType !== undefined && outboundType !== '') where.outbound_type = String(outboundType).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.OutboundOrder.findAndCountAll({ where, offset, @@ -65,11 +100,21 @@ class OutboundOrderController extends Controller { 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' ] }, ], }); - ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + // 创建人展示员工名称(principal_users.name),避免昵称为空时回退成邮箱账号 + const nameMap = await resolveAccountNameMap(ctx, rows.map(row => row.created_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)) || ''; + return plain; + }); + + ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; } /** @@ -85,6 +130,7 @@ class OutboundOrderController extends Controller { 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: 'voider', attributes: [ 'id', 'nickname', 'username' ] }, ], @@ -94,6 +140,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; const items = await ctx.model.StockItem.findAll({ where: { bill_type: 2, bill_id: order.id }, @@ -105,6 +152,11 @@ class OutboundOrderController extends Controller { const data = order.toJSON(); data.items = items; + // 创建人 / 作废人展示员工名称(principal_users.name),避免昵称为空时回退成邮箱账号 + const nameMap = await resolveAccountNameMap(ctx, [ data.created_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.voider_name = nameMap.get(Number(data.void_by)) || ''; ctx.body = { code: 0, message: 'success', data }; } @@ -167,6 +219,7 @@ class OutboundOrderController extends Controller { ...payload, bill_no: `CK_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, @@ -224,6 +277,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; // 仅「待出库」可编辑:与明细锁定规则一致,已审核及之后禁止改动(可先驳回再修改) if (order.status !== 1) { ctx.status = 400; @@ -232,6 +286,8 @@ class OutboundOrderController extends Controller { } 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]; // 出库单类型:同样存储 WMS 编码(CK 组),非法值拒绝(影响后续推送与取消的口径一致) if (ctx.request.body.outbound_type != null && String(ctx.request.body.outbound_type).trim() !== '') { @@ -266,6 +322,8 @@ class OutboundOrderController extends Controller { ctx.body = { code: 400, message: itemsOwner.message }; return; } + // 换仓库后单据货主跟随新仓库 + ctx.request.body.subsidiary_id = warehouseScope.subsidiaryId; } await order.update(ctx.request.body); @@ -289,6 +347,7 @@ class OutboundOrderController extends Controller { 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: '已审核及之后的单据禁止删除,请使用「作废」' }; @@ -329,6 +388,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 1) { ctx.status = 400; ctx.body = { code: 400, message: '只有「已创建」状态的单据可以审核' }; @@ -368,6 +428,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 2) { ctx.status = 400; ctx.body = { code: 400, message: '只有「已审核」状态的单据可以推送' }; @@ -397,6 +458,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 3) { ctx.status = 400; ctx.body = { code: 400, message: '只有「已推送」状态的单据可以完成出库' }; @@ -420,6 +482,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status === 4) { ctx.status = 400; ctx.body = { code: 400, message: '已完成单据不能取消' }; @@ -450,6 +513,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 9) { ctx.status = 400; ctx.body = { code: 400, message: '只有「已取消」的单据可以恢复' }; @@ -476,6 +540,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status !== 2) { ctx.status = 400; ctx.body = { code: 400, message: '只有「已审核」状态的单据可以作废' }; @@ -523,6 +588,7 @@ class OutboundOrderController extends Controller { ctx.body = { code: 404, message: '出库单不存在' }; return; } + if (!await this._assertAccess(order)) return; if (order.status === 4) { ctx.status = 400; ctx.body = { code: 400, message: '已完成出库的单据不能驳回' }; diff --git a/backend/app/controller/stockItem.js b/backend/app/controller/stockItem.js index 18fc127..13eb59b 100644 --- a/backend/app/controller/stockItem.js +++ b/backend/app/controller/stockItem.js @@ -3,7 +3,7 @@ const { Controller } = require('egg'); const recalcStock = require('../utils/recalcStock'); const { parsePagination, buildPageResult } = require('../lib/pagination'); -const { assertItemsOwner, resolveBillSubsidiary } = require('../lib/billOwnerScope'); +const { assertItemsOwner, resolveBillSubsidiary, resolveAccess, isVisible } = require('../lib/billOwnerScope'); /** * 应/已数量由系统维护(应=明细数量,已=WMS 回推),禁止前端直接写入。 @@ -13,21 +13,44 @@ const QTY_MANAGED_FIELDS = [ 'plan_in_qty', 'actual_in_qty', 'plan_out_qty', 'ac /** * 明细仅在所属单据处于「待处理(1)」时可增删改; * 单据一经审核(2) 及之后明细即锁定,避免审核后篡改导致库存与对账不一致。 + * 同时校验单据所属货主是否在当前账号可见范围内(所在公司权限不可越界)。 * @param {Object} ctx egg context * @param {Number} billType 1入库 2出库 * @param {Number} billId 单据头ID - * @return {Promise<{ok: boolean, message?: string}>} + * @return {Promise<{ok: boolean, status?: number, message?: string}>} 校验结果 */ async function assertItemsEditable(ctx, billType, billId) { const OrderModel = Number(billType) === 1 ? ctx.model.InboundOrder : ctx.model.OutboundOrder; - const order = await OrderModel.findByPk(billId); - if (!order) return { ok: false, message: '所属单据不存在' }; + const order = await OrderModel.findByPk(billId, { attributes: [ 'id', 'status', 'subsidiary_id' ] }); + if (!order) return { ok: false, status: 404, message: '所属单据不存在' }; + const access = await resolveAccess(ctx); + if (!isVisible(access, order.subsidiary_id)) { + return { ok: false, status: 403, message: '该单据不属于自己所属公司(货主),无权操作' }; + } if (order.status !== 1) { return { ok: false, message: '单据已审核或已结束,明细已锁定,不允许增删改' }; } return { ok: true }; } +/** + * 校验单据所属货主是否在当前账号可见范围内(只读场景:明细列表 / 详情) + * @param {Object} ctx egg context + * @param {Number} billType 1入库 2出库 + * @param {Number} billId 单据头ID + * @return {Promise<{ok: boolean, status?: number, message?: string}>} 校验结果 + */ +async function assertBillVisible(ctx, billType, billId) { + const OrderModel = Number(billType) === 1 ? ctx.model.InboundOrder : ctx.model.OutboundOrder; + const order = await OrderModel.findByPk(billId, { attributes: [ 'id', 'subsidiary_id' ] }); + if (!order) return { ok: false, status: 404, message: '所属单据不存在' }; + const access = await resolveAccess(ctx); + if (!isVisible(access, order.subsidiary_id)) { + return { ok: false, status: 403, message: '该单据不属于自己所属公司(货主),无权查看' }; + } + return { ok: true }; +} + /** * @controller StockItemController 出入库明细管理 * 明细挂在 stock_items 表,由 bill_type(1入库 2出库)+ bill_id 区分归属单据 @@ -55,6 +78,13 @@ class StockItemController extends Controller { return; } + const visible = await assertBillVisible(ctx, billType, billId); + if (!visible.ok) { + ctx.status = visible.status; + ctx.body = { code: visible.status, message: visible.message }; + return; + } + const where = { bill_id: Number(billId), bill_type: Number(billType), principal_id: ctx.state.principalId }; const { count, rows } = await ctx.model.StockItem.findAndCountAll({ where, @@ -90,6 +120,12 @@ class StockItemController extends Controller { ctx.body = { code: 404, message: '明细不存在' }; return; } + const visible = await assertBillVisible(ctx, item.bill_type, item.bill_id); + if (!visible.ok) { + ctx.status = visible.status; + ctx.body = { code: visible.status, message: visible.message }; + return; + } ctx.body = { code: 0, message: 'success', data: item }; } @@ -111,8 +147,9 @@ class StockItemController extends Controller { // 明细锁定校验:单据已审核及之后不允许再新增明细 const editable = await assertItemsEditable(ctx, billType, billId); if (!editable.ok) { - ctx.status = 400; - ctx.body = { code: 400, message: editable.message }; + const status = editable.status || 400; + ctx.status = status; + ctx.body = { code: status, message: editable.message }; return; } // 关联系统商品时必须启用,禁用商品不可绑定到明细 @@ -180,8 +217,9 @@ class StockItemController extends Controller { // 明细锁定校验:单据已审核及之后不允许修改明细 const editable = await assertItemsEditable(ctx, item.bill_type, item.bill_id); if (!editable.ok) { - ctx.status = 400; - ctx.body = { code: 400, message: editable.message }; + const status = editable.status || 400; + ctx.status = status; + ctx.body = { code: status, message: editable.message }; return; } const body = { ...ctx.request.body }; @@ -255,8 +293,9 @@ class StockItemController extends Controller { // 明细锁定校验:单据已审核及之后不允许删除明细 const editable = await assertItemsEditable(ctx, item.bill_type, item.bill_id); if (!editable.ok) { - ctx.status = 400; - ctx.body = { code: 400, message: editable.message }; + const status = editable.status || 400; + ctx.status = status; + ctx.body = { code: status, message: editable.message }; return; } await item.destroy(); diff --git a/backend/app/controller/stockRecord.js b/backend/app/controller/stockRecord.js index 20a7704..3ffcfc4 100644 --- a/backend/app/controller/stockRecord.js +++ b/backend/app/controller/stockRecord.js @@ -3,6 +3,7 @@ const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); const { BIZ_TYPES, BIZ_TYPE_LIST, DIRECTION_LABELS } = require('../utils/stockRecord'); +const { resolveAccess, ownSubsidiaryIds } = require('../lib/billOwnerScope'); /** * 把查询入参转成 Date:日期(YYYY-MM-DD)按当天 00:00:00 / 23:59:59 处理,含时间的按原值 @@ -40,6 +41,7 @@ class StockRecordController extends Controller { * @request query integer pageSize 每页条数,默认 20 * @request query integer product_id 商品ID(商品选择器锁定后传入,精确匹配) * @request query integer warehouse_id 仓库ID + * @request query integer subsidiary_id 货主(下属公司ID),按仓库所属公司筛选 * @request query string biz_type 业务动作:outbound_lock 出库推送锁定 / outbound_unlock 出库解锁 / outbound_deduct 出库确认扣减 / outbound_restore 出库驳回回补 / inbound_increase 入库确认增加 / order_lock 订单审核锁定 / order_unlock 订单解锁 / order_deduct 订单发货确认扣减 * @request query integer direction 业务方向:1入库方向 2出库方向 * @request query integer bill_type 单据类型:1入库单 2出库单 3发货单(订单) @@ -57,6 +59,7 @@ class StockRecordController extends Controller { const { product_id: productId, warehouse_id: warehouseId, + subsidiary_id: subsidiaryId, biz_type: bizType, direction, bill_type: billType, @@ -75,6 +78,47 @@ class StockRecordController extends Controller { if (billType !== undefined && billType !== '') where.bill_type = Number(billType); if (itemType) where.item_type = String(itemType).trim().toUpperCase(); if (billNo) where.bill_no = { [Op.like]: `%${billNo}%` }; + + // 货主口径:流水按仓库所属公司归属;所在公司权限只能看自己所属公司仓库的流水 + const access = await resolveAccess(ctx); + const ownIds = ownSubsidiaryIds(access); + const emptyPage = () => { + ctx.body = { code: 0, message: 'success', data: buildPageResult([], 0, { page, pageSize }) }; + }; + const warehouseIdsOf = async ids => { + if (!ids.length) return []; + const rows = await ctx.model.Warehouse.findAll({ + where: { principal_id: ctx.state.principalId, subsidiary_id: { [Op.in]: ids } }, + attributes: [ 'id' ], + raw: true, + }); + return rows.map(row => Number(row.id)); + }; + if (ownIds) { + const ownedIds = await warehouseIdsOf(ownIds); + if (!ownedIds.length) { + emptyPage(); + return; + } + if (warehouseId) { + // 只能查自己所属公司的仓库,传了别家仓库直接返回空 + if (!ownedIds.includes(Number(warehouseId))) { + emptyPage(); + return; + } + where.warehouse_id = Number(warehouseId); + } else { + where.warehouse_id = { [Op.in]: ownedIds }; + } + } else if (subsidiaryId) { + const scopedIds = await warehouseIdsOf([ Number(subsidiaryId) ]); + if (!scopedIds.length) { + emptyPage(); + return; + } + where.warehouse_id = { [Op.in]: scopedIds }; + } + // 关键词:未锁定商品时用模糊匹配(单据号 / 商品编码 / 商品名称);已锁定商品时用 product_id 精确过滤 if (keyword) { where[Op.or] = [ @@ -102,12 +146,30 @@ class StockRecordController extends Controller { order: [[ 'id', 'DESC' ]], }); - // 附上中文标签,前端直接展示(避免前后端枚举文案漂移) + // 附上中文标签与货主(流水按仓库归属货主),前端直接展示(避免前后端枚举文案漂移) + const warehouseIds = [ ...new Set(rows.map(row => Number(row.warehouse_id)).filter(id => Number.isInteger(id) && id > 0)) ]; + const ownerByWarehouse = new Map(); + if (warehouseIds.length) { + const warehouses = await ctx.model.Warehouse.findAll({ + where: { id: { [Op.in]: warehouseIds }, principal_id: ctx.state.principalId }, + attributes: [ 'id', 'subsidiary_id' ], + include: [{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }], + }); + for (const wh of warehouses) { + ownerByWarehouse.set(Number(wh.id), { + subsidiary_id: wh.subsidiary_id == null ? null : Number(wh.subsidiary_id), + subsidiary_name: wh.subsidiary ? wh.subsidiary.name : '', + }); + } + } const list = rows.map(row => { const item = row.get ? row.get({ plain: true }) : row; const meta = BIZ_TYPES[item.biz_type] || {}; item.biz_type_label = meta.label || item.biz_type; item.direction_label = DIRECTION_LABELS[item.direction] || ''; + const owner = ownerByWarehouse.get(Number(item.warehouse_id)); + item.subsidiary_id = owner ? owner.subsidiary_id : null; + item.subsidiary_name = owner ? owner.subsidiary_name : ''; return item; }); diff --git a/backend/app/lib/accountProfile.js b/backend/app/lib/accountProfile.js index 03f6dd0..06b28ca 100644 --- a/backend/app/lib/accountProfile.js +++ b/backend/app/lib/accountProfile.js @@ -72,4 +72,46 @@ function firstCharOf(name, username) { return Array.from(source)[0]; } -module.exports = { resolveAccountProfile, resolveAccountName, firstCharOf }; +/** + * 批量取账号在指定主体下的显示名称(列表展示创建人 / 审核人 / 作废人用) + * + * 与 resolveAccountName 同口径:principal_users.name → users.nickname → users.username, + * 一次查询完成,避免逐行查询 N+1。 + * @param {Object} ctx egg context + * @param {Array} userIds 用户ID列表(可含重复/空值) + * @param {Number|String} principalId 主体ID + * @return {Promise>} userId → 名称 + */ +async function resolveAccountNameMap(ctx, userIds, principalId) { + const ids = [ ...new Set((userIds || []).map(Number).filter(id => Number.isInteger(id) && id > 0)) ]; + const map = new Map(); + if (!ids.length) return map; + + const Op = ctx.app.Sequelize.Op; + const relations = Number(principalId) + ? await ctx.model.PrincipalUser.findAll({ + where: { user_id: { [Op.in]: ids }, principal_id: Number(principalId) }, + attributes: [ 'user_id', 'name' ], + raw: true, + }) + : []; + for (const row of relations) { + if (row.name) map.set(Number(row.user_id), String(row.name)); + } + + const missing = ids.filter(id => !map.has(id)); + if (missing.length) { + const users = await ctx.model.User.findAll({ + where: { id: { [Op.in]: missing } }, + attributes: [ 'id', 'nickname', 'username' ], + raw: true, + }); + for (const user of users) { + const name = user.nickname || user.username; + if (name) map.set(Number(user.id), String(name)); + } + } + return map; +} + +module.exports = { resolveAccountProfile, resolveAccountName, resolveAccountNameMap, firstCharOf }; diff --git a/backend/app/lib/billOwnerScope.js b/backend/app/lib/billOwnerScope.js index bd8c2af..6092939 100644 --- a/backend/app/lib/billOwnerScope.js +++ b/backend/app/lib/billOwnerScope.js @@ -109,4 +109,33 @@ async function resolveBillSubsidiary(ctx, billType, billId) { return { ok: true, subsidiaryId: warehouse.subsidiaryId }; } -module.exports = { resolveAccess, resolveWarehouse, assertItemsOwner, resolveBillSubsidiary }; +/** + * 判断某货主的数据是否在当前账号可见范围内 + * @param {Object} access resolveAccess 的结果 + * @param {number|null} subsidiaryId 数据所属货主ID + * @return {boolean} 是否可见/可操作 + */ +function isVisible(access, subsidiaryId) { + if (!access || access.isGroup) return true; + if (subsidiaryId === null || subsidiaryId === undefined) return false; + return access.ownCompanyIds.includes(Number(subsidiaryId)); +} + +/** + * 取当前账号的货主可见范围(集团返回 null,表示不限制) + * @param {Object} access resolveAccess 的结果 + * @return {Array|null} 可见货主ID列表;null 表示不限制 + */ +function ownSubsidiaryIds(access) { + if (!access || access.isGroup) return null; + return access.ownCompanyIds.map(Number); +} + +module.exports = { + resolveAccess, + resolveWarehouse, + assertItemsOwner, + resolveBillSubsidiary, + isVisible, + ownSubsidiaryIds, +}; diff --git a/backend/app/model/inboundOrder.js b/backend/app/model/inboundOrder.js index 13cc474..f6079c5 100644 --- a/backend/app/model/inboundOrder.js +++ b/backend/app/model/inboundOrder.js @@ -12,6 +12,7 @@ module.exports = app => { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, bill_no: { type: STRING(50), allowNull: false, comment: '入库单号' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + subsidiary_id: { type: BIGINT.UNSIGNED, comment: '所属货主(下属公司ID),跟随仓库' }, shop_id: { type: BIGINT.UNSIGNED, comment: '来源店铺/仓库ID' }, inbound_type: { type: STRING(20), @@ -53,6 +54,7 @@ module.exports = app => { InboundOrder.associate = () => { app.model.InboundOrder.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + app.model.InboundOrder.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' }); app.model.InboundOrder.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' }); app.model.InboundOrder.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' }); app.model.InboundOrder.belongsTo(app.model.User, { foreignKey: 'created_by', as: 'creator' }); diff --git a/backend/app/model/outboundOrder.js b/backend/app/model/outboundOrder.js index 57ec8c6..66d4852 100644 --- a/backend/app/model/outboundOrder.js +++ b/backend/app/model/outboundOrder.js @@ -12,6 +12,7 @@ module.exports = app => { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, bill_no: { type: STRING(50), allowNull: false, comment: '出库单号' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + subsidiary_id: { type: BIGINT.UNSIGNED, comment: '所属货主(下属公司ID),跟随仓库' }, shop_id: { type: BIGINT.UNSIGNED, comment: '目标店铺/仓库ID' }, outbound_type: { type: STRING(20), @@ -62,6 +63,7 @@ module.exports = app => { OutboundOrder.associate = () => { app.model.OutboundOrder.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + app.model.OutboundOrder.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' }); app.model.OutboundOrder.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' }); app.model.OutboundOrder.belongsTo(app.model.Warehouse, { foreignKey: 'warehouse_id', as: 'warehouse' }); app.model.OutboundOrder.belongsTo(app.model.User, { foreignKey: 'created_by', as: 'creator' }); diff --git a/backend/app/utils/exportDefs.js b/backend/app/utils/exportDefs.js index eff286e..33d8342 100644 --- a/backend/app/utils/exportDefs.js +++ b/backend/app/utils/exportDefs.js @@ -206,6 +206,20 @@ function makeWhere() { return api; } +/** + * 追加「货主可见范围」条件(所在公司权限只能导出自己所属公司的数据;集团不加条件) + * @param {Object} wh makeWhere() 结果 + * @param {Object} ctx 导出上下文(含 access) + * @param {string} column 货主列(如 t.subsidiary_id) + * @return {void} 直接追加到 wh + */ +function applyBillOwnerScope(wh, ctx, column) { + if (!ctx.access || ctx.access.isGroup) return; + const ids = (ctx.access.ownCompanyIds || []).map(Number); + if (ids.length) wh.raw(`${column} IN (${ids.map(() => '?').join(',')})`, ...ids); + else wh.raw('1 = 0'); +} + /** * 组装导出查询结果 * @param {Object} options 组装参数 @@ -269,6 +283,11 @@ const ORDER_COLUMNS = [ const INBOUND_COLUMNS = [ { key: 'id', header: 'ID' }, { key: 'bill_no', header: '入库单号' }, + { + key: 'subsidiary_name', + header: '货主', + expr: '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id)', + }, { key: 'status', header: '状态', format: labels(BILL_STATUS_LABELS) }, { key: 'inbound_type', header: '入库类型', format: labels(INBOUND_ORDER_TYPES) }, { key: 'warehouse_id', header: '仓库ID' }, @@ -298,6 +317,11 @@ const INBOUND_COLUMNS = [ const OUTBOUND_COLUMNS = [ { key: 'id', header: 'ID' }, { key: 'bill_no', header: '出库单号' }, + { + key: 'subsidiary_name', + header: '货主', + expr: '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id)', + }, { key: 'status', header: '状态', format: labels(BILL_STATUS_LABELS) }, { key: 'outbound_type', header: '出库类型', format: labels(OUTBOUND_ORDER_TYPES) }, { key: 'warehouse_id', header: '仓库ID' }, @@ -331,6 +355,12 @@ const OUTBOUND_COLUMNS = [ const STOCK_RECORD_COLUMNS = [ { key: 'id', header: 'ID' }, { key: 'created_at', header: '记录时间' }, + { + key: 'subsidiary_name', + header: '货主', + expr: '(SELECT s.name FROM warehouses w LEFT JOIN principal_subsidiaries s ON s.id = w.subsidiary_id' + + ' WHERE w.id = t.warehouse_id)', + }, { key: 'biz_type', header: '业务动作', format: labels(BIZ_LABELS) }, { key: 'direction', header: '方向', format: labels(DIRECTION_MAP) }, { key: 'bill_type', header: '单据类型', format: labels(BILL_TYPE_MAP) }, @@ -736,6 +766,7 @@ const EXPORT_TYPES = { { key: 'status', label: '状态', type: 'select', options: BILL_STATUS_OPTIONS }, { key: 'inbound_type', label: '入库类型', type: 'select', options: INBOUND_TYPE_OPTIONS }, { key: 'warehouse_id', label: '仓库', type: 'warehouse' }, + { key: 'subsidiary_id', label: '货主', type: 'subsidiary' }, { key: 'keyword', label: '关键词', type: 'text', placeholder: '单号 / 供应商 / 运单号' }, { key: 'start_time', label: '创建时间起', type: 'date' }, { key: 'end_time', label: '创建时间止', type: 'date' }, @@ -747,9 +778,12 @@ const EXPORT_TYPES = { .eq('t.status', f.status) .eq('t.inbound_type', upper(f.inbound_type)) .eq('t.warehouse_id', f.warehouse_id) + .eq('t.subsidiary_id', f.subsidiary_id) .kw([ 't.bill_no', 't.supplier', 't.supplier_code', 't.express_code' ], f.keyword) .from('t.created_at', f.start_time) .to('t.created_at', f.end_time); + // 所在公司权限:只能导出自己所属公司(货主)的入库单 + applyBillOwnerScope(wh, ctx, 't.subsidiary_id'); return buildResult({ columns: INBOUND_COLUMNS, from: 'inbound_orders t', wh }); }, }, @@ -761,6 +795,7 @@ const EXPORT_TYPES = { { key: 'status', label: '状态', type: 'select', options: BILL_STATUS_OPTIONS }, { key: 'outbound_type', label: '出库类型', type: 'select', options: OUTBOUND_TYPE_OPTIONS }, { key: 'warehouse_id', label: '仓库', type: 'warehouse' }, + { key: 'subsidiary_id', label: '货主', type: 'subsidiary' }, { key: 'shop_id', label: '店铺', type: 'shop' }, { key: 'keyword', label: '关键词', type: 'text', placeholder: '单号 / 客户 / 收货人 / 运单号' }, { key: 'start_time', label: '创建时间起', type: 'date' }, @@ -773,10 +808,13 @@ const EXPORT_TYPES = { .eq('t.status', f.status) .eq('t.outbound_type', upper(f.outbound_type)) .eq('t.warehouse_id', f.warehouse_id) + .eq('t.subsidiary_id', f.subsidiary_id) .eq('t.shop_id', f.shop_id) .kw([ 't.bill_no', 't.customer', 't.receiver_name', 't.receiver_mobile', 't.express_code' ], f.keyword) .from('t.created_at', f.start_time) .to('t.created_at', f.end_time); + // 所在公司权限:只能导出自己所属公司(货主)的出库单 + applyBillOwnerScope(wh, ctx, 't.subsidiary_id'); return buildResult({ columns: OUTBOUND_COLUMNS, from: 'outbound_orders t', wh }); }, }, @@ -786,6 +824,7 @@ const EXPORT_TYPES = { filters: [ { key: 'product_id', label: '商品', type: 'product' }, { key: 'warehouse_id', label: '仓库', type: 'warehouse' }, + { key: 'subsidiary_id', label: '货主', type: 'subsidiary' }, { key: 'biz_type', label: '业务动作', type: 'select', options: BIZ_TYPE_OPTIONS }, { key: 'direction', label: '方向', type: 'select', options: DIRECTION_OPTIONS }, { key: 'bill_type', label: '单据类型', type: 'select', options: BILL_TYPE_OPTIONS }, @@ -808,6 +847,21 @@ const EXPORT_TYPES = { .kw([ 't.bill_no', 't.item_code', 't.item_name' ], f.keyword) .from('t.created_at', f.start_time) .to('t.created_at', f.end_time); + // 货主口径(流水按仓库归属货主):集团可按货主筛选,所在公司权限只能导出自己公司的流水 + if (f.subsidiary_id) { + wh.raw('t.warehouse_id IN (SELECT w.id FROM warehouses w WHERE w.subsidiary_id = ?)', Number(f.subsidiary_id)); + } + if (ctx.access && !ctx.access.isGroup) { + const ids = (ctx.access.ownCompanyIds || []).map(Number); + if (ids.length) { + wh.raw( + `t.warehouse_id IN (SELECT w.id FROM warehouses w WHERE w.subsidiary_id IN (${ids.map(() => '?').join(',')}))`, + ...ids + ); + } else { + wh.raw('1 = 0'); + } + } return buildResult({ columns: STOCK_RECORD_COLUMNS, from: 'stock_records t', wh }); }, }, diff --git a/backend/database/migrations/20261105070300-add-subsidiary-to-stock-bills.js b/backend/database/migrations/20261105070300-add-subsidiary-to-stock-bills.js new file mode 100644 index 0000000..e20a7a0 --- /dev/null +++ b/backend/database/migrations/20261105070300-add-subsidiary-to-stock-bills.js @@ -0,0 +1,41 @@ +'use strict'; + +/** + * 出入库单绑定货主(下属公司):inbound_orders / outbound_orders 增加 subsidiary_id。 + * + * 取值跟随单据仓库的货主(warehouses.subsidiary_id),历史数据按仓库回填; + * 货主权限仅可见自己所属公司的出入库单,且不可越界操作。 + */ +const BILL_TABLES = [ 'inbound_orders', 'outbound_orders' ]; + +module.exports = { + async up(queryInterface, Sequelize) { + for (const table of BILL_TABLES) { + await queryInterface.addColumn(table, 'subsidiary_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '所属货主(下属公司ID),跟随仓库', + references: { model: 'principal_subsidiaries', key: 'id' }, + after: 'principal_id', + }); + await queryInterface.addIndex(table, [ 'principal_id', 'subsidiary_id' ], { + name: `idx_${table}_principal_subsidiary`, + }); + + // 按单据仓库的货主回填历史数据 + await queryInterface.sequelize.query( + `UPDATE ${table} t` + + ' JOIN warehouses w ON w.id = t.warehouse_id' + + ' SET t.subsidiary_id = w.subsidiary_id' + + ' WHERE t.subsidiary_id IS NULL AND w.subsidiary_id IS NOT NULL' + ); + } + }, + + async down(queryInterface) { + for (const table of BILL_TABLES) { + await queryInterface.removeIndex(table, `idx_${table}_principal_subsidiary`); + await queryInterface.removeColumn(table, 'subsidiary_id'); + } + }, +}; diff --git a/frontend/src/api/inboundOrder.ts b/frontend/src/api/inboundOrder.ts index b8565b8..7f83a00 100644 --- a/frontend/src/api/inboundOrder.ts +++ b/frontend/src/api/inboundOrder.ts @@ -6,6 +6,10 @@ export interface InboundOrder { id: number bill_no: string principal_id: number + /** 所属货主(下属公司ID),跟随仓库 */ + subsidiary_id?: number | null + /** 所属货主名称(列表/详情接口返回) */ + subsidiary_name?: string shop_id: number | null inbound_type: string status: number @@ -13,7 +17,11 @@ export interface InboundOrder { warehouse?: { id: number; code: string; name: string } | null shop?: { id: number; name: string } | null creator?: { id: number; nickname?: string | null; username: string } | null + /** 创建人展示名(员工名称,后端按 principal_users.name 解析) */ + creator_name?: string auditor?: { id: number; nickname?: string | null; username: string } | null + /** 审核人展示名(员工名称) */ + auditor_name?: string audit_by?: number | null audit_time?: string | null supplier?: string | null @@ -54,6 +62,8 @@ export interface InboundOrder { void_by?: number | null void_reason?: string | null voider?: { id: number; nickname?: string | null; username: string } | null + /** 作废人展示名(员工名称) */ + voider_name?: string items?: StockItemLine[] created_at?: string updated_at?: string diff --git a/frontend/src/api/outboundOrder.ts b/frontend/src/api/outboundOrder.ts index 21301dd..d6ebe4c 100644 --- a/frontend/src/api/outboundOrder.ts +++ b/frontend/src/api/outboundOrder.ts @@ -6,6 +6,10 @@ export interface OutboundOrder { id: number bill_no: string principal_id: number + /** 所属货主(下属公司ID),跟随仓库 */ + subsidiary_id?: number | null + /** 所属货主名称(列表/详情接口返回) */ + subsidiary_name?: string shop_id: number | null outbound_type: string status: number @@ -16,6 +20,8 @@ export interface OutboundOrder { warehouse?: { id: number; code: string; name: string } | null shop?: { id: number; name: string } | null creator?: { id: number; nickname?: string | null; username: string } | null + /** 创建人展示名(员工名称,后端按 principal_users.name 解析) */ + creator_name?: string item_total: number | string item_kind: number | null total_amount: number | string @@ -47,6 +53,8 @@ export interface OutboundOrder { void_by?: number | null void_reason?: string | null voider?: { id: number; nickname?: string | null; username: string } | null + /** 作废人展示名(员工名称) */ + voider_name?: string pushed_at?: string | null wms_push_result?: { success?: boolean diff --git a/frontend/src/api/stockRecord.ts b/frontend/src/api/stockRecord.ts index 381a36a..92e001e 100644 --- a/frontend/src/api/stockRecord.ts +++ b/frontend/src/api/stockRecord.ts @@ -9,6 +9,10 @@ export interface StockRecordItem { id: number principal_id: number warehouse_id: number | null + /** 所属货主(下属公司ID),按仓库归属 */ + subsidiary_id?: number | null + /** 所属货主名称 */ + subsidiary_name?: string product_id: number | null item_code: string | null item_name: string | null diff --git a/frontend/src/views/InboundOrder/Index.vue b/frontend/src/views/InboundOrder/Index.vue index fe6aa9b..28ec0d7 100644 --- a/frontend/src/views/InboundOrder/Index.vue +++ b/frontend/src/views/InboundOrder/Index.vue @@ -18,6 +18,7 @@ import DataTable from '@/components/DataTable.vue' import ListPager from '@/components/ListPager.vue' import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage' import VirtualSelect from '@/components/VirtualSelect.vue' +import { getPrincipalSubsidiaryOptions } from '@/api/principalSubsidiary' import { formatDateTime } from '@/utils/datetime' const STATUS_LABELS: Record = { @@ -53,6 +54,7 @@ const query = reactive({ bill_no: '', status: '' as string | number, inbound_type: '' as string | number, + subsidiary_id: '' as string | number, }) const { loading, list, total, elapsed, fetchList, search, handlePageChange, handleSizeChange } = useListPage({ query, @@ -61,12 +63,18 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand if (!params.bill_no) delete params.bill_no if (params.status === '') delete params.status if (params.inbound_type === '') delete params.inbound_type + if (params.subsidiary_id === '') delete params.subsidiary_id return inboundOrderApi.getList(params) }, }) async function fetchWarehouses() { try { warehouses.value = await getWarehouseOptions() } catch { warehouses.value = [] } } +/** 货主(下属公司)下拉:所在公司权限只给自己所属公司 */ +const subsidiaryOptions = ref<{ id: number; name: string }[]>([]) +async function fetchSubsidiaries() { + try { subsidiaryOptions.value = await getPrincipalSubsidiaryOptions({ mine: 1 }) } catch { subsidiaryOptions.value = [] } +} /** 快递公司字典(编辑弹窗「物流公司」下拉选项) */ async function fetchExpressCompanies() { try { expressCompanies.value = await getExpressCompanyOptions() } catch { expressCompanies.value = [] } @@ -80,6 +88,7 @@ function reset() { query.bill_no = '' query.status = '' query.inbound_type = '' + query.subsidiary_id = '' search() } @@ -88,6 +97,7 @@ const exportFilters = computed(() => ({ bill_no: query.bill_no.trim(), status: query.status, inbound_type: query.inbound_type, + subsidiary_id: query.subsidiary_id, })) function typeLabel(row: InboundOrder) { return TYPE_OPTIONS.find((o) => o.value === row.inbound_type)?.label || String(row.inbound_type) @@ -446,6 +456,7 @@ onMounted(async () => { } await fetchWarehouses() await fetchExpressCompanies() + await fetchSubsidiaries() await fetchList() }) @@ -478,6 +489,11 @@ onMounted(async () => { + + + + + 查询 重置 @@ -493,6 +509,9 @@ onMounted(async () => { @row-click="handleRowClick" > + + + @@ -511,7 +530,7 @@ onMounted(async () => { - + @@ -597,7 +616,7 @@ onMounted(async () => { {{ currentOrder.operator || '-' }} {{ formatDateTime(currentOrder.audit_time) }} {{ currentOrder.total_amount }} - {{ currentOrder.voider?.nickname || currentOrder.voider?.username || '-' }} + {{ currentOrder.voider_name || currentOrder.voider?.nickname || currentOrder.voider?.username || '-' }} {{ formatDateTime(currentOrder.void_at) }} {{ currentOrder.void_reason || '-' }} {{ currentOrder.remark || '-' }} diff --git a/frontend/src/views/OutboundOrder/Index.vue b/frontend/src/views/OutboundOrder/Index.vue index d48467b..bf892d4 100644 --- a/frontend/src/views/OutboundOrder/Index.vue +++ b/frontend/src/views/OutboundOrder/Index.vue @@ -19,6 +19,7 @@ import ListPager from '@/components/ListPager.vue' import VirtualSelect from '@/components/VirtualSelect.vue' import ProductSelect from '@/components/ProductSelect.vue' import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage' +import { getPrincipalSubsidiaryOptions } from '@/api/principalSubsidiary' import { formatDateTime } from '@/utils/datetime' const STATUS_LABELS: Record = { @@ -48,6 +49,8 @@ const shopSelectOptions = computed(() => ) /** 快递公司字典(仅启用,供「物流公司」下拉,对齐 WMS stockout.create 的 deliveryOrder.logisticsCode) */ const expressCompanies = ref([]) +/** 货主(下属公司)下拉:所在公司权限只给自己所属公司 */ +const subsidiaryOptions = ref<{ id: number; name: string }[]>([]) /* -------------------- 列表 -------------------- */ const query = reactive({ @@ -56,6 +59,7 @@ const query = reactive({ bill_no: '', status: '' as string | number, outbound_type: '' as string | number, + subsidiary_id: '' as string | number, }) const { loading, list, total, elapsed, fetchList, search, handlePageChange, handleSizeChange } = useListPage({ query, @@ -64,6 +68,7 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand if (!params.bill_no) delete params.bill_no if (params.status === '') delete params.status if (params.outbound_type === '') delete params.outbound_type + if (params.subsidiary_id === '') delete params.subsidiary_id return outboundOrderApi.getList(params) }, }) @@ -71,11 +76,13 @@ async function fetchOptions() { try { warehouses.value = await getWarehouseOptions() } catch { warehouses.value = [] } try { shops.value = (await getShops({ pageSize: 200 })).list } catch { shops.value = [] } try { expressCompanies.value = await getExpressCompanyOptions() } catch { expressCompanies.value = [] } + try { subsidiaryOptions.value = await getPrincipalSubsidiaryOptions({ mine: 1 }) } catch { subsidiaryOptions.value = [] } } function reset() { query.bill_no = '' query.status = '' query.outbound_type = '' + query.subsidiary_id = '' search() } @@ -84,6 +91,7 @@ const exportFilters = computed(() => ({ bill_no: query.bill_no.trim(), status: query.status, outbound_type: query.outbound_type, + subsidiary_id: query.subsidiary_id, })) function typeLabel(row: OutboundOrder) { return TYPE_OPTIONS.find((o) => o.value === row.outbound_type)?.label || String(row.outbound_type) @@ -526,6 +534,11 @@ onMounted(async () => { + + + + + 查询 重置 @@ -541,6 +554,9 @@ onMounted(async () => { @row-click="handleRowClick" > + + + @@ -568,7 +584,7 @@ onMounted(async () => { - + @@ -641,7 +657,7 @@ onMounted(async () => { {{ [ currentOrder.receiver_province, currentOrder.receiver_city, currentOrder.receiver_area, currentOrder.receiver_town, currentOrder.receiver_detail_address ].filter(Boolean).join(' ') || '-' }} {{ currentOrder.remark || '-' }} - {{ currentOrder.voider?.nickname || currentOrder.voider?.username || '-' }} + {{ currentOrder.voider_name || currentOrder.voider?.nickname || currentOrder.voider?.username || '-' }} {{ formatDateTime(currentOrder.void_at) }} {{ currentOrder.void_reason || '-' }} diff --git a/frontend/src/views/StockRecord/Index.vue b/frontend/src/views/StockRecord/Index.vue index 336e802..f2fbeb7 100644 --- a/frontend/src/views/StockRecord/Index.vue +++ b/frontend/src/views/StockRecord/Index.vue @@ -13,6 +13,7 @@ import { type StockRecordItem, } from '@/api/stockRecord' import type { ProductSearchItem } from '@/api/product' +import { getPrincipalSubsidiaryOptions } from '@/api/principalSubsidiary' /** * 出入库记录(库存流水)页 @@ -46,6 +47,8 @@ const query = reactive({ biz_type: '', direction: '' as string | number, bill_type: '' as string | number, + /** 货主(下属公司ID),流水按仓库所属公司归属 */ + subsidiary_id: '' as string | number, dateRange: [] as string[], }) @@ -66,6 +69,7 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand if (query.biz_type) params.biz_type = query.biz_type if (query.direction !== '') params.direction = query.direction if (query.bill_type !== '') params.bill_type = query.bill_type + if (query.subsidiary_id !== '') params.subsidiary_id = query.subsidiary_id if (query.dateRange.length === 2) { params.start_time = query.dateRange[0] params.end_time = query.dateRange[1] @@ -82,10 +86,21 @@ const exportFilters = computed(() => ({ biz_type: query.biz_type, direction: query.direction, bill_type: query.bill_type, + subsidiary_id: query.subsidiary_id, start_time: query.dateRange[0], end_time: query.dateRange[1], })) +/** 货主(下属公司)下拉:所在公司权限只给自己所属公司 */ +const subsidiaryOptions = ref<{ id: number; name: string }[]>([]) +async function fetchSubsidiaries() { + try { + subsidiaryOptions.value = await getPrincipalSubsidiaryOptions({ mine: 1 }) + } catch { + subsidiaryOptions.value = [] + } +} + /** 业务动作下拉(后端返回枚举,避免文案漂移) */ const bizTypes = ref([]) async function fetchBizTypes() { @@ -117,6 +132,7 @@ function reset() { query.biz_type = '' query.direction = '' query.bill_type = '' + query.subsidiary_id = '' query.dateRange = [] onProductClear() search() @@ -142,6 +158,7 @@ function billTypeLabel(value: number | string): string { onMounted(() => { fetchBizTypes() + fetchSubsidiaries() fetchList() }) @@ -200,6 +217,11 @@ onMounted(() => { + + + + + { + + +