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: '店铺编码(同名店铺用于区分)' }, code: { type: 'string', description: '店铺编码(同名店铺用于区分)' },
name: { type: 'string', description: '店铺名称' }, name: { type: 'string', description: '店铺名称' },
type: { type: 'integer', description: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(手工建单排除 2)' }, type: { type: 'integer', description: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(手工建单排除 2)' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);建单时仓库与商品需与店铺同货主' },
}, },
/** 筛选条件下拉数据源(GET /api/order-status/filters) */ /** 筛选条件下拉数据源(GET /api/order-status/filters) */
orderStatusFilters: { orderStatusFilters: {
@ -2172,6 +2173,7 @@ module.exports = {
id: { type: 'integer', description: '仓库ID' }, id: { type: 'integer', description: '仓库ID' },
code: { type: 'string', description: '仓库编码' }, code: { type: 'string', description: '仓库编码' },
name: { type: 'string', description: '仓库名称' }, name: { type: 'string', description: '仓库名称' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);需与所选店铺同货主' },
}, },
orderStatusFiltersResponse: { orderStatusFiltersResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' }, code: { type: 'integer', description: '业务状态码,0 成功' },
@ -2312,14 +2314,14 @@ module.exports = {
parent_order_no: { type: 'string', description: '来源订单号(上游/平台订单号;与 order_no 至少传一个,都不传时按 FH_{id} 生成)' }, parent_order_no: { type: 'string', description: '来源订单号(上游/平台订单号;与 order_no 至少传一个,都不传时按 FH_{id} 生成)' },
order_no: { type: 'string', description: '订单号,缺省按「来源订单号-序号」自动生成;无来源单号时按 FH_{id} 生成(需主体内唯一)' }, order_no: { type: 'string', description: '订单号,缺省按「来源订单号-序号」自动生成;无来源单号时按 FH_{id} 生成(需主体内唯一)' },
items: { type: 'array', itemType: 'orderStatusItemLine', description: '商品明细(发货单口径;不传时可用 product_info 存快照)' }, 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: '商品明细快照' }, product_info: { type: 'array', itemType: 'orderStatusProductLine', description: '商品明细快照' },
receiver: { type: 'string', description: '收货人' }, receiver: { type: 'string', description: '收货人' },
address: { type: 'string', description: '收货地址(不传时按省市区镇 + 详细地址自动拼接)' }, address: { type: 'string', description: '收货地址(不传时按省市区镇 + 详细地址自动拼接)' },
remark: { type: 'string', description: '备注' }, remark: { type: 'string', description: '备注' },
// —— 以下为扩展字段(为容纳老表而扩展,均可由接口写入;系统托管字段见控制器注释)—— // —— 以下为扩展字段(为容纳老表而扩展,均可由接口写入;系统托管字段见控制器注释)——
order_type: { type: 'string', description: '订单类型:JYCK/HHCK/BFCK' }, 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: '仓库编码' }, warehouse_code: { type: 'string', description: '仓库编码' },
order_flag: { type: 'string', description: '订单标记' }, order_flag: { type: 'string', description: '订单标记' },
pre_delivery_order_code: { 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 warehouseId = Number(fields.warehouse_id);
const warehouse = await ctx.model.Warehouse.findOne({ const warehouse = await ctx.model.Warehouse.findOne({
where: { id: warehouseId, principal_id: principalId }, where: { id: warehouseId, principal_id: principalId },
attributes: [ 'id', 'code' ], attributes: [ 'id', 'code', 'subsidiary_id' ],
}); });
if (!warehouse) { if (!warehouse) {
const err = new Error('仓库不存在或不属于当前主体'); const err = new Error('仓库不存在或不属于当前主体');
err.status = 404; err.status = 404;
throw err; 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; fields.warehouse_id = warehouseId;
if (!fields.warehouse_code) fields.warehouse_code = warehouse.code; if (!fields.warehouse_code) fields.warehouse_code = warehouse.code;
} }
@ -726,6 +734,8 @@ class OrderStatusService extends Service {
err.status = 400; err.status = 400;
throw err; throw err;
} }
// 明细商品/组合必须与店铺同货主,避免通过接口注入其它货主的商品
await this._assertItemsOwner(items, shopSubsidiaryId, principalId);
} else { } else {
const receiverError = validateReceiver({ ...fields, receiver: payload.receiver }); const receiverError = validateReceiver({ ...fields, receiver: payload.receiver });
if (receiverError) { 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 商品总金额) * 重算单据的明细统计(item_total 总量 / item_kind 种类数 / item_amount 商品总金额)
* *
@ -1501,6 +1560,8 @@ class OrderStatusService extends Service {
err.status = 400; err.status = 400;
throw err; throw err;
} }
// 明细商品必须与订单货主一致
await this._assertItemsOwner(items, row.subsidiary_id, principalId);
const transaction = await ctx.model.transaction(); const transaction = await ctx.model.transaction();
try { try {
@ -1542,17 +1603,41 @@ class OrderStatusService extends Service {
delete body.parent_order_no; delete body.parent_order_no;
delete body.principal_id; delete body.principal_id;
delete body.items; delete body.items;
// 货主由店铺推导,不接受接口直接写入(防止绕过店铺改归属)
delete body.subsidiary_id;
const patch = this._pickCreateFields(body); const patch = this._pickCreateFields(body);
// 明细随表单一并保存:先校验,避免单据头已改、明细报错造成半成功 // 店铺变更:校验归属 + 刷新 shop_nick 快照(推送时靠 shopNick 匹配快递策略)
const items = Array.isArray(p.items) ? p.items : []; // 先于仓库 / 明细校验处理,换店铺后订单货主跟随新店铺,后续校验用生效货主
if (items.length) { let effectiveSubsidiaryId = row.subsidiary_id == null ? null : Number(row.subsidiary_id);
const invalidItems = validateItems(items); if (body.shop_id !== undefined) {
if (!invalidItems.ok) { const shopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id);
const err = new Error(invalidItems.message); patch.shop_id = shopId;
err.status = 400; 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; 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;
}
} }
// 仓库变更:校验归属 + 刷新 warehouse_code 快照 // 仓库变更:校验归属 + 刷新 warehouse_code 快照
@ -1563,39 +1648,39 @@ class OrderStatusService extends Service {
if (warehouseId) { if (warehouseId) {
const warehouse = await ctx.model.Warehouse.findOne({ const warehouse = await ctx.model.Warehouse.findOne({
where: { id: warehouseId, principal_id: principalId }, where: { id: warehouseId, principal_id: principalId },
attributes: [ 'id', 'code' ], attributes: [ 'id', 'code', 'subsidiary_id' ],
}); });
if (!warehouse) { if (!warehouse) {
const err = new Error('仓库不存在或不属于当前主体'); const err = new Error('仓库不存在或不属于当前主体');
err.status = 404; err.status = 404;
throw err; 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; patch.warehouse_code = warehouse.code;
} }
} }
// 店铺变更:校验归属 + 刷新 shop_nick 快照(推送时靠 shopNick 匹配快递策略) // 明细随表单一并保存:先校验,避免单据头已改、明细报错造成半成功
if (body.shop_id !== undefined) { const items = Array.isArray(p.items) ? p.items : [];
const shopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id); if (items.length) {
patch.shop_id = shopId; const invalidItems = validateItems(items);
patch.shop_nick = null; if (!invalidItems.ok) {
if (shopId) { const err = new Error(invalidItems.message);
const shop = await ctx.model.Shop.findOne({ err.status = 400;
where: { id: shopId, principal_id: principalId },
attributes: [ 'id', 'name' ],
});
if (!shop) {
const err = new Error('店铺不存在或不属于当前主体');
err.status = 404;
throw err; throw err;
} }
patch.shop_nick = shop.name; // 明细商品必须与生效货主一致(换店铺后按新货主校验)
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)) { if (body.shop_id !== undefined && this._isExternalPrintOrder(current)) {
const nextShopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id); const nextShopId = body.shop_id === null || body.shop_id === '' ? null : Number(body.shop_id);
if (nextShopId !== Number(current.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 } }); 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) { if (items.length) {
await this.saveItems({ order_id: row.id, items }); await this.saveItems({ order_id: row.id, items });
@ -1801,13 +1894,22 @@ class OrderStatusService extends Service {
const targets = indexRows; const targets = indexRows;
const warehouse = await ctx.model.Warehouse.findOne({ const warehouse = await ctx.model.Warehouse.findOne({
where: { id: targetId, principal_id: principalId }, where: { id: targetId, principal_id: principalId },
attributes: [ 'id', 'code', 'name' ], attributes: [ 'id', 'code', 'name', 'subsidiary_id' ],
}); });
if (!warehouse) { if (!warehouse) {
const err = new Error('仓库不存在或不属于当前主体'); const err = new Error('仓库不存在或不属于当前主体');
err.status = 404; err.status = 404;
throw err; 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 patch = { warehouse_id: targetId, warehouse_code: warehouse.code };
const target = { id: Number(warehouse.id), code: warehouse.code, name: warehouse.name }; const target = { id: Number(warehouse.id), code: warehouse.code, name: warehouse.name };
@ -1962,19 +2064,22 @@ class OrderStatusService extends Service {
async filters() { async filters() {
const { ctx } = this; const { ctx } = this;
const principalId = ctx.state.principalId; const principalId = ctx.state.principalId;
// 所在公司权限:店铺下拉只给自己所属公司(货主)的店铺 // 所在公司权限:店铺/仓库下拉只给自己所属公司(货主)的数据
const access = await this._scopeAccess(principalId); const access = await this._scopeAccess(principalId);
const ownScope = () => ({ [ctx.app.Sequelize.Op.in]: access.ownIds });
const shopWhere = { principal_id: principalId }; 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({ const shops = await ctx.model.Shop.findAll({
where: shopWhere, where: shopWhere,
attributes: [ 'id', 'code', 'name', 'type' ], attributes: [ 'id', 'code', 'name', 'type', 'subsidiary_id' ],
order: [[ 'id', 'ASC' ]], order: [[ 'id', 'ASC' ]],
limit: 500, limit: 500,
}); });
const warehouseWhere = { principal_id: principalId };
if (!access.isGroup) warehouseWhere.subsidiary_id = ownScope();
const warehouses = await ctx.model.Warehouse.findAll({ const warehouses = await ctx.model.Warehouse.findAll({
where: { principal_id: principalId }, where: warehouseWhere,
attributes: [ 'id', 'code', 'name' ], attributes: [ 'id', 'code', 'name', 'subsidiary_id' ],
order: [[ 'id', 'ASC' ]], order: [[ 'id', 'ASC' ]],
limit: 500, limit: 500,
}); });
@ -1991,11 +2096,13 @@ class OrderStatusService extends Service {
code: shop.code, code: shop.code,
name: shop.name, name: shop.name,
type: Number(shop.type) || 1, type: Number(shop.type) || 1,
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
})), })),
warehouses: warehouses.map(warehouse => ({ warehouses: warehouses.map(warehouse => ({
id: Number(warehouse.id), id: Number(warehouse.id),
code: warehouse.code, code: warehouse.code,
name: warehouse.name, 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 archive_months: number
/** 订单索引表名 */ /** 订单索引表名 */
index_table?: string index_table?: string
shops: { id: number; code?: string; name: string; type?: number }[] shops: { id: number; code?: string; name: string; type?: number; subsidiary_id?: number | null }[]
warehouses: { id: number; code: string; name: string }[] warehouses: { id: number; code: string; name: string; subsidiary_id?: number | null }[]
} }
/** 新建/编辑订单(发货单口径) */ /** 新建/编辑订单(发货单口径) */

View File

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

View File

@ -121,15 +121,12 @@ function fillItems(items: OrderItemLine[] | undefined) {
if (!form.items.length) form.items = [ emptyLine() ] 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,其订单只能由平台拉取) */ /** 手工建单可选店铺:排除外部打单平台店铺(type=2,其订单只能由平台拉取) */
const selectableShops = computed(() => (props.filters.shops || []).filter(shop => Number(shop.type ?? 1) !== 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 { function defaultShopIdOf(): number | null {
if (props.defaultShopId) return props.defaultShopId if (props.defaultShopId) return props.defaultShopId
@ -137,17 +134,40 @@ function defaultShopIdOf(): number | null {
return list.length ? list[0].id : 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) const isExternal = ref(false)
/** 外部单的店铺展示名:外部平台店铺不在可选列表里,直接显示名称而不是让下拉回显 ID */ /** 外部单的店铺展示名:外部平台店铺不在可选列表里,直接显示名称而不是让下拉回显 ID */
const externalShopLabel = ref('') const externalShopLabel = ref('')
function reset() { function reset() {
// 先定位默认店铺,仓库默认值依赖店铺所属货主
form.shop_id = defaultShopIdOf()
Object.assign(form, { Object.assign(form, {
parent_order_no: '', parent_order_no: '',
order_no: '', order_no: '',
warehouse_id: defaultWarehouseId(), warehouse_id: defaultWarehouseId(),
shop_id: defaultShopIdOf(), shop_id: form.shop_id,
order_type: 'JYCK', order_type: 'JYCK',
is_urgency: 'N', is_urgency: 'N',
invoice_flag: 'N', invoice_flag: 'N',
@ -369,12 +389,36 @@ watch(
() => props.filters, () => props.filters,
() => { () => {
if (!visible.value || isEdit.value) return 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.shop_id == null) form.shop_id = defaultShopIdOf()
if (form.warehouse_id == null) form.warehouse_id = defaultWarehouseId()
}, },
{ deep: true }, { 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() { function addLine() {
form.items = [ ...form.items, emptyLine() ] form.items = [ ...form.items, emptyLine() ]
@ -392,6 +436,8 @@ function onLineProductSelect(index: number, product: ProductSearchItem) {
line.item_id = product.id line.item_id = product.id
line.item_code = product.item_code || '' line.item_code = product.item_code || ''
line.item_name = product.item_name || '' line.item_name = product.item_name || ''
// 记录商品所属货主,切换店铺时用来校验 / 清空不一致的明细
itemOwnerMap.value[product.id] = product.subsidiary_id ?? null
} }
function lineAmount(line: OrderItemLine): string { function lineAmount(line: OrderItemLine): string {
@ -553,12 +599,13 @@ async function submit() {
<el-form-item label="仓库" prop="warehouse_id"> <el-form-item label="仓库" prop="warehouse_id">
<el-select v-model="form.warehouse_id" placeholder="请选择仓库" clearable filterable style="width: 100%"> <el-select v-model="form.warehouse_id" placeholder="请选择仓库" clearable filterable style="width: 100%">
<el-option <el-option
v-for="warehouse in props.filters.warehouses" v-for="warehouse in selectableWarehouses"
:key="warehouse.id" :key="warehouse.id"
:label="`${warehouse.name}(${warehouse.code})`" :label="`${warehouse.name}(${warehouse.code})`"
:value="warehouse.id" :value="warehouse.id"
/> />
</el-select> </el-select>
<div v-if="shopSubsidiaryId !== null" class="form-tip">仅可选择与所选店铺同货主(所属公司)的仓库</div>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
@ -799,6 +846,7 @@ async function submit() {
<ProductSelect <ProductSelect
v-model="row.item_id" v-model="row.item_id"
:model-label="[ row.item_code, row.item_name ].filter(Boolean).join(' ')" :model-label="[ row.item_code, row.item_name ].filter(Boolean).join(' ')"
:subsidiary-id="shopSubsidiaryId"
@select="(p: ProductSearchItem) => onLineProductSelect($index, p)" @select="(p: ProductSearchItem) => onLineProductSelect($index, p)"
/> />
</template> </template>