feat(order): 订单关联货主与越界操作拦截

- order_index 与各订单状态表新增 subsidiary_id(跟随店铺货主),历史数据按店铺回填
- 订单列表/详情/导出按货主范围过滤,货主权限仅可见自己所属公司的订单
- 订单 id 级操作统一在 _loadIndexRows 校验货主:审核/推送/驳回/取消/作废/恢复/改仓库物流/删除/明细维护越界返回 403
- 新建订单货主跟随店铺,货主权限只能为自己公司店铺建单;平台拉单写入时同步店铺货主
- 内部任务/平台回调无登录态时按系统操作处理,不受货主范围限制
- 订单列表与导出新增货主列

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-05 02:15:46 +08:00
parent 7c8e531362
commit 2d2f781f09
7 changed files with 180 additions and 6 deletions

View File

@ -33,6 +33,7 @@ function coreColumns(Sequelize, status) {
order_no: { type: STRING(50), allowNull: false, comment: '订单号(老 order_no / delivery_order_code)' },
parent_order_no: { type: STRING(50), comment: '来源订单号(外部平台唯一单号;店管家为系统编号 LogicOrderId)' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' },
subsidiary_id: { type: BIGINT.UNSIGNED, comment: '所属货主(下属公司ID),跟随店铺' },
shop_id: { type: BIGINT.UNSIGNED, comment: '店铺ID' },
product_info: { type: JsonType, comment: '商品明细快照(JSON 数组;结构化明细见 order_status_items)' },
receiver: { type: STRING(50), comment: '收货人(老 orders.receiver.name / order_deliveries.name)' },

View File

@ -19,6 +19,7 @@ module.exports = app => {
order_no: { type: STRING(50), allowNull: false, comment: '订单号' },
parent_order_no: { type: STRING(50), comment: '来源订单号(外部平台唯一单号;店管家为系统编号 LogicOrderId)' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' },
subsidiary_id: { type: BIGINT.UNSIGNED, comment: '所属货主(下属公司ID)' },
current_table: { type: STRING(16), allowNull: false, defaultValue: 'pending', comment: '当前所在表:pending/exception/outsourcing/delivery/history' },
current_status: { type: STRING(16), allowNull: false, defaultValue: 'pending', comment: '当前状态:pending 待审核 / exception 异常 / outsourcing 委外中 / delivery 配送 / history 历史' },
created_at: { type: DATE, comment: '创建时间(用于超 3 个月自动归档判断)' },

View File

@ -536,6 +536,8 @@ class ExternalPrintOrderService extends Service {
const fields = {
shop_id: shop.id,
// 订单货主跟随店铺(货主权限按此过滤)
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
// 外部打单平台订单:平台配置要求回打单平台取号时,推送 WMS 需在根节点下发 need_oms_waybill=1
need_oms_waybill: Number(account.platform && account.platform.fetch_waybill_no) === 1 ? 1 : 0,
// 订单页「店铺」列展示 OMS 店铺名(平台店铺名带手机号,写入 extend_props 备用)
@ -594,6 +596,7 @@ class ExternalPrintOrderService extends Service {
order_no: orderNo,
parent_order_no: externalOrderId,
principal_id: shop.principal_id,
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
current_table: ORDER_STATUS.PENDING,
current_status: ORDER_STATUS.PENDING,
}, { transaction });
@ -604,6 +607,7 @@ class ExternalPrintOrderService extends Service {
order_no: orderNo,
parent_order_no: externalOrderId,
principal_id: shop.principal_id,
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
status: ORDER_STATUS.PENDING,
}, { transaction });
}

View File

@ -135,6 +135,31 @@ class OrderStatusService extends Service {
return [ ...new Set(list.map(item => Number(item)).filter(id => Number.isInteger(id) && id > 0)) ];
}
/**
* 当前账号在该主体下的权限范围(集团 / 所在公司)
* @param {Number} principalId 主体ID
* @return {Promise<{isGroup: boolean, ownIds: Array<number>}>} 范围信息
*/
async _scopeAccess(principalId) {
const { ctx } = this;
// 内部任务 / 平台回调 / 定时任务没有登录态(ctx.userId 为空):按系统操作处理,不做货主范围限制
if (!ctx.userId) return { isGroup: true, ownIds: [] };
const access = await ctx.service.access.resolve(ctx.userId, principalId);
return { isGroup: !!access.isGroup, ownIds: (access.ownCompanyIds || []).map(Number) };
}
/**
* 判断订单货主是否在当前账号可见范围内
* @param {Object} access 权限范围
* @param {Number|null} subsidiaryId 订单货主ID
* @return {Boolean} 是否可见/可操作
*/
_isOwnAccess(access, subsidiaryId) {
if (access.isGroup) return true;
if (subsidiaryId === null || subsidiaryId === undefined) return false;
return access.ownIds.includes(Number(subsidiaryId));
}
/**
* 按 id 取索引表记录(主体隔离),并校验全部命中
* @param {Array} ids 订单 id
@ -158,6 +183,17 @@ class OrderStatusService extends Service {
throw err;
}
// 所在公司权限:只能操作自己所属公司(货主)的订单
const access = await this._scopeAccess(principalId);
if (!access.isGroup) {
const denied = rows.find(row => !this._isOwnAccess(access, row.subsidiary_id));
if (denied) {
const err = new Error(`订单 ${denied.order_no} 不属于自己所属公司(货主),无权操作`);
err.status = 403;
throw err;
}
}
// 索引表说在哪张表,就在哪张表;按表分组校验一次(避免逐条查询),找不到说明数据不一致
const idsByStatus = new Map();
for (const row of rows) {
@ -337,6 +373,12 @@ class OrderStatusService extends Service {
if (address) where.address = { [Op.like]: `%${address}%` };
if (remark) where.remark = { [Op.like]: `%${remark}%` };
if (p.shop_id !== undefined && p.shop_id !== '' && p.shop_id !== null) where.shop_id = Number(p.shop_id);
// 所在公司权限:仅列出自己所属公司(货主)的订单
const access = await this._scopeAccess(principalId);
if (!access.isGroup) {
where.subsidiary_id = { [Op.in]: access.ownIds };
}
if (keyword) {
where[Op.or] = [
{ order_no: { [Op.like]: `%${keyword}%` } },
@ -463,6 +505,21 @@ class OrderStatusService extends Service {
for (const row of list) row.shop_name = nameById.get(Number(row.shop_id)) || null;
}
// 货主名称(订单货主跟随店铺,列表按 id 批量补名称)
const subsidiaryIds = [
...new Set(list.map(row => Number(row.subsidiary_id)).filter(id => Number.isInteger(id) && id > 0)),
];
if (subsidiaryIds.length) {
const subsidiaries = await ctx.model.PrincipalSubsidiary.findAll({
where: { id: { [Op.in]: subsidiaryIds }, principal_id: principalId },
attributes: [ 'id', 'name' ],
});
const nameById = new Map(subsidiaries.map(item => [ Number(item.id), item.name ]));
for (const row of list) row.subsidiary_name = nameById.get(Number(row.subsidiary_id)) || '';
} else {
for (const row of list) row.subsidiary_name = '';
}
// 仓库名称(状态表只存 warehouse_id + warehouse_code 快照,列表按 id 批量补名称,列表展示名称而非编码)
const warehouseIds = [
...new Set(list.map(row => Number(row.warehouse_id)).filter(id => Number.isInteger(id) && id > 0)),
@ -612,11 +669,12 @@ class OrderStatusService extends Service {
}
let shopId = null;
let shopSubsidiaryId = null;
if (payload.shop_id !== undefined && payload.shop_id !== null && payload.shop_id !== '') {
shopId = Number(payload.shop_id);
const shop = await ctx.model.Shop.findOne({
where: { id: shopId, principal_id: principalId },
attributes: [ 'id', 'name', 'type' ],
attributes: [ 'id', 'name', 'type', 'subsidiary_id' ],
});
if (!shop) {
const err = new Error('店铺不存在或不属于当前主体');
@ -629,6 +687,14 @@ class OrderStatusService extends Service {
err.status = 400;
throw err;
}
// 订单货主跟随店铺;所在公司权限只能为自己所属公司(货主)的店铺建单
shopSubsidiaryId = shop.subsidiary_id == null ? null : Number(shop.subsidiary_id);
const access = await this._scopeAccess(principalId);
if (!access.isGroup && !this._isOwnAccess(access, shopSubsidiaryId)) {
const err = new Error('只能为自己所属公司(货主)的店铺创建订单');
err.status = 403;
throw err;
}
} else {
const err = new Error('请选择店铺(手工订单必须指定店铺,平台拉取的店铺不可选)');
err.status = 400;
@ -682,6 +748,7 @@ class OrderStatusService extends Service {
order_no: orderNo || `FH_TMP_${Date.now()}_${Math.floor(Math.random() * 100000)}`,
parent_order_no: parentOrderNo,
principal_id: principalId,
subsidiary_id: shopSubsidiaryId,
current_table: ORDER_STATUS.PENDING,
current_status: ORDER_STATUS.PENDING,
}, { transaction });
@ -709,6 +776,7 @@ class OrderStatusService extends Service {
order_no: orderNo,
parent_order_no: parentOrderNo,
principal_id: principalId,
subsidiary_id: shopSubsidiaryId,
shop_id: shopId,
shop_nick: shopNick || fields.shop_nick || null,
product_info: productInfo,
@ -1368,6 +1436,10 @@ class OrderStatusService extends Service {
const shop = await ctx.model.Shop.findByPk(plain.shop_id, { attributes: [ 'id', 'name' ] });
if (shop) plain.shop_name = shop.name;
}
if (plain.subsidiary_id) {
const subsidiary = await ctx.model.PrincipalSubsidiary.findByPk(plain.subsidiary_id, { attributes: [ 'id', 'name' ] });
plain.subsidiary_name = subsidiary ? subsidiary.name : '';
}
if (plain.warehouse_id) {
const warehouse = await ctx.model.Warehouse.findByPk(plain.warehouse_id, { attributes: [ 'id', 'code', 'name' ] });
if (warehouse) {
@ -1393,6 +1465,8 @@ class OrderStatusService extends Service {
err.status = 400;
throw err;
}
// 越界保护:明细需按订单的货主范围校验
await this._loadIndexRows([ orderId ], principalId);
const items = await ctx.model.OrderStatusItem.findAll({
where: { order_id: orderId, principal_id: principalId },
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
@ -1887,14 +1961,19 @@ class OrderStatusService extends Service {
*/
async filters() {
const { ctx } = this;
const principalId = ctx.state.principalId;
// 所在公司权限:店铺下拉只给自己所属公司(货主)的店铺
const access = await this._scopeAccess(principalId);
const shopWhere = { principal_id: principalId };
if (!access.isGroup) shopWhere.subsidiary_id = { [ctx.app.Sequelize.Op.in]: access.ownIds };
const shops = await ctx.model.Shop.findAll({
where: { principal_id: ctx.state.principalId },
where: shopWhere,
attributes: [ 'id', 'code', 'name', 'type' ],
order: [[ 'id', 'ASC' ]],
limit: 500,
});
const warehouses = await ctx.model.Warehouse.findAll({
where: { principal_id: ctx.state.principalId },
where: { principal_id: principalId },
attributes: [ 'id', 'code', 'name' ],
order: [[ 'id', 'ASC' ]],
limit: 500,

View File

@ -239,6 +239,7 @@ const ORDER_COLUMNS = [
{ key: 'order_type', header: '订单类型' },
{ key: 'shop_id', header: '店铺ID' },
{ key: 'shop_nick', header: '店铺名称' },
{ key: 'subsidiary_name', header: '货主' },
{ key: 'warehouse_id', header: '仓库ID' },
{ key: 'warehouse_code', header: '仓库编码' },
{ key: 'receiver', header: '收货人' },
@ -683,11 +684,20 @@ const EXPORT_TYPES = {
build: (f, ctx) => {
// 订单按状态分表存储:指定状态时只查对应表,未指定时 UNION ALL 各状态表
const stages = ORDER_TABLE_BY_STATUS[f.order_stage] ? [ f.order_stage ] : ORDER_STATUS_ORDER;
const select = ORDER_COLUMNS.map(c => c.key).join(', ');
const select = ORDER_COLUMNS
.map(c => (c.key === 'subsidiary_name'
? '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id) AS subsidiary_name'
: c.key))
.join(', ');
// 所在公司权限:只能导出自己所属公司(货主)的订单,条件写进各状态表子查询
const ownIds = ctx.access && !ctx.access.isGroup ? (ctx.access.ownCompanyIds || []).map(Number) : null;
const scopeSql = ownIds
? (ownIds.length ? ` AND t.subsidiary_id IN (${ownIds.map(() => '?').join(',')})` : ' AND 1 = 0')
: '';
const inner = stages.map(stage => {
const table = ORDER_TABLE_BY_STATUS[stage];
const archived = stage === ORDER_STATUS.HISTORY ? 't.archived_at' : 'NULL AS archived_at';
return `SELECT ${select}, ${archived} FROM ${table} t WHERE t.principal_id = ?`;
return `SELECT ${select}, ${archived} FROM ${table} t WHERE t.principal_id = ?${scopeSql}`;
}).join(' UNION ALL ');
const wh = makeWhere();
wh.like('order_no', f.order_no)
@ -712,7 +722,9 @@ const EXPORT_TYPES = {
columns: ORDER_COLUMNS,
from: `(${inner}) AS t`,
wh,
leadRepl: stages.map(() => ctx.principalId),
leadRepl: stages.flatMap(() => (ownIds && ownIds.length
? [ ctx.principalId, ...ownIds ]
: [ ctx.principalId ])),
});
},
},

View File

@ -0,0 +1,74 @@
'use strict';
/**
* 订单绑定下属公司(货主):order_index 与各订单状态表增加 subsidiary_id。
*
* 取值跟随订单所属店铺的货主(店铺 = 货主),历史数据按店铺回填;
* 货主权限仅可见自己所属公司的订单,且不可越界操作。
*/
const STATUS_TABLES = [
'order_status_pending',
'order_status_queued',
'order_status_exception',
'order_status_outsourcing',
'order_status_delivery',
'order_status_void',
'order_status_canceled',
'order_status_history',
];
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('order_index', 'subsidiary_id', {
type: Sequelize.BIGINT.UNSIGNED,
allowNull: true,
comment: '所属货主(下属公司ID),跟随店铺',
references: { model: 'principal_subsidiaries', key: 'id' },
after: 'principal_id',
});
await queryInterface.addIndex('order_index', [ 'principal_id', 'subsidiary_id' ], {
name: 'idx_order_index_principal_subsidiary',
});
for (const table of STATUS_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`,
});
}
// 按订单所属店铺的货主回填历史数据(状态表自带 shop_id;索引表按状态表回填)
for (const table of STATUS_TABLES) {
await queryInterface.sequelize.query(
`UPDATE ${table} t`
+ ' JOIN shops s ON s.id = t.shop_id'
+ ' SET t.subsidiary_id = s.subsidiary_id'
+ ' WHERE t.subsidiary_id IS NULL AND s.subsidiary_id IS NOT NULL'
);
}
const unionSql = STATUS_TABLES
.map(table => `SELECT id, subsidiary_id FROM ${table} WHERE subsidiary_id IS NOT NULL`)
.join(' UNION ALL ');
await queryInterface.sequelize.query(
'UPDATE order_index oi'
+ ` JOIN (${unionSql}) st ON st.id = oi.id`
+ ' SET oi.subsidiary_id = st.subsidiary_id'
+ ' WHERE oi.subsidiary_id IS NULL'
);
},
async down(queryInterface) {
for (const table of STATUS_TABLES) {
await queryInterface.removeIndex(table, `idx_${table}_principal_subsidiary`);
await queryInterface.removeColumn(table, 'subsidiary_id');
}
await queryInterface.removeIndex('order_index', 'idx_order_index_principal_subsidiary');
await queryInterface.removeColumn('order_index', 'subsidiary_id');
},
};

View File

@ -887,6 +887,9 @@ onMounted(async () => {
<el-table-column label="店铺" width="120" show-overflow-tooltip>
<template #default="{ row }">{{ row.shop_name || '-' }}</template>
</el-table-column>
<el-table-column label="货主" width="130" show-overflow-tooltip>
<template #default="{ row }">{{ row.subsidiary_name || '-' }}</template>
</el-table-column>
<el-table-column label="商品明细" min-width="180" show-overflow-tooltip>
<template #default="{ row }">{{ row.product_summary || '-' }}</template>
</el-table-column>