feat(order): 建单仓库/商品按店铺货主限制并校验防注入

- create:仓库必须与店铺同货主;新增 _assertItemsOwner 校验明细商品/组合货主
  (兼容 item_id / product_id 两种明细口径)
- update:先处理店铺变更并推导生效货主(越权换店铺 403),仓库与明细按生效货主校验,
  货主变更同步 order_index;subsidiary_id 禁止接口直写
- saveItems / changeWarehouse:补充同货主校验
- filters:货主权限下仓库下拉同步收窄,店铺/仓库下拉返回 subsidiary_id
- 前端:建单弹窗仓库按店铺货主过滤、切店铺自动回落并清空跨货主商品,
  ProductSelect 新增 subsidiaryId 透传商品搜索与查询弹窗
- 契约:店铺/仓库下拉项补 subsidiary_id,建单店铺/仓库字段说明同货主约束
This commit is contained in:
liufumingren 2026-11-05 03:09:34 +08:00
parent baa89a7509
commit d68ee9905d
5 changed files with 218 additions and 48 deletions

View File

@ -2155,6 +2155,7 @@ module.exports = {
code: { type: 'string', description: '店铺编码(同名店铺用于区分)' },
name: { type: 'string', description: '店铺名称' },
type: { type: 'integer', description: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(手工建单排除 2)' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);建单时仓库与商品需与店铺同货主' },
},
/** 筛选条件下拉数据源(GET /api/order-status/filters) */
orderStatusFilters: {
@ -2172,6 +2173,7 @@ module.exports = {
id: { type: 'integer', description: '仓库ID' },
code: { type: 'string', description: '仓库编码' },
name: { type: 'string', description: '仓库名称' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);需与所选店铺同货主' },
},
orderStatusFiltersResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' },
@ -2312,14 +2314,14 @@ module.exports = {
parent_order_no: { type: 'string', description: '来源订单号(上游/平台订单号;与 order_no 至少传一个,都不传时按 FH_{id} 生成)' },
order_no: { type: 'string', description: '订单号,缺省按「来源订单号-序号」自动生成;无来源单号时按 FH_{id} 生成(需主体内唯一)' },
items: { type: 'array', itemType: 'orderStatusItemLine', description: '商品明细(发货单口径;不传时可用 product_info 存快照)' },
shop_id: { type: 'integer', description: '店铺ID(需属于当前主体,同步写 shop_nick 快照)' },
shop_id: { type: 'integer', description: '店铺ID(需属于当前主体;手工建单排除外部打单平台店铺;订单货主跟随店铺,所在公司权限只能选自己所属公司的店铺)' },
product_info: { type: 'array', itemType: 'orderStatusProductLine', description: '商品明细快照' },
receiver: { type: 'string', description: '收货人' },
address: { type: 'string', description: '收货地址(不传时按省市区镇 + 详细地址自动拼接)' },
remark: { type: 'string', description: '备注' },
// —— 以下为扩展字段(为容纳老表而扩展,均可由接口写入;系统托管字段见控制器注释)——
order_type: { type: 'string', description: '订单类型:JYCK/HHCK/BFCK' },
warehouse_id: { type: 'integer', description: '仓库ID' },
warehouse_id: { type: 'integer', description: '仓库ID(需属于当前主体且与店铺同货主)' },
warehouse_code: { type: 'string', description: '仓库编码' },
order_flag: { type: 'string', description: '订单标记' },
pre_delivery_order_code: { type: 'string', description: '预发货单号' },

View File

@ -707,13 +707,21 @@ class OrderStatusService extends Service {
const warehouseId = Number(fields.warehouse_id);
const warehouse = await ctx.model.Warehouse.findOne({
where: { id: warehouseId, principal_id: principalId },
attributes: [ 'id', 'code' ],
attributes: [ 'id', 'code', 'subsidiary_id' ],
});
if (!warehouse) {
const err = new Error('仓库不存在或不属于当前主体');
err.status = 404;
throw err;
}
// 仓库必须与店铺同货主,避免通过接口注入其它货主的仓库
if (shopSubsidiaryId !== null
&& warehouse.subsidiary_id != null
&& Number(warehouse.subsidiary_id) !== shopSubsidiaryId) {
const err = new Error('仓库不属于该店铺的货主,请选择同货主的仓库');
err.status = 400;
throw err;
}
fields.warehouse_id = warehouseId;
if (!fields.warehouse_code) fields.warehouse_code = warehouse.code;
}
@ -726,6 +734,8 @@ class OrderStatusService extends Service {
err.status = 400;
throw err;
}
// 明细商品/组合必须与店铺同货主,避免通过接口注入其它货主的商品
await this._assertItemsOwner(items, shopSubsidiaryId, principalId);
} else {
const receiverError = validateReceiver({ ...fields, receiver: payload.receiver });
if (receiverError) {
@ -808,6 +818,55 @@ class OrderStatusService extends Service {
}
}
/**
* 校验订单明细的商品/组合与订单货主一致(防止接口注入其它货主的商品)
* @param {Array} items 明细 [{ item_id / product_id / combo_product_id, ... }]
* @param {Number|null} subsidiaryId 订单货主ID
* @param {Number} principalId 主体ID
* @return {Promise<void>} 不通过时抛出 400
*/
async _assertItemsOwner(items, subsidiaryId, principalId) {
const { ctx } = this;
const Op = ctx.app.Sequelize.Op;
// 明细既有新建订单的 item_id,也有历史排单口径的 product_id,两者都按商品校验
const pickProductId = it => Number(it && (it.item_id != null && it.item_id !== '' ? it.item_id : it.product_id));
const productIds = [ ...new Set(items.map(pickProductId).filter(id => Number.isInteger(id) && id > 0)) ];
const comboIds = [ ...new Set(items.map(it => Number(it && it.combo_product_id)).filter(id => Number.isInteger(id) && id > 0)) ];
if (!productIds.length && !comboIds.length) return;
const [ products, combos ] = await Promise.all([
productIds.length
? ctx.model.Product.findAll({
where: { id: { [Op.in]: productIds }, principal_id: principalId },
attributes: [ 'id', 'subsidiary_id' ],
raw: true,
})
: [],
comboIds.length
? ctx.model.ComboProduct.findAll({
where: { id: { [Op.in]: comboIds }, principal_id: principalId },
attributes: [ 'id', 'subsidiary_id' ],
raw: true,
})
: [],
]);
if (products.length !== productIds.length || combos.length !== comboIds.length) {
const err = new Error('明细中存在无效商品(不存在或不属于当前主体)');
err.status = 400;
throw err;
}
if (subsidiaryId === null || subsidiaryId === undefined) return;
const mismatch = [ ...products, ...combos ].find(
row => row.subsidiary_id != null && Number(row.subsidiary_id) !== Number(subsidiaryId)
);
if (mismatch) {
const err = new Error('明细商品不属于该订单的货主,请选择同货主的商品');
err.status = 400;
throw err;
}
}
/**
* 重算单据的明细统计(item_total 总量 / item_kind 种类数 / item_amount 商品总金额)
*
@ -1501,6 +1560,8 @@ class OrderStatusService extends Service {
err.status = 400;
throw err;
}
// 明细商品必须与订单货主一致
await this._assertItemsOwner(items, row.subsidiary_id, principalId);
const transaction = await ctx.model.transaction();
try {
@ -1542,16 +1603,40 @@ class OrderStatusService extends Service {
delete body.parent_order_no;
delete body.principal_id;
delete body.items;
// 货主由店铺推导,不接受接口直接写入(防止绕过店铺改归属)
delete body.subsidiary_id;
const patch = this._pickCreateFields(body);
// 明细随表单一并保存:先校验,避免单据头已改、明细报错造成半成功
const items = Array.isArray(p.items) ? p.items : [];
if (items.length) {
const invalidItems = validateItems(items);
if (!invalidItems.ok) {
const err = new Error(invalidItems.message);
err.status = 400;
throw err;
// 店铺变更:校验归属 + 刷新 shop_nick 快照(推送时靠 shopNick 匹配快递策略)
// 先于仓库 / 明细校验处理,换店铺后订单货主跟随新店铺,后续校验用生效货主
let effectiveSubsidiaryId = row.subsidiary_id == null ? null : Number(row.subsidiary_id);
if (body.shop_id !== undefined) {
const shopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id);
patch.shop_id = shopId;
patch.shop_nick = null;
if (shopId) {
const shop = await ctx.model.Shop.findOne({
where: { id: shopId, principal_id: principalId },
attributes: [ 'id', 'name', 'subsidiary_id' ],
});
if (!shop) {
const err = new Error('店铺不存在或不属于当前主体');
err.status = 404;
throw err;
}
const nextSubsidiaryId = shop.subsidiary_id == null ? null : Number(shop.subsidiary_id);
// 换店铺时订单货主跟随新店铺;所在公司权限只能换到自己所属公司的店铺
if (nextSubsidiaryId !== effectiveSubsidiaryId) {
const access = await this._scopeAccess(principalId);
if (!access.isGroup && !this._isOwnAccess(access, nextSubsidiaryId)) {
const err = new Error('只能选择自己所属公司(货主)的店铺');
err.status = 403;
throw err;
}
patch.subsidiary_id = nextSubsidiaryId;
effectiveSubsidiaryId = nextSubsidiaryId;
}
patch.shop_nick = shop.name;
}
}
@ -1563,39 +1648,39 @@ class OrderStatusService extends Service {
if (warehouseId) {
const warehouse = await ctx.model.Warehouse.findOne({
where: { id: warehouseId, principal_id: principalId },
attributes: [ 'id', 'code' ],
attributes: [ 'id', 'code', 'subsidiary_id' ],
});
if (!warehouse) {
const err = new Error('仓库不存在或不属于当前主体');
err.status = 404;
throw err;
}
// 仓库必须与订单货主一致,避免通过接口注入其它货主的仓库
if (effectiveSubsidiaryId !== null && warehouse.subsidiary_id != null
&& Number(warehouse.subsidiary_id) !== effectiveSubsidiaryId) {
const err = new Error('仓库不属于该订单的货主,请选择同货主的仓库');
err.status = 400;
throw err;
}
patch.warehouse_code = warehouse.code;
}
}
// 店铺变更:校验归属 + 刷新 shop_nick 快照(推送时靠 shopNick 匹配快递策略)
if (body.shop_id !== undefined) {
const shopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id);
patch.shop_id = shopId;
patch.shop_nick = null;
if (shopId) {
const shop = await ctx.model.Shop.findOne({
where: { id: shopId, principal_id: principalId },
attributes: [ 'id', 'name' ],
});
if (!shop) {
const err = new Error('店铺不存在或不属于当前主体');
err.status = 404;
throw err;
}
patch.shop_nick = shop.name;
// 明细随表单一并保存:先校验,避免单据头已改、明细报错造成半成功
const items = Array.isArray(p.items) ? p.items : [];
if (items.length) {
const invalidItems = validateItems(items);
if (!invalidItems.ok) {
const err = new Error(invalidItems.message);
err.status = 400;
throw err;
}
// 明细商品必须与生效货主一致(换店铺后按新货主校验)
await this._assertItemsOwner(items, effectiveSubsidiaryId, principalId);
}
const current = await this._model(row.current_status).findByPk(row.id);
// 店铺由平台决定:平台拉取的订单不允许通过编辑改店铺
const current = await this._model(row.current_status).findByPk(row.id);
if (body.shop_id !== undefined && this._isExternalPrintOrder(current)) {
const nextShopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id);
if (nextShopId !== Number(current.shop_id)) {
@ -1618,6 +1703,14 @@ class OrderStatusService extends Service {
await this._model(row.current_status).update(patch, { where: { id: row.id, principal_id: principalId } });
// 货主变更要同步索引表(越权校验与列表都依赖 order_index.subsidiary_id)
if (patch.subsidiary_id !== undefined) {
await ctx.model.OrderIndex.update(
{ subsidiary_id: patch.subsidiary_id },
{ where: { id: row.id, principal_id: principalId } }
);
}
// 明细覆盖式保存(含统计与商品总金额重算)
if (items.length) {
await this.saveItems({ order_id: row.id, items });
@ -1801,13 +1894,22 @@ class OrderStatusService extends Service {
const targets = indexRows;
const warehouse = await ctx.model.Warehouse.findOne({
where: { id: targetId, principal_id: principalId },
attributes: [ 'id', 'code', 'name' ],
attributes: [ 'id', 'code', 'name', 'subsidiary_id' ],
});
if (!warehouse) {
const err = new Error('仓库不存在或不属于当前主体');
err.status = 404;
throw err;
}
// 仓库必须与订单货主一致,避免通过接口注入其它货主的仓库
const mismatch = indexRows.find(row => row.subsidiary_id != null
&& warehouse.subsidiary_id != null
&& Number(warehouse.subsidiary_id) !== Number(row.subsidiary_id));
if (mismatch) {
const err = new Error(`仓库不属于订单 ${mismatch.order_no} 的货主,请选择同货主的仓库`);
err.status = 400;
throw err;
}
const patch = { warehouse_id: targetId, warehouse_code: warehouse.code };
const target = { id: Number(warehouse.id), code: warehouse.code, name: warehouse.name };
@ -1962,19 +2064,22 @@ class OrderStatusService extends Service {
async filters() {
const { ctx } = this;
const principalId = ctx.state.principalId;
// 所在公司权限:店铺下拉只给自己所属公司(货主)的店铺
// 所在公司权限:店铺/仓库下拉只给自己所属公司(货主)的数据
const access = await this._scopeAccess(principalId);
const ownScope = () => ({ [ctx.app.Sequelize.Op.in]: access.ownIds });
const shopWhere = { principal_id: principalId };
if (!access.isGroup) shopWhere.subsidiary_id = { [ctx.app.Sequelize.Op.in]: access.ownIds };
if (!access.isGroup) shopWhere.subsidiary_id = ownScope();
const shops = await ctx.model.Shop.findAll({
where: shopWhere,
attributes: [ 'id', 'code', 'name', 'type' ],
attributes: [ 'id', 'code', 'name', 'type', 'subsidiary_id' ],
order: [[ 'id', 'ASC' ]],
limit: 500,
});
const warehouseWhere = { principal_id: principalId };
if (!access.isGroup) warehouseWhere.subsidiary_id = ownScope();
const warehouses = await ctx.model.Warehouse.findAll({
where: { principal_id: principalId },
attributes: [ 'id', 'code', 'name' ],
where: warehouseWhere,
attributes: [ 'id', 'code', 'name', 'subsidiary_id' ],
order: [[ 'id', 'ASC' ]],
limit: 500,
});
@ -1991,11 +2096,13 @@ class OrderStatusService extends Service {
code: shop.code,
name: shop.name,
type: Number(shop.type) || 1,
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
})),
warehouses: warehouses.map(warehouse => ({
id: Number(warehouse.id),
code: warehouse.code,
name: warehouse.name,
subsidiary_id: warehouse.subsidiary_id == null ? null : Number(warehouse.subsidiary_id),
})),
};
}

View File

@ -190,8 +190,8 @@ export interface OrderStatusFilters {
archive_months: number
/** 订单索引表名 */
index_table?: string
shops: { id: number; code?: string; name: string; type?: number }[]
warehouses: { id: number; code: string; name: string }[]
shops: { id: number; code?: string; name: string; type?: number; subsidiary_id?: number | null }[]
warehouses: { id: number; code: string; name: string; subsidiary_id?: number | null }[]
}
/** 新建/编辑订单(发货单口径) */

View File

@ -15,11 +15,14 @@ const props = withDefaults(
disabled?: boolean
/** 已选中但选项尚未加载(如编辑回显)时用于展示的标签 */
modelLabel?: string
/** 限定商品所属货主(下单时按店铺货主收窄,避免选到其它货主的商品) */
subsidiaryId?: number | null
}>(),
{
placeholder: '搜索并选择商品',
disabled: false,
modelLabel: '',
subsidiaryId: null,
},
)
@ -34,7 +37,10 @@ const loading = ref(false)
async function remoteMethod(keyword: string) {
loading.value = true
try {
options.value = await searchProducts(keyword || '')
options.value = await searchProducts(
keyword || '',
props.subsidiaryId == null ? undefined : { subsidiary_id: props.subsidiaryId },
)
} catch {
options.value = []
} finally {
@ -99,6 +105,7 @@ async function fetchPicker() {
pageSize: pickerPageSize.value,
keyword: searchKey.value || undefined,
status: 1,
...(props.subsidiaryId == null ? {} : { subsidiary_id: props.subsidiaryId }),
})
pickerList.value = res.list
pickerTotal.value = res.total
@ -169,6 +176,7 @@ function pickProduct(row: ProductItem) {
<el-button @click="searchKey = ''; onPickerSearch()">重置</el-button>
</el-form-item>
</el-form>
<div v-if="subsidiaryId != null" class="picker-tip">仅显示当前所选店铺同货主(所属公司)的商品</div>
<el-table
:data="pickerList"
v-loading="pickerLoading"
@ -219,6 +227,11 @@ function pickProduct(row: ProductItem) {
.picker-search {
margin-bottom: 6px;
}
.picker-tip {
margin-bottom: 6px;
color: var(--el-text-color-secondary);
font-size: 12px;
}
.picker-pager {
margin-top: 8px;
justify-content: flex-end;

View File

@ -121,15 +121,12 @@ function fillItems(items: OrderItemLine[] | undefined) {
if (!form.items.length) form.items = [ emptyLine() ]
}
/** 默认仓库:取当前主体仓库列表第一个(与老发货单一致,减少手工选择) */
function defaultWarehouseId(): number | null {
const list = props.filters.warehouses || []
return list.length ? list[0].id : null
}
/** 手工建单可选店铺:排除外部打单平台店铺(type=2,其订单只能由平台拉取) */
const selectableShops = computed(() => (props.filters.shops || []).filter(shop => Number(shop.type ?? 1) !== 2))
/** item_id → 商品所属货主;用于切换店铺后校验已选明细是否同货主 */
const itemOwnerMap = ref<Record<number, number | null>>({})
/** 默认店铺:优先父级入口指定的店铺,否则取可选店铺列表第一个 */
function defaultShopIdOf(): number | null {
if (props.defaultShopId) return props.defaultShopId
@ -137,17 +134,40 @@ function defaultShopIdOf(): number | null {
return list.length ? list[0].id : null
}
/** 当前选中店铺的所属货主(null 表示主体级店铺):仓库与商品只能选该货主下的数据 */
const shopSubsidiaryId = computed<number | null>(() => {
const shop = (props.filters.shops || []).find(item => item.id === form.shop_id)
const sid = shop?.subsidiary_id
return sid === null || sid === undefined ? null : Number(sid)
})
/** 仓库下拉:店铺有货主时只保留同货主仓库(历史未关联货主的仓库保持可选) */
const selectableWarehouses = computed(() => {
const list = props.filters.warehouses || []
const sid = shopSubsidiaryId.value
if (sid === null) return list
return list.filter(item => item.subsidiary_id == null || Number(item.subsidiary_id) === sid)
})
/** 默认仓库:取当前店铺货主下的第一个仓库(与老发货单一致,减少手工选择) */
function defaultWarehouseId(): number | null {
const list = selectableWarehouses.value
return list.length ? list[0].id : null
}
/** 当前编辑的单据是否由外部打单平台拉取(店铺不可修改) */
const isExternal = ref(false)
/** 外部单的店铺展示名:外部平台店铺不在可选列表里,直接显示名称而不是让下拉回显 ID */
const externalShopLabel = ref('')
function reset() {
// 先定位默认店铺,仓库默认值依赖店铺所属货主
form.shop_id = defaultShopIdOf()
Object.assign(form, {
parent_order_no: '',
order_no: '',
warehouse_id: defaultWarehouseId(),
shop_id: defaultShopIdOf(),
shop_id: form.shop_id,
order_type: 'JYCK',
is_urgency: 'N',
invoice_flag: 'N',
@ -369,12 +389,36 @@ watch(
() => props.filters,
() => {
if (!visible.value || isEdit.value) return
if (form.warehouse_id == null) form.warehouse_id = defaultWarehouseId()
if (form.shop_id == null) form.shop_id = defaultShopIdOf()
if (form.warehouse_id == null) form.warehouse_id = defaultWarehouseId()
},
{ deep: true },
)
// 切换店铺后,仓库与明细商品都必须与该店铺同货主
watch(shopSubsidiaryId, sid => {
if (!visible.value) return
const list = selectableWarehouses.value
if (form.warehouse_id != null && list.some(item => item.id === form.warehouse_id)) {
// 仓库已同货主,无需调整
} else {
form.warehouse_id = list.length ? list[0].id : null
}
if (sid === null) return
// 已选商品若属于其它货主,直接清空(后端同样会拦截,避免提交后才报错)
let cleared = 0
for (const line of form.items) {
if (!line.item_id) continue
const owner = itemOwnerMap.value[line.item_id]
if (owner === undefined || owner === null || Number(owner) === sid) continue
line.item_id = null
line.item_code = ''
line.item_name = ''
cleared += 1
}
if (cleared) ElMessage.warning(`已清空 ${cleared} 行与所选店铺货主不一致的商品,请重新选择`)
})
/* -------------------- 明细 -------------------- */
function addLine() {
form.items = [ ...form.items, emptyLine() ]
@ -392,6 +436,8 @@ function onLineProductSelect(index: number, product: ProductSearchItem) {
line.item_id = product.id
line.item_code = product.item_code || ''
line.item_name = product.item_name || ''
// 记录商品所属货主,切换店铺时用来校验 / 清空不一致的明细
itemOwnerMap.value[product.id] = product.subsidiary_id ?? null
}
function lineAmount(line: OrderItemLine): string {
@ -553,12 +599,13 @@ async function submit() {
<el-form-item label="仓库" prop="warehouse_id">
<el-select v-model="form.warehouse_id" placeholder="请选择仓库" clearable filterable style="width: 100%">
<el-option
v-for="warehouse in props.filters.warehouses"
v-for="warehouse in selectableWarehouses"
:key="warehouse.id"
:label="`${warehouse.name}(${warehouse.code})`"
:value="warehouse.id"
/>
</el-select>
<div v-if="shopSubsidiaryId !== null" class="form-tip">仅可选择与所选店铺同货主(所属公司)的仓库</div>
</el-form-item>
</el-col>
<el-col :span="12">
@ -799,6 +846,7 @@ async function submit() {
<ProductSelect
v-model="row.item_id"
:model-label="[ row.item_code, row.item_name ].filter(Boolean).join(' ')"
:subsidiary-id="shopSubsidiaryId"
@select="(p: ProductSearchItem) => onLineProductSelect($index, p)"
/>
</template>