feat(stock): 出入库单仓库与商品按货主双向限制并校验防注入

- 新增 app/lib/billOwnerScope.js:仓库可访问性(主体 + 所在公司)、明细商品/组合
  与仓库同货主校验、按单据仓库取货主
- 入库单/出库单 create:仓库可访问且明细商品必须与仓库同货主
  (原明细校验未带 principal_id,一并修正)
- 入库单/出库单 update:改仓库时校验新仓库可访问且已有明细同货主
- 明细接口(stock_items create/update):按所属单据仓库货主校验商品,堵住
  单据建好后再塞入其它货主商品的路径
- 前端新增 useWarehouseGoodsScope:仓库与商品双向约束(先选仓库限制商品、
  先选商品限制仓库、同单明细不得跨货主)
- 入库/出库创建页与单据明细编辑区接入该约束并给出提示
- ProductSelect 新增 beforeSelect 前置校验与受控显示值,校验不通过时回滚显示
This commit is contained in:
liufumingren 2026-11-05 15:02:12 +08:00
parent d68ee9905d
commit 4e56077770
10 changed files with 491 additions and 41 deletions

View File

@ -6,6 +6,7 @@ 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 QimenWmsClient = require('../lib/wms/qimenClient');
const { DEFAULT_INBOUND_ORDER_TYPE, INBOUND_ORDER_TYPE_LIST, normalizeInboundOrderType } = require('../lib/wms/orderTypes');
@ -149,7 +150,8 @@ class InboundOrderController extends Controller {
/**
* @summary 新增入库单
* @description 单号由系统按 RK_{自增id} 自动生成(不接受传入);仓库必填;可同时传入 items(stock_items, bill_type=1)一次性写入明细
* @description 单号由系统按 RK_{自增id} 自动生成(不接受传入);仓库必填;可同时传入 items(stock_items, bill_type=1)一次性写入明细。
* 单据货主由仓库决定(warehouses.subsidiary_id),明细商品/组合必须与仓库同货主,否则拒绝创建
* @router post /api/inbound-orders
* @apikey
* @request body createInboundOrderRequest *body
@ -181,19 +183,20 @@ class InboundOrderController extends Controller {
}
payload.inbound_type = inboundType || DEFAULT_INBOUND_ORDER_TYPE;
// 校验明细关联商品均存在且已启用
const productIds = (items || []).map((i) => i.product_id).filter(Boolean);
if (productIds.length) {
const validProducts = await ctx.model.Product.findAll({
where: { id: productIds, status: 1 },
attributes: [ 'id' ],
});
const validIds = new Set(validProducts.map((p) => p.id));
if (productIds.some((id) => !validIds.has(id))) {
ctx.status = 400;
ctx.body = { code: 400, message: '明细关联的商品不存在或已禁用,无法创建单据' };
return;
}
// 货主口径:仓库决定单据货主,明细商品必须与仓库同货主(防止跨货主串货)
const warehouseScope = await resolveWarehouse(ctx, warehouseId);
if (!warehouseScope.ok) {
ctx.status = warehouseScope.status;
ctx.body = { code: warehouseScope.status, message: warehouseScope.message };
return;
}
// 校验明细关联商品均存在、已启用且与仓库同货主
const itemsOwner = await assertItemsOwner(ctx, items, warehouseScope.subsidiaryId);
if (!itemsOwner.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: itemsOwner.message };
return;
}
const transaction = await ctx.model.transaction();
@ -283,6 +286,29 @@ class InboundOrderController extends Controller {
} else {
delete ctx.request.body.inbound_type;
}
// 换仓库时:仓库需可访问,且单据已有明细必须与新仓库同货主(防止改仓库把单据挪到别的货主)
if (ctx.request.body.warehouse_id !== undefined
&& Number(ctx.request.body.warehouse_id) !== Number(order.warehouse_id)) {
const warehouseScope = await resolveWarehouse(ctx, ctx.request.body.warehouse_id);
if (!warehouseScope.ok) {
ctx.status = warehouseScope.status;
ctx.body = { code: warehouseScope.status, message: warehouseScope.message };
return;
}
const existingItems = await ctx.model.StockItem.findAll({
where: { bill_type: 1, bill_id: order.id, principal_id: ctx.state.principalId },
attributes: [ 'product_id', 'combo_product_id' ],
raw: true,
});
const itemsOwner = await assertItemsOwner(ctx, existingItems, warehouseScope.subsidiaryId);
if (!itemsOwner.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: itemsOwner.message };
return;
}
}
await order.update(ctx.request.body);
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}

View File

@ -6,6 +6,7 @@ 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 QimenWmsClient = require('../lib/wms/qimenClient');
const { DEFAULT_OUTBOUND_ORDER_TYPE, OUTBOUND_ORDER_TYPE_LIST, normalizeOutboundOrderType } = require('../lib/wms/orderTypes');
@ -109,7 +110,8 @@ class OutboundOrderController extends Controller {
/**
* @summary 新增出库单
* @description 单号由系统按 CK_{自增id} 自动生成(不接受传入);可同时传入 items(stock_items, bill_type=2)一次性写入明细
* @description 单号由系统按 CK_{自增id} 自动生成(不接受传入);可同时传入 items(stock_items, bill_type=2)一次性写入明细。
* 单据货主由仓库决定(warehouses.subsidiary_id),明细商品/组合必须与仓库同货主,否则拒绝创建
* @router post /api/outbound-orders
* @apikey
* @request body createOutboundOrderRequest *body
@ -140,19 +142,20 @@ class OutboundOrderController extends Controller {
}
payload.outbound_type = outboundType || DEFAULT_OUTBOUND_ORDER_TYPE;
// 校验明细关联商品均存在且已启用
const productIds = (items || []).map((i) => i.product_id).filter(Boolean);
if (productIds.length) {
const validProducts = await ctx.model.Product.findAll({
where: { id: productIds, status: 1 },
attributes: [ 'id' ],
});
const validIds = new Set(validProducts.map((p) => p.id));
if (productIds.some((id) => !validIds.has(id))) {
ctx.status = 400;
ctx.body = { code: 400, message: '明细关联的商品不存在或已禁用,无法创建单据' };
return;
}
// 货主口径:仓库决定单据货主,明细商品必须与仓库同货主(防止跨货主串货)
const warehouseScope = await resolveWarehouse(ctx, warehouseId);
if (!warehouseScope.ok) {
ctx.status = warehouseScope.status;
ctx.body = { code: warehouseScope.status, message: warehouseScope.message };
return;
}
// 校验明细关联商品均存在、已启用且与仓库同货主
const itemsOwner = await assertItemsOwner(ctx, items, warehouseScope.subsidiaryId);
if (!itemsOwner.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: itemsOwner.message };
return;
}
const transaction = await ctx.model.transaction();
@ -242,6 +245,29 @@ class OutboundOrderController extends Controller {
} else {
delete ctx.request.body.outbound_type;
}
// 换仓库时:仓库需可访问,且单据已有明细必须与新仓库同货主(防止改仓库把单据挪到别的货主)
if (ctx.request.body.warehouse_id !== undefined
&& Number(ctx.request.body.warehouse_id) !== Number(order.warehouse_id)) {
const warehouseScope = await resolveWarehouse(ctx, ctx.request.body.warehouse_id);
if (!warehouseScope.ok) {
ctx.status = warehouseScope.status;
ctx.body = { code: warehouseScope.status, message: warehouseScope.message };
return;
}
const existingItems = await ctx.model.StockItem.findAll({
where: { bill_type: 2, bill_id: order.id, principal_id: ctx.state.principalId },
attributes: [ 'product_id', 'combo_product_id' ],
raw: true,
});
const itemsOwner = await assertItemsOwner(ctx, existingItems, warehouseScope.subsidiaryId);
if (!itemsOwner.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: itemsOwner.message };
return;
}
}
await order.update(ctx.request.body);
ctx.body = { code: 0, message: 'success', data: { id: order.id } };
}

View File

@ -3,6 +3,7 @@
const { Controller } = require('egg');
const recalcStock = require('../utils/recalcStock');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { assertItemsOwner, resolveBillSubsidiary } = require('../lib/billOwnerScope');
/**
* 应/已数量由系统维护(应=明细数量,已=WMS 回推),禁止前端直接写入。
@ -123,6 +124,19 @@ class StockItemController extends Controller {
ctx.body = { code: 400, message: '商品不存在或已禁用,无法关联' };
return;
}
// 商品必须与单据仓库同货主(防止跨货主串货)
const billScope = await resolveBillSubsidiary(ctx, billType, billId);
if (!billScope.ok) {
ctx.status = billScope.status;
ctx.body = { code: billScope.status, message: billScope.message };
return;
}
const itemsOwner = await assertItemsOwner(ctx, [ ctx.request.body ], billScope.subsidiaryId);
if (!itemsOwner.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: itemsOwner.message };
return;
}
}
const data = {
...ctx.request.body,
@ -183,6 +197,19 @@ class StockItemController extends Controller {
ctx.body = { code: 400, message: '商品不存在或已禁用,无法关联' };
return;
}
// 商品必须与单据仓库同货主(防止跨货主串货)
const billScope = await resolveBillSubsidiary(ctx, item.bill_type, item.bill_id);
if (!billScope.ok) {
ctx.status = billScope.status;
ctx.body = { code: billScope.status, message: billScope.message };
return;
}
const itemsOwner = await assertItemsOwner(ctx, [ body ], billScope.subsidiaryId);
if (!itemsOwner.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: itemsOwner.message };
return;
}
body.name = body.name || product.item_name;
body.code = body.code || product.item_code;
body.spec = body.spec || product.sku_property;

View File

@ -0,0 +1,112 @@
'use strict';
/**
* 出入库单据的货主(下属公司)口径
*
* 单据头不单独存货主字段:货主由所选仓库决定(warehouses.subsidiary_id)。
* 为避免「某货主的货物进入另一货主的出入库单」,明细商品/组合必须与仓库同货主;
* 同时,所在公司权限的账号只能使用自己所属公司的仓库。
*/
/** 单据类型 → 单据头模型名(stock_items.bill_type) */
const BILL_MODEL = { 1: 'InboundOrder', 2: 'OutboundOrder' };
/**
* 解析当前账号在该主体下的权限范围(无登录态视为系统操作,按集团放行)
* @param {Object} ctx egg context
* @return {Promise<{isGroup: boolean, ownCompanyIds: Array<number>}>} 权限范围
*/
async function resolveAccess(ctx) {
const principalId = Number(ctx.state.principalId);
if (!ctx.userId || !Number.isInteger(principalId)) return { isGroup: true, ownCompanyIds: [] };
return ctx.service.access.resolve(ctx.userId, principalId);
}
/**
* 取仓库并校验主体隔离与货主权限
* @param {Object} ctx egg context
* @param {number|string} warehouseId 仓库ID
* @return {Promise<{ok: boolean, status?: number, message?: string, warehouse?: Object, subsidiaryId?: number|null}>} 校验结果
*/
async function resolveWarehouse(ctx, warehouseId) {
const principalId = Number(ctx.state.principalId);
const warehouse = await ctx.model.Warehouse.findOne({
where: { id: Number(warehouseId), principal_id: principalId },
attributes: [ 'id', 'code', 'name', 'subsidiary_id' ],
});
if (!warehouse) return { ok: false, status: 404, message: '仓库不存在或不属于当前主体' };
const subsidiaryId = warehouse.subsidiary_id == null ? null : Number(warehouse.subsidiary_id);
const access = await resolveAccess(ctx);
if (!access.isGroup && subsidiaryId !== null && !access.ownCompanyIds.includes(subsidiaryId)) {
return { ok: false, status: 403, message: '仓库不属于自己所属公司(货主),无权使用' };
}
return { ok: true, warehouse, subsidiaryId };
}
/**
* 校验明细商品/组合与仓库同货主(存在性 + 启用状态 + 货主一致)
* @param {Object} ctx egg context
* @param {Array} items 明细 [{ product_id, combo_product_id }]
* @param {number|null} subsidiaryId 仓库所属公司ID(null 表示仓库未关联货主,不做货主校验)
* @return {Promise<{ok: boolean, message?: string}>} 校验结果
*/
async function assertItemsOwner(ctx, items, subsidiaryId) {
const Op = ctx.app.Sequelize.Op;
const principalId = Number(ctx.state.principalId);
const list = Array.isArray(items) ? items : [];
const pickIds = key => [ ...new Set(list.map(it => Number(it && it[key])).filter(id => Number.isInteger(id) && id > 0)) ];
const productIds = pickIds('product_id');
const comboIds = pickIds('combo_product_id');
if (!productIds.length && !comboIds.length) return { ok: true };
const [ products, combos ] = await Promise.all([
productIds.length
? ctx.model.Product.findAll({
where: { id: { [Op.in]: productIds }, principal_id: principalId },
attributes: [ 'id', 'status', 'subsidiary_id' ],
raw: true,
})
: [],
comboIds.length
? ctx.model.ComboProduct.findAll({
where: { id: { [Op.in]: comboIds }, principal_id: principalId },
attributes: [ 'id', 'subsidiary_id' ],
raw: true,
})
: [],
]);
const disabled = products.filter(row => Number(row.status) !== 1);
if (disabled.length) return { ok: false, message: '明细关联的商品不存在或已禁用,无法保存' };
if (products.length !== productIds.length || combos.length !== comboIds.length) {
return { ok: false, message: '明细关联的商品/组合不存在或不属于当前主体' };
}
if (subsidiaryId === null || subsidiaryId === undefined) return { ok: true };
const mismatch = [ ...products, ...combos ].find(
row => row.subsidiary_id != null && Number(row.subsidiary_id) !== Number(subsidiaryId)
);
if (mismatch) return { ok: false, message: '明细商品不属于该仓库的货主,请选择同货主的商品' };
return { ok: true };
}
/**
* 取单据所在仓库的货主ID(明细增删改时校验商品货主用)
* @param {Object} ctx egg context
* @param {number} billType 单据类型:1入库 2出库
* @param {number} billId 单据头ID
* @return {Promise<{ok: boolean, status?: number, message?: string, subsidiaryId?: number|null}>} 校验结果
*/
async function resolveBillSubsidiary(ctx, billType, billId) {
const modelName = BILL_MODEL[Number(billType)];
if (!modelName) return { ok: false, status: 400, message: 'bill_type 不合法,仅支持 1入库 / 2出库' };
const order = await ctx.model[modelName].findByPk(billId, { attributes: [ 'id', 'warehouse_id' ] });
if (!order) return { ok: false, status: 404, message: '所属单据不存在' };
if (!order.warehouse_id) return { ok: true, subsidiaryId: null };
const warehouse = await resolveWarehouse(ctx, order.warehouse_id);
if (!warehouse.ok) return { ok: false, status: warehouse.status, message: warehouse.message };
return { ok: true, subsidiaryId: warehouse.subsidiaryId };
}
module.exports = { resolveAccess, resolveWarehouse, assertItemsOwner, resolveBillSubsidiary };

View File

@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { computed, ref, watch } from 'vue'
import { DEFAULT_PAGE_SIZE } from '@/composables/useListPage'
import {
getProducts,
@ -17,12 +17,15 @@ const props = withDefaults(
modelLabel?: string
/** 限定商品所属货主(下单时按店铺货主收窄,避免选到其它货主的商品) */
subsidiaryId?: number | null
/** 选择前置校验:返回 false 时选中不生效(用于单据内商品的货主一致性校验) */
beforeSelect?: (product: ProductSearchItem) => boolean
}>(),
{
placeholder: '搜索并选择商品',
disabled: false,
modelLabel: '',
subsidiaryId: null,
beforeSelect: undefined,
},
)
@ -34,6 +37,18 @@ const emit = defineEmits<{
const options = ref<ProductSearchItem[]>([])
const loading = ref(false)
/**
* 受控显示值:选择被 beforeSelect 拒绝时能让下拉回滚显示,
* 否则 el-select 会先写入父级 v-model,界面残留一个未生效的商品
*/
const innerValue = ref<number | null>(props.modelValue)
watch(
() => props.modelValue,
val => {
innerValue.value = val
},
)
async function remoteMethod(keyword: string) {
loading.value = true
try {
@ -52,12 +67,12 @@ async function remoteMethod(keyword: string) {
const selectOptions = computed(() => {
const list = [...options.value]
if (
props.modelValue != null &&
!list.some((o) => o.id === props.modelValue) &&
innerValue.value != null &&
!list.some((o) => o.id === innerValue.value) &&
props.modelLabel
) {
list.push({
id: props.modelValue,
id: innerValue.value,
item_code: '',
item_name: props.modelLabel,
goods_code: null,
@ -75,11 +90,20 @@ function optLabel(p: ProductSearchItem) {
}
function onChange(val: number | null) {
emit('update:modelValue', val)
if (val != null) {
const p = options.value.find((x) => x.id === val)
if (p) emit('select', p)
if (val == null) {
innerValue.value = null
emit('update:modelValue', null)
return
}
const p = options.value.find((x) => x.id === val)
// 前置校验不通过:保持原值(回滚显示),不向上层写入
if (p && props.beforeSelect && !props.beforeSelect(p)) {
innerValue.value = props.modelValue
return
}
innerValue.value = val
emit('update:modelValue', val)
if (p) emit('select', p)
}
/* -------------------- 查询弹窗(可翻页浏览) -------------------- */
@ -133,8 +157,12 @@ function pickProduct(row: ProductItem) {
sku_property: row.sku_property,
stock_unit: row.stock_unit,
status: row.status,
subsidiary_id: row.subsidiary_id ?? null,
}
// 前置校验不通过:保持弹窗,交由上层提示原因
if (props.beforeSelect && !props.beforeSelect(mapped)) return
if (!options.value.some((o) => o.id === row.id)) options.value.push(mapped)
innerValue.value = row.id
emit('update:modelValue', row.id)
emit('select', mapped)
pickerVisible.value = false
@ -144,7 +172,7 @@ function pickProduct(row: ProductItem) {
<template>
<div class="product-select">
<el-select
:model-value="modelValue"
:model-value="innerValue"
filterable
remote
clearable

View File

@ -0,0 +1,101 @@
import { computed, watch, type Ref } from 'vue'
import { ElMessage } from 'element-plus'
/** 仓库下拉项中本组合式函数关心的最小字段集 */
export interface WarehouseOwnerLike {
id: number
subsidiary_id?: number | null
}
/**
* 出入库单「仓库 ↔ 商品」货主双向约束
*
* 单据货主由仓库决定,明细商品必须与仓库同货主:
* - 先选仓库:商品搜索只保留同货主商品(由 ProductSelect 的 subsidiaryId 生效)
* - 先选商品:仓库下拉只保留同货主仓库;两者冲突时自动清空并提示
* @param options 配置
* @param options.warehouseId 单据头仓库(可写,冲突时会被清空)
* @param options.warehouses 全部仓库选项
* @param options.lineOwners 明细当前已选商品的所属货主(未选商品给 null)
* @param options.clearMismatchedGoods 清空与仓库货主不一致的明细商品,返回清空行数
* @return 派生状态:仓库货主 / 商品货主 / 是否跨货主 / 可选仓库
*/
export function useWarehouseGoodsScope(options: {
warehouseId: Ref<number | null>
warehouses: Ref<WarehouseOwnerLike[]>
lineOwners: () => Array<number | null | undefined>
clearMismatchedGoods: (warehouseOwnerId: number) => number
}) {
const { warehouseId, warehouses, lineOwners, clearMismatchedGoods } = options
/** 当前所选仓库的所属货主(null 表示未选仓库或仓库未关联货主) */
const warehouseOwnerId = computed<number | null>(() => {
if (warehouseId.value == null) return null
const hit = warehouses.value.find(item => Number(item.id) === Number(warehouseId.value))
const sid = hit?.subsidiary_id
return sid === null || sid === undefined ? null : Number(sid)
})
/** 明细商品的货主集合(忽略未选商品与未关联货主的商品) */
const goodsOwnerIds = computed<number[]>(() => [
...new Set(lineOwners().filter((id): id is number => id !== null && id !== undefined).map(Number)),
])
/** 明细商品是否已跨货主(选择了两个不同货主的商品) */
const goodsOwnerConflict = computed(() => goodsOwnerIds.value.length > 1)
/** 明细商品的统一货主(未选 / 跨货主时为 null) */
const goodsOwnerId = computed<number | null>(() => (goodsOwnerIds.value.length === 1 ? goodsOwnerIds.value[0] : null))
/** 商品搜索应使用的货主过滤:优先仓库货主,其次已选商品的货主 */
const scopeSubsidiaryId = computed<number | null>(() => warehouseOwnerId.value ?? goodsOwnerId.value)
/** 仓库下拉:已选商品有货主时只保留同货主仓库 */
const selectableWarehouses = computed(() => {
const sid = goodsOwnerId.value
if (sid === null) return warehouses.value
return warehouses.value.filter(item => item.subsidiary_id == null || Number(item.subsidiary_id) === sid)
})
/** 校验待选商品是否能加入单据(同一单据明细必须同货主) */
function canPickGoods(goodsOwnerIdOfProduct: number | null | undefined, exceptIndex?: number): boolean {
const sid = goodsOwnerIdOfProduct === null || goodsOwnerIdOfProduct === undefined
? null
: Number(goodsOwnerIdOfProduct)
if (sid === null) return true
// 同一行改选商品时排除该行原有货主,避免自己挡住自己
const otherOwners = lineOwners()
.filter((_, index) => index !== exceptIndex)
.filter((id): id is number => id !== null && id !== undefined)
.map(Number)
if (otherOwners.some(id => id !== sid)) {
ElMessage.warning('同一单据的明细商品必须属于同一货主(所属公司)')
return false
}
const current = warehouseOwnerId.value
if (current !== null && current !== sid) {
ElMessage.warning('该商品不属于所选仓库的货主(所属公司)')
return false
}
return true
}
// 换仓库:清空与仓库货主不一致的已选商品
watch(warehouseOwnerId, sid => {
if (sid === null) return
const cleared = clearMismatchedGoods(sid)
if (cleared > 0) ElMessage.warning(`已清空 ${cleared} 行与所选仓库货主不一致的商品,请重新选择`)
})
// 先选商品后选仓库:仓库货主与商品不一致时清空仓库,避免提交后才发现
watch(goodsOwnerId, sid => {
if (sid === null) return
const current = warehouseOwnerId.value
if (current !== null && current !== sid) {
warehouseId.value = null
ElMessage.warning('已清空仓库:与所选商品的货主(所属公司)不一致')
}
})
return { warehouseOwnerId, goodsOwnerId, goodsOwnerConflict, scopeSubsidiaryId, selectableWarehouses, canPickGoods }
}

View File

@ -8,6 +8,7 @@ import { getExpressCompanyOptions, type ExpressCompanyOption } from '@/api/expre
import type { ProductSearchItem } from '@/api/product'
import ProductSelect from '@/components/ProductSelect.vue'
import VirtualSelect from '@/components/VirtualSelect.vue'
import { useWarehouseGoodsScope } from '@/composables/useWarehouseGoodsScope'
/** 入库类型:RK 组(WMS 编码,与入库单列表保持一致) */
const TYPE_OPTIONS = [
@ -79,6 +80,8 @@ function handleExpressChange(code: string | null) {
/* -------------------- 商品明细(内联,随单创建) -------------------- */
interface LineItem {
product_id: number | null
/** 所选商品的所属货主(用于与仓库做同货主校验) */
product_subsidiary_id: number | null
name: string
code: string
spec: string
@ -93,7 +96,7 @@ const lines = ref<LineItem[]>([])
function addLine() {
lines.value.push({
product_id: null, name: '', code: '', spec: '', unit: '',
product_id: null, product_subsidiary_id: null, name: '', code: '', spec: '', unit: '',
quantity: 1, price: null, inventory_type: 'ZP', remark: '',
})
}
@ -102,10 +105,32 @@ function removeLine(index: number) {
lines.value.splice(index, 1)
}
/** 仓库 ↔ 商品双向货主约束:仓库决定单据货主,明细商品必须同货主 */
const { warehouseOwnerId, goodsOwnerId, goodsOwnerConflict, scopeSubsidiaryId, selectableWarehouses, canPickGoods } = useWarehouseGoodsScope({
warehouseId: computed(() => form.warehouse_id),
warehouses,
lineOwners: () => lines.value.map(line => line.product_subsidiary_id),
clearMismatchedGoods: ownerId => {
let cleared = 0
for (const line of lines.value) {
if (!line.product_id) continue
if (line.product_subsidiary_id != null && Number(line.product_subsidiary_id) === Number(ownerId)) continue
line.product_id = null
line.product_subsidiary_id = null
line.name = ''
line.code = ''
line.spec = ''
cleared += 1
}
return cleared
},
})
function onLineProductSelect(index: number, p: ProductSearchItem) {
const line = lines.value[index]
if (!line) return
line.product_id = p.id
line.product_subsidiary_id = p.subsidiary_id == null ? null : Number(p.subsidiary_id)
line.name = p.item_name || ''
line.code = p.item_code || ''
line.spec = p.sku_property || ''
@ -137,6 +162,17 @@ async function submit() {
return
}
}
// 明细商品必须与仓库同货主,且同一单据明细之间也不能跨货主
if (goodsOwnerConflict.value) {
ElMessage.warning('明细商品属于不同货主(所属公司),请统一后再提交')
return
}
if (warehouseOwnerId.value !== null
&& lines.value.some(line => line.product_subsidiary_id != null
&& Number(line.product_subsidiary_id) !== warehouseOwnerId.value)) {
ElMessage.warning('存在与仓库货主(所属公司)不一致的商品,请重新选择')
return
}
submitting.value = true
try {
@ -219,7 +255,7 @@ onMounted(async () => {
<el-form-item label="仓库" prop="warehouse_id">
<VirtualSelect
v-model="form.warehouse_id"
:options="warehouses"
:options="selectableWarehouses"
label-key="name"
value-key="id"
placeholder="请选择仓库"
@ -320,11 +356,18 @@ onMounted(async () => {
<span class="items-total">合计金额:{{ itemsTotal.toFixed(2) }}</span>
<el-button type="primary" size="small" @click="addLine">添加商品</el-button>
</div>
<div v-if="warehouseOwnerId !== null || goodsOwnerId !== null" class="items-tip">
{{ warehouseOwnerId !== null
? '明细商品仅可选与仓库同货主(所属公司)的商品'
: '已按所选商品的货主(所属公司)过滤可选仓库' }}
</div>
<el-table :data="lines" size="small" border max-height="240">
<el-table-column label="商品" min-width="170">
<template #default="{ row, $index }">
<ProductSelect
v-model="row.product_id"
:subsidiary-id="scopeSubsidiaryId"
:before-select="(p: ProductSearchItem) => canPickGoods(p.subsidiary_id, $index)"
@select="(p: ProductSearchItem) => onLineProductSelect($index, p)"
/>
</template>
@ -445,4 +488,9 @@ onMounted(async () => {
font-weight: 600;
color: #303133;
}
.items-tip {
margin-bottom: 6px;
color: var(--el-text-color-secondary);
font-size: 12px;
}
</style>

View File

@ -313,6 +313,14 @@ function isEmptyRow(it: EditItem) {
return !it.product_id && !it.name && !it.code
}
const editItems = ref<EditItem[]>([])
/** 当前单据仓库的货主:明细商品只能选同货主商品(防止跨货主商品进入单据) */
const currentWarehouseOwnerId = computed<number | null>(() => {
const warehouseId = currentOrder.value?.warehouse_id
if (warehouseId == null) return null
const hit = warehouses.value.find(w => Number(w.id) === Number(warehouseId))
const sid = hit?.subsidiary_id
return sid === null || sid === undefined ? null : Number(sid)
})
const editTotal = computed(() =>
editItems.value.reduce((s, it) => s + (Number(it.quantity) || 0) * (Number(it.price) || 0), 0),
)
@ -367,6 +375,13 @@ async function fetchItems() {
ensureTrailingEmptyRow()
}
}
/** 明细商品前置校验:必须与单据仓库同货主(不一致时不允许加入,后端同样会拦截) */
function allowPickProduct(p: ProductSearchItem): boolean {
if (currentWarehouseOwnerId.value === null || p.subsidiary_id == null) return true
if (Number(p.subsidiary_id) === currentWarehouseOwnerId.value) return true
ElMessage.warning('该商品不属于单据仓库的货主(所属公司)')
return false
}
function onEditItemSelect(idx: number, p: ProductSearchItem) {
const it = editItems.value[idx]
if (!it) return
@ -621,6 +636,8 @@ onMounted(async () => {
<ProductSelect
v-model="row.product_id"
:model-label="row._label"
:subsidiary-id="currentWarehouseOwnerId"
:before-select="allowPickProduct"
:disabled="itemsLocked"
@select="(p: ProductSearchItem) => onEditItemSelect($index, p)"
/>

View File

@ -9,6 +9,7 @@ import { getExpressCompanyOptions, type ExpressCompanyOption } from '@/api/expre
import type { ProductSearchItem } from '@/api/product'
import ProductSelect from '@/components/ProductSelect.vue'
import VirtualSelect from '@/components/VirtualSelect.vue'
import { useWarehouseGoodsScope } from '@/composables/useWarehouseGoodsScope'
/** 出库类型:CK 组(WMS 编码,与出库单列表保持一致) */
const TYPE_OPTIONS = [
@ -98,6 +99,8 @@ function handleExpressChange(code: string | null) {
/* -------------------- 商品明细(内联,随单创建) -------------------- */
interface LineItem {
product_id: number | null
/** 所选商品的所属货主(用于与仓库做同货主校验) */
product_subsidiary_id: number | null
name: string
code: string
spec: string
@ -112,7 +115,7 @@ const lines = ref<LineItem[]>([])
function addLine() {
lines.value.push({
product_id: null, name: '', code: '', spec: '', unit: '',
product_id: null, product_subsidiary_id: null, name: '', code: '', spec: '', unit: '',
quantity: 1, price: null, inventory_type: 'ZP', remark: '',
})
}
@ -121,10 +124,32 @@ function removeLine(index: number) {
lines.value.splice(index, 1)
}
/** 仓库 ↔ 商品双向货主约束:仓库决定单据货主,明细商品必须同货主 */
const { warehouseOwnerId, goodsOwnerId, goodsOwnerConflict, scopeSubsidiaryId, selectableWarehouses, canPickGoods } = useWarehouseGoodsScope({
warehouseId: computed(() => form.warehouse_id),
warehouses,
lineOwners: () => lines.value.map(line => line.product_subsidiary_id),
clearMismatchedGoods: ownerId => {
let cleared = 0
for (const line of lines.value) {
if (!line.product_id) continue
if (line.product_subsidiary_id != null && Number(line.product_subsidiary_id) === Number(ownerId)) continue
line.product_id = null
line.product_subsidiary_id = null
line.name = ''
line.code = ''
line.spec = ''
cleared += 1
}
return cleared
},
})
function onLineProductSelect(index: number, p: ProductSearchItem) {
const line = lines.value[index]
if (!line) return
line.product_id = p.id
line.product_subsidiary_id = p.subsidiary_id == null ? null : Number(p.subsidiary_id)
line.name = p.item_name || ''
line.code = p.item_code || ''
line.spec = p.sku_property || ''
@ -156,6 +181,17 @@ async function submit() {
return
}
}
// 明细商品必须与仓库同货主,且同一单据明细之间也不能跨货主
if (goodsOwnerConflict.value) {
ElMessage.warning('明细商品属于不同货主(所属公司),请统一后再提交')
return
}
if (warehouseOwnerId.value !== null
&& lines.value.some(line => line.product_subsidiary_id != null
&& Number(line.product_subsidiary_id) !== warehouseOwnerId.value)) {
ElMessage.warning('存在与仓库货主(所属公司)不一致的商品,请重新选择')
return
}
submitting.value = true
try {
@ -248,7 +284,7 @@ onMounted(async () => {
<el-form-item label="仓库" prop="warehouse_id">
<VirtualSelect
v-model="form.warehouse_id"
:options="warehouses"
:options="selectableWarehouses"
label-key="name"
value-key="id"
placeholder="请选择仓库"
@ -383,11 +419,18 @@ onMounted(async () => {
<span class="items-total">合计金额:{{ itemsTotal.toFixed(2) }}</span>
<el-button type="primary" size="small" @click="addLine">添加商品</el-button>
</div>
<div v-if="warehouseOwnerId !== null || goodsOwnerId !== null" class="items-tip">
{{ warehouseOwnerId !== null
? '明细商品仅可选与仓库同货主(所属公司)的商品'
: '已按所选商品的货主(所属公司)过滤可选仓库' }}
</div>
<el-table :data="lines" size="small" border max-height="240">
<el-table-column label="商品" min-width="170">
<template #default="{ row, $index }">
<ProductSelect
v-model="row.product_id"
:subsidiary-id="scopeSubsidiaryId"
:before-select="(p: ProductSearchItem) => canPickGoods(p.subsidiary_id, $index)"
@select="(p: ProductSearchItem) => onLineProductSelect($index, p)"
/>
</template>
@ -504,4 +547,9 @@ onMounted(async () => {
font-weight: 600;
color: #303133;
}
.items-tip {
margin-bottom: 6px;
color: var(--el-text-color-secondary);
font-size: 12px;
}
</style>

View File

@ -347,6 +347,14 @@ function isEmptyRow(it: EditItem) {
return !it.product_id && !it.name && !it.code
}
const editItems = ref<EditItem[]>([])
/** 当前单据仓库的货主:明细商品只能选同货主商品(防止跨货主商品进入单据) */
const currentWarehouseOwnerId = computed<number | null>(() => {
const warehouseId = currentOrder.value?.warehouse_id
if (warehouseId == null) return null
const hit = warehouses.value.find(w => Number(w.id) === Number(warehouseId))
const sid = hit?.subsidiary_id
return sid === null || sid === undefined ? null : Number(sid)
})
const editTotal = computed(() =>
editItems.value.reduce((s, it) => s + (Number(it.quantity) || 0) * (Number(it.price) || 0), 0),
)
@ -416,6 +424,13 @@ async function fetchItems() {
ensureTrailingEmptyRow()
}
}
/** 明细商品前置校验:必须与单据仓库同货主(不一致时不允许加入,后端同样会拦截) */
function allowPickProduct(p: ProductSearchItem): boolean {
if (currentWarehouseOwnerId.value === null || p.subsidiary_id == null) return true
if (Number(p.subsidiary_id) === currentWarehouseOwnerId.value) return true
ElMessage.warning('该商品不属于单据仓库的货主(所属公司)')
return false
}
function onEditItemSelect(idx: number, p: ProductSearchItem) {
const it = editItems.value[idx]
if (!it) return
@ -689,6 +704,8 @@ onMounted(async () => {
<ProductSelect
v-model="row.product_id"
:model-label="row._label"
:subsidiary-id="currentWarehouseOwnerId"
:before-select="allowPickProduct"
:disabled="itemsLocked"
@select="(p: ProductSearchItem) => onEditItemSelect($index, p)"
/>