feat(报价单+权限): 一客户一单(新建按客户拆分/编辑追加建新单/老数据脚本)+ 角色权限改管理员维护 + 散客改为客户下拉项 + 竞价状态与软删收尾
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
# 角色权限由「管理员」维护(SEC-4 修订)
|
||||
|
||||
- 日期:2026-10-19(同日修订 SEC-4)
|
||||
- 裁决人:开发者(本人)
|
||||
- 状态:已实现,待部署
|
||||
|
||||
## 背景
|
||||
|
||||
SEC-4 初版把**全局**角色/角色权限的写操作收窄为**仅 `super_admin`**:
|
||||
`role_permissions` / `role_definitions` 是全局表(无 `branch_code`),分公司 `admin`
|
||||
若能改就等于垂直提权到所有分公司。
|
||||
|
||||
上线后开发者实测:在「角色权限」页用**管理员**账号保存权限时被拒
|
||||
(`仅超级管理员可管理角色与角色权限`),确认这条收窄过严。
|
||||
|
||||
## 裁决(本次修订)
|
||||
|
||||
| 操作 | 修订前 | **修订后** |
|
||||
|---|---|---|
|
||||
| 修改某角色的权限(`PUT /api/roles/:roleCode/permissions`) | 仅 `super_admin` | **`admin` 与 `super_admin` 都可以** |
|
||||
| 修改 `admin` / `super_admin` 这两个角色自身的权限 | 仅 `super_admin` | **仍仅 `super_admin`**(防管理员自我提权) |
|
||||
| 新建 / 删除全局角色定义(`POST /`、`DELETE /:roleCode`) | 仅 `super_admin` | **不变,仍仅 `super_admin`** |
|
||||
| 读取角色、权限清单(`GET /`、`GET /permissions`) | `admin` 可读 | 不变 |
|
||||
|
||||
拒绝仍发生在**取连接/开事务之前**(零写 SQL、不占连接),与原 SEC-4 的实现约束一致。
|
||||
|
||||
## 影响面
|
||||
|
||||
- 后端:`server/src/routes/roles.ts`(`assertCanEditRolePermissions` 新增;`assertSuperAdmin` 仅保留给角色定义的新建/删除)
|
||||
- 前端:`src/pages/system/RoleManagement.tsx` 无需改动——它对非超管本来就把 `admin` / `super_admin`
|
||||
两个角色从下拉里隐掉,其余角色可编辑;此前只是被后端 403 挡住。
|
||||
- 测试:`server/tests/rolesRouteSuperAdminOnly.test.ts` 改为新口径(admin 可改普通角色、不可改 admin/super_admin;
|
||||
POST/DELETE 仍 403)
|
||||
|
||||
## 安全边界(保留)
|
||||
|
||||
- 管理员**不能**给自己或超级管理员角色加权限 → 无法自我提权为超管。
|
||||
- 管理员**不能**新建/删除全局角色 → 角色集合仍由超管维护。
|
||||
- 所有拒绝路径不产生任何写 SQL。
|
||||
|
||||
## 回滚
|
||||
|
||||
把 `server/src/routes/roles.ts` 的 PUT 守卫换回 `assertSuperAdmin`,并同步回滚本测试文件即可。
|
||||
@@ -0,0 +1,21 @@
|
||||
-- 单行取消库存抵扣锁定(2026-10-19)
|
||||
-- 待分拣(45)后不允许整单取消;允许按单个商品取消其库存抵扣。
|
||||
-- 取消后必须阻止保存/重新分配时被自动抵扣回来,故给 order_items 加锁标记。
|
||||
DO $$
|
||||
DECLARE
|
||||
s text;
|
||||
BEGIN
|
||||
FOR s IN
|
||||
SELECT nspname
|
||||
FROM pg_namespace
|
||||
WHERE nspname LIKE 'tenant\_%' ESCAPE '\'
|
||||
OR nspname IN ('public', 'legacy_public')
|
||||
LOOP
|
||||
IF to_regclass(format('%I.order_items', s)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS stock_cover_locked boolean NOT NULL DEFAULT false',
|
||||
s
|
||||
);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* 老数据拆分:把「一张报价单挂多个客户」的存量数据拆成「一客户一单」。
|
||||
*
|
||||
* 背景(2026-10-19 开发者裁决):报价单从「一单可多客户」改为「一客户一单」。
|
||||
* 新建/编辑已按新口径实现;本脚本处理**存量**:
|
||||
* · 原单**保留第一个客户**(按关联表建立顺序);
|
||||
* · 其余每个客户各生成一张新单(新单号、生效),明细/价格/周期/生效日与原单一致。
|
||||
*
|
||||
* 用法:
|
||||
* npx tsx server/scripts/split-multi-customer-quote-sheets.ts # dry-run(默认,只读)
|
||||
* npx tsx server/scripts/split-multi-customer-quote-sheets.ts --execute # 真正执行
|
||||
* npx tsx server/scripts/split-multi-customer-quote-sheets.ts --branch BR002
|
||||
*
|
||||
* 纪律:
|
||||
* · dry-run 不发任何写 SQL;
|
||||
* · --execute 前请先备份;脚本按单张事务执行,单张失败不影响其它;
|
||||
* · 幂等:拆完后每个 quote_sheet_code 只剩 1 个客户,再跑一次不会产生新单。
|
||||
*/
|
||||
import { pool } from '../src/db';
|
||||
import { newSheetCode } from '../src/services/quoteSheetService';
|
||||
|
||||
type SheetRow = { quote_sheet_code: string; branch_code: string; title: string | null };
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const execute = argv.includes('--execute');
|
||||
const branchArgIdx = argv.indexOf('--branch');
|
||||
const branchFilter = branchArgIdx >= 0 ? String(argv[branchArgIdx + 1] || '').trim() : '';
|
||||
|
||||
async function tenantSchemas(): Promise<string[]> {
|
||||
const { rows } = await pool.query<{ schema_name: string }>(
|
||||
`SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE 'tenant_%' AND schema_name <> 'tenant_template' ORDER BY 1`
|
||||
);
|
||||
return rows.map((r) => r.schema_name);
|
||||
}
|
||||
|
||||
|
||||
/** 逐张事务执行:原单保留第一个客户,其余客户各拷贝一张新单(新单号,字段整行复制) */
|
||||
async function runExecute(schemas: string[]) {
|
||||
let created = 0;
|
||||
let failed = 0;
|
||||
for (const schema of schemas) {
|
||||
const { rows: sheets } = await pool.query<SheetRow>(
|
||||
`SELECT s.quote_sheet_code, s.branch_code, s.title
|
||||
FROM ${schema}.customer_quote_sheets s
|
||||
WHERE (SELECT count(*) FROM ${schema}.customer_quote_sheet_customers c
|
||||
WHERE c.quote_sheet_code = s.quote_sheet_code) > 1
|
||||
${branchFilter ? 'AND s.branch_code = $1' : ''}`,
|
||||
branchFilter ? [branchFilter] : []
|
||||
);
|
||||
for (const sheet of sheets) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const { rows: customers } = await client.query<{ customer_code: string }>(
|
||||
`SELECT customer_code FROM ${schema}.customer_quote_sheet_customers
|
||||
WHERE quote_sheet_code = $1 ORDER BY customer_code`,
|
||||
[sheet.quote_sheet_code]
|
||||
);
|
||||
const extras = customers.slice(1).map((c) => c.customer_code);
|
||||
if (!extras.length) { client.release(); continue; }
|
||||
// 列清单(去掉主键 code 列),用于整行复制
|
||||
const { rows: cols } = await client.query<{ column_name: string }>(
|
||||
`SELECT column_name FROM information_schema.columns
|
||||
WHERE table_schema = $1 AND table_name = 'customer_quote_sheets'
|
||||
AND column_name <> 'quote_sheet_code' ORDER BY ordinal_position`,
|
||||
[schema]
|
||||
);
|
||||
const colList = cols.map((c) => `"${c.column_name}"`).join(', ');
|
||||
const { rows: itemCols } = await client.query<{ column_name: string }>(
|
||||
`SELECT column_name FROM information_schema.columns
|
||||
WHERE table_schema = $1 AND table_name = 'customer_quote_sheet_items'
|
||||
AND column_name <> 'quote_sheet_code' ORDER BY ordinal_position`,
|
||||
[schema]
|
||||
);
|
||||
const itemColList = itemCols.map((c) => `"${c.column_name}"`).join(', ');
|
||||
await client.query('BEGIN');
|
||||
for (const extra of extras) {
|
||||
const nextCode = newSheetCode();
|
||||
await client.query(
|
||||
`INSERT INTO ${schema}.customer_quote_sheets (quote_sheet_code, ${colList})
|
||||
SELECT $1, ${colList} FROM ${schema}.customer_quote_sheets WHERE quote_sheet_code = $2`,
|
||||
[nextCode, sheet.quote_sheet_code]
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO ${schema}.customer_quote_sheet_items (quote_sheet_code, ${itemColList})
|
||||
SELECT $1, ${itemColList} FROM ${schema}.customer_quote_sheet_items WHERE quote_sheet_code = $2`,
|
||||
[nextCode, sheet.quote_sheet_code]
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO ${schema}.customer_quote_sheet_customers (quote_sheet_code, customer_code) VALUES ($1, $2)`,
|
||||
[nextCode, extra]
|
||||
);
|
||||
created += 1;
|
||||
console.log(` [${schema}] ${sheet.quote_sheet_code} → 新单 ${nextCode}(客户 ${extra})`);
|
||||
}
|
||||
// 原单只保留第一个客户
|
||||
await client.query(
|
||||
`DELETE FROM ${schema}.customer_quote_sheet_customers
|
||||
WHERE quote_sheet_code = $1 AND customer_code <> $2`,
|
||||
[sheet.quote_sheet_code, customers[0].customer_code]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
} catch (error: any) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
failed += 1;
|
||||
console.error(` ❌ ${sheet.quote_sheet_code} 失败:${error?.message || error}`);
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(`\n执行完成:新建 ${created} 张,失败 ${failed} 张`);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const schemas = await tenantSchemas();
|
||||
let multiSheets = 0;
|
||||
let willSplitCustomers = 0;
|
||||
|
||||
for (const schema of schemas) {
|
||||
const { rows: sheets } = await pool.query<SheetRow>(
|
||||
`SELECT s.quote_sheet_code, s.branch_code, s.title
|
||||
FROM ${schema}.customer_quote_sheets s
|
||||
WHERE (SELECT count(*) FROM ${schema}.customer_quote_sheet_customers c
|
||||
WHERE c.quote_sheet_code = s.quote_sheet_code) > 1
|
||||
${branchFilter ? `AND s.branch_code = $1` : ''}
|
||||
ORDER BY s.quote_sheet_code`,
|
||||
branchFilter ? [branchFilter] : []
|
||||
);
|
||||
if (!sheets.length) continue;
|
||||
console.log(`\n[${schema}] 一单多客户的报价单:${sheets.length} 张`);
|
||||
for (const sheet of sheets) {
|
||||
const { rows: customers } = await pool.query<{ customer_code: string }>(
|
||||
`SELECT customer_code FROM ${schema}.customer_quote_sheet_customers
|
||||
WHERE quote_sheet_code = $1 ORDER BY customer_code`,
|
||||
[sheet.quote_sheet_code]
|
||||
);
|
||||
const { rows: items } = await pool.query<{ n: number }>(
|
||||
`SELECT count(*)::int AS n FROM ${schema}.customer_quote_sheet_items WHERE quote_sheet_code = $1`,
|
||||
[sheet.quote_sheet_code]
|
||||
);
|
||||
const keep = customers[0]?.customer_code || '-';
|
||||
const extras = customers.slice(1).map((c) => c.customer_code);
|
||||
multiSheets += 1;
|
||||
willSplitCustomers += extras.length;
|
||||
console.log(
|
||||
` ${sheet.quote_sheet_code} | 客户 ${customers.length}(${customers.map((c) => c.customer_code).join(', ')})` +
|
||||
` | 明细 ${items[0]?.n ?? 0} 行 | 保留 ${keep} | 将为 ${extras.join(', ') || '-'} 各建一张`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`\n汇总:一单多客户 ${multiSheets} 张;预计新建 ${willSplitCustomers} 张;模式=${execute ? 'EXECUTE(会写库)' : 'DRY-RUN(只读)'}`
|
||||
);
|
||||
if (execute) {
|
||||
await runExecute(schemas);
|
||||
}
|
||||
await pool.end();
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('拆分脚本失败:', error?.message || error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -280,7 +280,7 @@ export const handlers: Record<string, OrderEntryToolHandler> = {
|
||||
assertNewRowsIdentifiable(items);
|
||||
const isAdmin = Boolean(run.ctx.isSuperAdmin || run.ctx.roles.includes('admin'));
|
||||
const canForceEdit = Boolean(
|
||||
run.ctx.isSuperAdmin || run.ctx.roles.includes('admin') || run.ctx.permissions.includes('order_force_edit')
|
||||
run.ctx.isSuperAdmin || run.ctx.roles.includes('admin') || run.ctx.permissions.includes('order_force_edit') || run.ctx.permissions.includes('order_edit')
|
||||
);
|
||||
return syncOrderManageItems({
|
||||
orderCode,
|
||||
|
||||
@@ -355,7 +355,8 @@ router.patch('/orders/:orderCode/items', authMiddleware, async (req: AuthRequest
|
||||
const canForceEdit = Boolean(
|
||||
ctx?.isSuperAdmin ||
|
||||
ctx?.roles.includes('admin') ||
|
||||
ctx?.permissions.includes('order_force_edit')
|
||||
ctx?.permissions.includes('order_force_edit') ||
|
||||
ctx?.permissions.includes('order_edit')
|
||||
);
|
||||
const preferItemSuppliers =
|
||||
req.body?.prefer_item_suppliers === true ||
|
||||
@@ -887,6 +888,39 @@ router.post('/orders/:orderCode/inventory-offset', authMiddleware, async (req: A
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/orders/:orderCode/items/:itemId/cancel-stock-cover', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'allocation_manage']);
|
||||
const orderCode = String(req.params.orderCode || '').trim();
|
||||
const itemId = String(req.params.itemId || '').trim();
|
||||
if (!orderCode || !itemId) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少订单号或明细 id' });
|
||||
}
|
||||
await assertOrderCodeAccess(orderCode, ctx!);
|
||||
const { cancelStockCoverForOrderItem } = await import('../../../services/inventoryStockCoverService');
|
||||
const result = await cancelStockCoverForOrderItem({
|
||||
orderItemId: itemId,
|
||||
orderCode,
|
||||
branchCode: ctx?.branchCode,
|
||||
});
|
||||
let orderStatusAfter: number | null = null;
|
||||
try {
|
||||
const { reconcileOrderWorkflowStatus } = await import('../../../services/orderStatusReconcileService');
|
||||
const reconcile = await reconcileOrderWorkflowStatus(orderCode);
|
||||
orderStatusAfter = Number(reconcile.newStatus) || null;
|
||||
} catch (error) {
|
||||
console.error(`[stock-cover] 取消抵扣后状态对账失败 order=${orderCode}:`, error);
|
||||
}
|
||||
return res.json({ data: { ...result, order_status_after: orderStatusAfter } });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '取消库存抵扣失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 主系统商品名对不上导致抵扣扣不上:详情里手动选「抵扣的库存商品」(2026-10-12)。
|
||||
* 设计:docs/design/20261104-主系统商品名映射与手动选抵扣库存.md
|
||||
@@ -948,7 +982,8 @@ router.post('/orders/:orderCode/items/:itemId/stock-cover-sku', authMiddleware,
|
||||
const canForceEdit = Boolean(
|
||||
ctx?.isSuperAdmin ||
|
||||
ctx?.roles?.includes('admin') ||
|
||||
ctx?.permissions?.includes('order_force_edit')
|
||||
ctx?.permissions?.includes('order_force_edit') ||
|
||||
ctx?.permissions?.includes('order_edit')
|
||||
);
|
||||
const { setMainSystemItemCoverSku } = await import('../../../services/mainSystemItemSkuMappingService');
|
||||
const result = await setMainSystemItemCoverSku({
|
||||
|
||||
@@ -18,13 +18,16 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon
|
||||
? [String(req.body.customer_code)]
|
||||
: [];
|
||||
const items = Array.isArray(req.body?.items) ? req.body.items : [];
|
||||
const data = await createQuoteSheet({
|
||||
title: req.body?.title ? String(req.body.title) : undefined,
|
||||
autoSalePriceByCost: req.body?.auto_sale_price_by_cost === undefined
|
||||
? undefined
|
||||
: req.body.auto_sale_price_by_cost === true,
|
||||
customerCodes,
|
||||
items: items.map((item: any) => ({
|
||||
/**
|
||||
* 2026-10-19 开发者裁决:**一个客户一张报价单**。
|
||||
* 新建时勾了 N 个客户 ⇒ 逐张新建 N 张(各取新单号),不再是 1 张挂 N 个客户。
|
||||
* 明细/价格/周期/生效日全部复制;每张都走 activate 生效。
|
||||
*/
|
||||
const targetCustomerCodes = Array.from(new Set(customerCodes.map((c) => String(c || '').trim()).filter(Boolean)));
|
||||
if (targetCustomerCodes.length === 0) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '请选择客户' });
|
||||
}
|
||||
const normalizedItems = items.map((item: any) => ({
|
||||
sku_code: String(item.sku_code || ''),
|
||||
unit: item.unit ? String(item.unit) : undefined,
|
||||
price: Number(item.sale_price ?? item.price),
|
||||
@@ -32,14 +35,25 @@ router.post('/quote/sheet', authMiddleware, async (req: AuthRequest, res: Respon
|
||||
cost_price: Number(item.cost_price) || 0,
|
||||
markup_ratio: item.markup_ratio == null ? null : Number(item.markup_ratio),
|
||||
sku_name: item.sku_name ? String(item.sku_name) : undefined,
|
||||
})),
|
||||
quoteCycle: req.body?.quote_cycle ? String(req.body.quote_cycle) : undefined,
|
||||
effectiveAt: req.body?.effective_at ? String(req.body.effective_at) : undefined,
|
||||
createdBy: req.userId,
|
||||
ctx,
|
||||
operatingBranchCode: operatingBranch,
|
||||
});
|
||||
return res.json({ data });
|
||||
}));
|
||||
const created: any[] = [];
|
||||
for (const customerCode of targetCustomerCodes) {
|
||||
const sheet = await createQuoteSheet({
|
||||
title: req.body?.title ? String(req.body.title) : undefined,
|
||||
autoSalePriceByCost: req.body?.auto_sale_price_by_cost === undefined
|
||||
? undefined
|
||||
: req.body.auto_sale_price_by_cost === true,
|
||||
customerCodes: [customerCode],
|
||||
items: normalizedItems,
|
||||
quoteCycle: req.body?.quote_cycle ? String(req.body.quote_cycle) : undefined,
|
||||
effectiveAt: req.body?.effective_at ? String(req.body.effective_at) : undefined,
|
||||
createdBy: req.userId,
|
||||
ctx,
|
||||
operatingBranchCode: operatingBranch,
|
||||
});
|
||||
created.push(sheet);
|
||||
}
|
||||
return res.json({ data: created[0] ?? null, sheets: created, created_count: created.length });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({ error: 'server_error', error_description: error?.message || '创建报价单失败' });
|
||||
}
|
||||
@@ -91,9 +105,39 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res:
|
||||
const operatingBranch = readOperatingBranchCode(req);
|
||||
requireWorkflowPermission(ctx, ['customer_manage', 'order_manage']);
|
||||
const { applyQuoteSheetEditAndRequestDeliveryReview } = await import('../../../services/quoteSheetEditService');
|
||||
const customerCodes = Array.isArray(req.body?.customer_codes)
|
||||
? req.body.customer_codes.map(String)
|
||||
const rawCustomerCodes = Array.isArray(req.body?.customer_codes)
|
||||
? Array.from(new Set(req.body.customer_codes.map((c: unknown) => String(c || '').trim()).filter(Boolean)))
|
||||
: undefined;
|
||||
/**
|
||||
* 2026-10-19 开发者裁决(编辑阶段):
|
||||
* · 本单**自己的客户不变**(不能换客户);
|
||||
* · 可以**追加**客户:追加的客户若名下还没有报价单,保存时以本单数据为模板给它**新建一张**;
|
||||
* · 追加的客户若名下**已有**报价单 ⇒ 拒绝(请去编辑它自己那张,避免一份数据两个来源)。
|
||||
*/
|
||||
let customersToCreate: string[] = [];
|
||||
if (rawCustomerCodes && rawCustomerCodes.length) {
|
||||
const { pool } = await import('../../../db');
|
||||
const current = await pool.query<{ customer_code: string }>(
|
||||
`SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1`,
|
||||
[req.params.code]
|
||||
);
|
||||
const currentCodes = new Set(current.rows.map((r) => String(r.customer_code)));
|
||||
const extra = rawCustomerCodes.filter((c) => !currentCodes.has(c));
|
||||
if (extra.length) {
|
||||
const taken = await pool.query<{ customer_code: string }>(
|
||||
`SELECT DISTINCT customer_code FROM customer_quote_sheet_customers WHERE customer_code = ANY($1::text[])`,
|
||||
[extra]
|
||||
);
|
||||
if ((taken.rowCount || 0) > 0) {
|
||||
return res.status(400).json({
|
||||
error: 'customer_already_quoted',
|
||||
error_description: `以下客户名下已有报价单,不能追加:${taken.rows.map((r) => r.customer_code).join('、')}`,
|
||||
});
|
||||
}
|
||||
customersToCreate = extra;
|
||||
}
|
||||
}
|
||||
const customerCodes = rawCustomerCodes ? rawCustomerCodes.filter((c) => c) : undefined;
|
||||
const items = Array.isArray(req.body?.items)
|
||||
? req.body.items.map((item: any) => ({
|
||||
sku_code: String(item.sku_code || ''),
|
||||
@@ -119,11 +163,45 @@ router.put('/quote/sheets/:code', authMiddleware, async (req: AuthRequest, res:
|
||||
operatingBranchCode: operatingBranch,
|
||||
requestedBy: req.userId || null,
|
||||
});
|
||||
/**
|
||||
* 追加客户(编辑阶段):以本单**保存后的数据**为模板,给每个追加客户各新建一张(新单号、生效)。
|
||||
* 本单自己的客户不变。
|
||||
*/
|
||||
const createdSheets: any[] = [];
|
||||
if (customersToCreate.length) {
|
||||
const { createQuoteSheet } = await import('../../../services/quoteSheetService');
|
||||
const template = result.data as any;
|
||||
const templateItems = (template?.items || []).map((it: any) => ({
|
||||
sku_code: String(it.sku_code || ''),
|
||||
unit: it.unit ? String(it.unit) : undefined,
|
||||
price: Number(it.sale_price ?? it.price),
|
||||
sale_price: Number(it.sale_price ?? it.price),
|
||||
cost_price: Number(it.cost_price) || 0,
|
||||
markup_ratio: it.markup_ratio == null ? null : Number(it.markup_ratio),
|
||||
sku_name: it.sku_name ? String(it.sku_name) : undefined,
|
||||
}));
|
||||
for (const customerCode of customersToCreate) {
|
||||
const sheet = await createQuoteSheet({
|
||||
title: template?.title ? String(template.title) : undefined,
|
||||
autoSalePriceByCost: undefined,
|
||||
customerCodes: [customerCode],
|
||||
items: templateItems,
|
||||
quoteCycle: template?.quote_cycle ? String(template.quote_cycle) : undefined,
|
||||
effectiveAt: template?.effective_at ? String(template.effective_at) : undefined,
|
||||
createdBy: req.userId,
|
||||
ctx,
|
||||
operatingBranchCode: operatingBranch,
|
||||
});
|
||||
createdSheets.push(sheet);
|
||||
}
|
||||
}
|
||||
// 新口径(2026-10-18):自己的报价单**立即生效**;改价再自动发一条「配送商销售价确认」申请给对方审核
|
||||
return res.json({
|
||||
data: result.data,
|
||||
applied: true,
|
||||
delivery_handoff: result.delivery_handoff,
|
||||
created_count: createdSheets.length,
|
||||
sheets: createdSheets,
|
||||
});
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
|
||||
@@ -349,7 +349,7 @@ router.get('/orders/:orderCode', authMiddleware, async (req: AuthRequest, res: R
|
||||
const isAdmin = ctx.isSuperAdmin || ctx.roles.includes('admin');
|
||||
const canEditCompleted = isAdmin;
|
||||
const canForceEdit =
|
||||
ctx.isSuperAdmin || ctx.roles.includes('admin') || ctx.permissions.includes('order_force_edit');
|
||||
ctx.isSuperAdmin || ctx.roles.includes('admin') || ctx.permissions.includes('order_force_edit') || ctx.permissions.includes('order_edit');
|
||||
const canEditOrderData =
|
||||
isAdmin || ctx.permissions.includes('order_edit') || ctx.permissions.includes('order_entry');
|
||||
const smartAllocationEnabled = await isSmartAllocationEnabled(order.branch_code);
|
||||
@@ -399,7 +399,7 @@ router.patch('/orders/:orderCode', authMiddleware, async (req: AuthRequest, res:
|
||||
const isAdmin = ctx.isSuperAdmin || ctx.roles.includes('admin');
|
||||
const canEditCompleted = isAdmin;
|
||||
const canForceEdit =
|
||||
ctx.isSuperAdmin || ctx.roles.includes('admin') || ctx.permissions.includes('order_force_edit');
|
||||
ctx.isSuperAdmin || ctx.roles.includes('admin') || ctx.permissions.includes('order_force_edit') || ctx.permissions.includes('order_edit');
|
||||
const canEditOrderData =
|
||||
isAdmin || ctx.permissions.includes('order_edit') || ctx.permissions.includes('order_entry');
|
||||
if (!canEditOrderData) {
|
||||
|
||||
@@ -20,18 +20,35 @@ async function getRoleManagerContext(userId: string) {
|
||||
if (!set.has('super_admin') && !set.has('admin')) {
|
||||
throw Object.assign(new Error('无权管理角色'), { status: 403 });
|
||||
}
|
||||
return { isSuperAdmin: set.has('super_admin') };
|
||||
return { isSuperAdmin: set.has('super_admin'), isAdmin: set.has('admin') };
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-4(2026-10-19):**全局**角色/角色权限的写操作仅 `super_admin`。
|
||||
* `role_permissions` / `role_definitions` 是全局表(无 branch_code),分公司 `admin`
|
||||
* 若能改就等于垂直提权到所有分公司。约定:在取连接/开事务**之前**拒绝(admin 403 且零写 SQL)。
|
||||
* SEC-4(2026-10-19,**2026-10-19 修订**):
|
||||
* · **角色权限(`PUT /:roleCode/permissions`)由「管理员」维护**(开发者明确要求:
|
||||
* 这块就是管理员的权限,不是超级管理员);`super_admin` 当然也可以。
|
||||
* · 但管理员**不能**改 `admin` / `super_admin` 这两个角色的权限(防自我提权)。
|
||||
* · 角色定义的**新建/删除**仍只给 `super_admin`(会改变全局角色集合)。
|
||||
* · 拒绝一律发生在取连接/开事务**之前**(零写 SQL),GET 读路径不受影响。
|
||||
*/
|
||||
async function assertCanEditRolePermissions(userId: string, roleCode: string): Promise<void> {
|
||||
const { isSuperAdmin, isAdmin } = await getRoleManagerContext(userId);
|
||||
if (!isSuperAdmin && !isAdmin) {
|
||||
throw Object.assign(new Error('仅管理员可修改角色权限'), { status: 403, code: 'forbidden' });
|
||||
}
|
||||
if (!isSuperAdmin && SUPER_ADMIN_ONLY_ROLES.has(String(roleCode || ''))) {
|
||||
throw Object.assign(new Error('管理员不能修改「管理员 / 超级管理员」角色的权限'), {
|
||||
status: 403,
|
||||
code: 'forbidden',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** 角色定义的写操作(新建/删除)仍仅 `super_admin` */
|
||||
async function assertSuperAdmin(userId: string): Promise<void> {
|
||||
const { isSuperAdmin } = await getRoleManagerContext(userId);
|
||||
if (!isSuperAdmin) {
|
||||
throw Object.assign(new Error('仅超级管理员可管理角色与角色权限'), {
|
||||
throw Object.assign(new Error('仅超级管理员可管理角色定义'), {
|
||||
status: 403,
|
||||
code: 'forbidden',
|
||||
});
|
||||
@@ -112,15 +129,15 @@ router.post('/', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
router.put('/:roleCode/permissions', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
if (!req.userId) return res.status(401).json({ error: 'invalid_token' });
|
||||
/**
|
||||
* SEC-4:仅超级管理员可改全局角色权限;**必须在取连接/BEGIN 之前拒绝**,
|
||||
* 保证 admin 403 时既无 DELETE/INSERT 写 SQL,也不占用连接/事务。
|
||||
* SEC-4(修订):角色权限由**管理员**维护(super_admin 也可),但管理员不能改
|
||||
* admin / super_admin 两个角色;**必须在取连接/BEGIN 之前拒绝**(零写 SQL、不占连接)。
|
||||
*/
|
||||
try {
|
||||
await assertSuperAdmin(req.userId);
|
||||
await assertCanEditRolePermissions(req.userId, String(req.params?.roleCode || ''));
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 403).json({
|
||||
error: error?.code || 'forbidden',
|
||||
error_description: error?.message || '仅超级管理员可修改角色权限',
|
||||
error_description: error?.message || '仅管理员可修改角色权限',
|
||||
});
|
||||
}
|
||||
const roleCode = String(req.params.roleCode || '').trim();
|
||||
|
||||
@@ -3,6 +3,7 @@ import { isOrderIndependentInbound } from './independentInbound';
|
||||
import { PROCESSING_OWNER_SUPPLIER, requiresProcessing } from './processingMethodUtils';
|
||||
import { INTERNAL_PURCHASER_CODE, STOCK_COVER_SUPPLIER_CODE } from './allocationRules';
|
||||
import { pool } from '../db';
|
||||
import { getTenantDbStore } from './tenantDbContext';
|
||||
|
||||
type Db = Pick<PoolClient, 'query'>;
|
||||
|
||||
@@ -624,6 +625,18 @@ export async function applyStockCoverForOrderItem(
|
||||
}
|
||||
}
|
||||
|
||||
// 单行取消库存抵扣后锁定:保存明细/重新分配时不得自动抵扣回来(2026-10-19)
|
||||
if (orderItemId && ORDER_ITEM_UUID_RE.test(orderItemId)) {
|
||||
const lockResult = await db.query<{ locked: boolean; cover_qty: number }>(
|
||||
`SELECT COALESCE(stock_cover_locked, false) AS locked,
|
||||
COALESCE(stock_cover_qty, 0)::float AS cover_qty
|
||||
FROM order_items WHERE id = $1::uuid`,
|
||||
[orderItemId]
|
||||
);
|
||||
const lockRow = (lockResult as { rows?: Array<{ locked: boolean; cover_qty: number }> } | undefined)?.rows?.[0];
|
||||
if (lockRow?.locked) return Number(lockRow.cover_qty) || 0;
|
||||
}
|
||||
|
||||
if (!orderItemId || !orderCode || !skuCode || need <= 0) {
|
||||
if (orderItemId) {
|
||||
await db.query(`UPDATE order_items SET stock_cover_qty = $2, ${STOCK_COVER_SUPPLIER_SQL} WHERE id = $1::uuid`, [orderItemId, 0]);
|
||||
@@ -1155,6 +1168,131 @@ export async function clearCoverForPendingOrWarehouseProcessing(
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消**单行**库存抵扣(2026-10-19 开发者:待分拣后不能整单取消,但可以取消订单中单个商品的抵扣库存)。
|
||||
*
|
||||
* 调用方必须:
|
||||
* - 在事务内调用(本函数不 BEGIN/COMMIT,但会 `FOR UPDATE` 锁订单与明细);
|
||||
* - 传入已带租户上下文的 `db`(search_path + app.branch_code);
|
||||
* - 提交后调用 `reconcileOrderWorkflowStatus(orderCode)` 让状态回到该到的位置。
|
||||
*
|
||||
* 行为:归零 `stock_cover_qty`、供应商回 `UNASSIGNED`、释放活跃预留(含 FIFO/我方指定抵扣批次),
|
||||
* 同单同 SKU 无其它活行时作废该格抵扣成本;状态 ≥50(已发车/配送/完成)拒绝。
|
||||
*/
|
||||
async function cancelStockCoverForOrderItemTx(
|
||||
db: Db,
|
||||
input: { orderItemId: string; orderCode: string }
|
||||
): Promise<{ cancelled: boolean; coverQty: number; skuCode: string | null }> {
|
||||
const orderItemId = String(input.orderItemId || '').trim();
|
||||
const orderCode = String(input.orderCode || '').trim();
|
||||
if (!orderItemId || !ORDER_ITEM_UUID_RE.test(orderItemId) || !orderCode) {
|
||||
throw Object.assign(new Error('参数不合法'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
|
||||
const order = await db.query<{ order_status: number }>(
|
||||
`SELECT order_status FROM orders WHERE order_code = $1 FOR UPDATE`,
|
||||
[orderCode]
|
||||
);
|
||||
if (!order.rowCount) {
|
||||
throw Object.assign(new Error('订单不存在'), { status: 404, code: 'not_found' });
|
||||
}
|
||||
const status = Number(order.rows[0]?.order_status) || 0;
|
||||
if (status >= 50) {
|
||||
throw Object.assign(new Error('订单已发车/配送/完成,不能再取消库存抵扣'), {
|
||||
status: 409,
|
||||
code: 'order_picked',
|
||||
});
|
||||
}
|
||||
|
||||
const row = await db.query<{
|
||||
sku_code: string | null;
|
||||
cover_qty: number;
|
||||
is_returned: boolean;
|
||||
}>(
|
||||
`SELECT sku_code,
|
||||
COALESCE(stock_cover_qty, 0)::float AS cover_qty,
|
||||
COALESCE(is_returned, false) AS is_returned
|
||||
FROM order_items
|
||||
WHERE id = $1::uuid AND order_code = $2
|
||||
FOR UPDATE`,
|
||||
[orderItemId, orderCode]
|
||||
);
|
||||
if (!row.rowCount) {
|
||||
throw Object.assign(new Error('订单明细不存在'), { status: 404, code: 'not_found' });
|
||||
}
|
||||
const item = row.rows[0];
|
||||
if (item.is_returned) {
|
||||
throw Object.assign(new Error('已退货的行不能取消库存抵扣'), { status: 409, code: 'returned' });
|
||||
}
|
||||
const coverQty = Number(item.cover_qty) || 0;
|
||||
if (coverQty <= 1e-9) {
|
||||
throw Object.assign(new Error('该行没有库存抵扣'), { status: 400, code: 'no_stock_cover' });
|
||||
}
|
||||
|
||||
await db.query(
|
||||
`UPDATE order_items SET stock_cover_qty = $2, stock_cover_locked = true, ${STOCK_COVER_SUPPLIER_SQL} WHERE id = $1::uuid`,
|
||||
[orderItemId, 0]
|
||||
);
|
||||
// 释放活跃预留(内部会一并清 FIFO 批次计划与「我方指定抵扣批次」)
|
||||
await releaseReservationsForOrderItem(db, orderItemId);
|
||||
|
||||
const skuCode = String(item.sku_code || '').trim() || null;
|
||||
if (skuCode) {
|
||||
const liveSibling = await hasLiveSiblingRowForSku(db, {
|
||||
orderCode,
|
||||
skuCode,
|
||||
excludeItemId: orderItemId,
|
||||
});
|
||||
if (!liveSibling) {
|
||||
await voidInventoryCoverCostsForOrderSku(db, {
|
||||
orderCode,
|
||||
skuCode,
|
||||
remark: '单行取消库存抵扣:释放该行抵扣并回退成本',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { cancelled: true, coverQty, skuCode };
|
||||
}
|
||||
|
||||
/**
|
||||
* 单行取消库存抵扣(对外入口):自带独立连接/事务,路由层不得再直接拿连接或写 SQL。
|
||||
* 调用方提交后自行决定是否 `reconcileOrderWorkflowStatus`。
|
||||
*/
|
||||
export async function cancelStockCoverForOrderItem(input: {
|
||||
orderItemId: string;
|
||||
orderCode: string;
|
||||
branchCode?: string | null;
|
||||
schemaName?: string | null;
|
||||
}): Promise<{ cancelled: boolean; coverQty: number; skuCode: string | null }> {
|
||||
const store = getTenantDbStore();
|
||||
const schemaName = String(input.schemaName || store?.schemaName || '').trim();
|
||||
const branchCode = String(input.branchCode || store?.branchCode || '').trim();
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
if (schemaName && /^tenant_[a-z0-9_-]{2,40}$/.test(schemaName)) {
|
||||
await client.query(`SELECT set_config('search_path', $1, false)`, [`${schemaName}, public`]);
|
||||
}
|
||||
if (branchCode) {
|
||||
await client.query(`SELECT set_config('app.branch_code', $1, false)`, [branchCode]);
|
||||
}
|
||||
await client.query('BEGIN');
|
||||
const result = await cancelStockCoverForOrderItemTx(client, {
|
||||
orderItemId: input.orderItemId,
|
||||
orderCode: input.orderCode,
|
||||
});
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
await client.query(`SELECT set_config('search_path', 'public', false)`).catch(() => undefined);
|
||||
await client.query(`SELECT set_config('app.branch_code', '', false)`).catch(() => undefined);
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
export async function releaseReservationsForOrderItem(
|
||||
db: Db,
|
||||
orderItemId: string,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { pool } from '../db';
|
||||
import { runWithTenantDataAccess } from './tenantSchemaService';
|
||||
import { isIndependentInboundCustomer } from './independentInbound';
|
||||
|
||||
@@ -253,7 +254,7 @@ export async function listCoverableSkuOptions(params: {
|
||||
* 抵扣重跑由调用方复用既有 `POST /orders/:orderCode/inventory-offset`。
|
||||
*
|
||||
* ⚠️ `canForceEdit` 必须由**调用方按权限**传入(默认 false):
|
||||
* 40–89 的订单属于「履约中」,改明细要 `order_force_edit`(与
|
||||
* 40–89 的订单属于「履约中」,改明细要 `order_force_edit` 或 `order_edit`(与
|
||||
* `PATCH /orders/:orderCode/items` 同一道闸)。这里硬编码 `true` 会让只持
|
||||
* `order_manage`(语义仅"查看")的角色越权改履约中的单。
|
||||
*/
|
||||
@@ -345,6 +346,8 @@ export async function setMainSystemItemCoverSku(params: {
|
||||
quality_report_id: row.quality_report_id ?? null,
|
||||
}));
|
||||
|
||||
// 手动「选择抵扣商品」是明确的重新抵扣动作:清掉该行取消锁
|
||||
await pool.query(`UPDATE order_items SET stock_cover_locked = false WHERE id = $1::uuid`, [itemId]);
|
||||
const { syncOrderManageItems } = await import('./orderManageItemsService');
|
||||
await syncOrderManageItems({
|
||||
orderCode,
|
||||
@@ -353,7 +356,7 @@ export async function setMainSystemItemCoverSku(params: {
|
||||
operatorRoles: params.operatorRoles ?? 'main_system_import',
|
||||
provisionPurchaserOrderSkus: true,
|
||||
allowUnpriced: true,
|
||||
// 由路由按 `order_force_edit` 判定后传入;默认 false ⇒ 40–89 履约中拒绝改明细
|
||||
// 由路由按 `order_force_edit`/`order_edit` 判定后传入;默认 false ⇒ 40–89 履约中拒绝改明细
|
||||
canForceEdit: params.canForceEdit === true,
|
||||
});
|
||||
|
||||
|
||||
@@ -2900,6 +2900,8 @@ export async function applyInventoryOffsetForMainSystemOrder(input: {
|
||||
* `reconcileOrderWorkflowStatus` 接着推到 40/45 待分拣。
|
||||
* 见 docs/design/20261013-主系统导入单默认未分配(先抵扣后人工选择供应商或自采).md
|
||||
*/
|
||||
// 手动「库存抵扣」按钮是明确的重新抵扣动作:先清掉所有单行取消锁
|
||||
await pool.query(`UPDATE order_items SET stock_cover_locked = false WHERE order_code = $1`, [orderCode]);
|
||||
const allocation = await reprocessOrderAllocation(
|
||||
orderCode,
|
||||
input.customerCode ?? null,
|
||||
|
||||
@@ -323,7 +323,7 @@ function normalizeQualityReportIds(row: OrderManageItemInput): string[] {
|
||||
/**
|
||||
* 明细可编辑矩阵(与 Web OrderManagement 对齐):
|
||||
* - ≥90:管理员或调用方 canEditCompleted(采购员改单)
|
||||
* - 40–89:须 canForceEdit(order_force_edit;内置 admin/super_admin 默认具备)
|
||||
* - 40–89:须 canForceEdit(order_force_edit 或 order_edit;内置 admin/super_admin 默认具备)
|
||||
* - <40:有订单写权限即可(由路由鉴权)
|
||||
*/
|
||||
export function canEditOrderItemsForStatus(
|
||||
@@ -815,7 +815,7 @@ export async function syncOrderManageItems(params: {
|
||||
isAdmin?: boolean;
|
||||
/** 已完成订单可改(admin 或采购员专用通道) */
|
||||
canEditCompleted?: boolean;
|
||||
/** 履约中(40–89)强制改明细:order_force_edit */
|
||||
/** 履约中(40–89)强制改明细:order_force_edit 或 order_edit */
|
||||
canForceEdit?: boolean;
|
||||
/** 手动分配页:保存时按明细供应商落履约,不跑规则改写 */
|
||||
preferItemSuppliers?: boolean;
|
||||
|
||||
@@ -64,7 +64,7 @@ export async function assertCustomersInBranch(customerCodes: string[], branchCod
|
||||
}
|
||||
}
|
||||
|
||||
function newSheetCode() {
|
||||
export function newSheetCode() {
|
||||
return `QS${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const route = readFileSync(new URL('../src/modules/workflow/routes/orderRoutes.ts', import.meta.url), 'utf8');
|
||||
const svc = readFileSync(new URL('../src/services/inventoryStockCoverService.ts', import.meta.url), 'utf8');
|
||||
const panel = readFileSync(new URL('../../src/components/order/OrderDetailDeliveryNotePanel.tsx', import.meta.url), 'utf8');
|
||||
const page = readFileSync(new URL('../../src/pages/orders/orderManagement/OrderManagementPage.tsx', import.meta.url), 'utf8');
|
||||
const api = readFileSync(new URL('../../src/utils/workflowApi.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('单行取消库存抵扣(2026-10-19)', () => {
|
||||
it('后端:路由只做权限/事务边界,服务内校验 50+ 拒绝并释放预留/作废成本', () => {
|
||||
const idx = route.indexOf("'/orders/:orderCode/items/:itemId/cancel-stock-cover'");
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const next = route.indexOf('router.post(', idx + 10);
|
||||
const body = route.slice(idx, next > idx ? next : idx + 2400);
|
||||
expect(body).toContain("requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'allocation_manage'])");
|
||||
expect(body).toContain('cancelStockCoverForOrderItem({');
|
||||
expect(body).not.toContain('SELECT ');
|
||||
|
||||
const svcIdx = svc.indexOf('async function cancelStockCoverForOrderItemTx');
|
||||
expect(svcIdx).toBeGreaterThan(-1);
|
||||
const tx = svc.slice(svcIdx, svcIdx + 4200);
|
||||
expect(tx).toContain('status >= 50');
|
||||
expect(tx).toContain('order_picked');
|
||||
expect(tx).toContain('releaseReservationsForOrderItem(');
|
||||
expect(tx).toContain('voidInventoryCoverCostsForOrderSku(');
|
||||
expect(tx).toContain('stock_cover_qty = $2');
|
||||
expect(tx).toContain('stock_cover_locked = true');
|
||||
// 自动抵扣必须尊重锁定,否则取消后保存会被抵扣回来
|
||||
const applyIdx = svc.indexOf('export async function applyStockCoverForOrderItem');
|
||||
const apply = svc.slice(applyIdx, applyIdx + 4200);
|
||||
expect(apply).toContain('stock_cover_locked');
|
||||
});
|
||||
|
||||
it('手动“库存抵扣/选择抵扣商品”会清锁,允许重新抵扣', () => {
|
||||
const alloc = readFileSync(new URL('../src/services/orderAllocationService.ts', import.meta.url), 'utf8');
|
||||
expect(alloc).toContain('stock_cover_locked = false');
|
||||
const mapping = readFileSync(new URL('../src/services/mainSystemItemSkuMappingService.ts', import.meta.url), 'utf8');
|
||||
expect(mapping).toContain('stock_cover_locked = false');
|
||||
});
|
||||
|
||||
it('前端:按行显示取消抵扣,且 45 仍可用(仅 <50)', () => {
|
||||
expect(panel).toContain('onCancelStockCover');
|
||||
const idx = panel.indexOf("t('orders.detail.cancelCover')");
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const around = panel.slice(Math.max(0, idx - 900), idx);
|
||||
expect(around).toContain('Number(item.cover_qty || 0) > 1e-9');
|
||||
expect(around).toContain('(orderStatus ?? 0) < 50');
|
||||
expect(page).toContain('handleCancelStockCover');
|
||||
expect(page).toContain('cancelOrderItemStockCoverApi');
|
||||
expect(api).toContain('/cancel-stock-cover');
|
||||
});
|
||||
});
|
||||
@@ -244,6 +244,8 @@ describe('改绑抵扣商品:输入校验 + 权限闸', () => {
|
||||
// 2026-10-13:去掉"仅主系统单"那段守卫后路由变短,窗口相应放宽(断言内容不变)
|
||||
const body = routes.slice(routeStart, routeStart + 3200);
|
||||
expect(body).toContain("permissions?.includes('order_force_edit')");
|
||||
// 2026-10-19:产品要求「修改订单数据」(order_edit) 也视为可强制改履约中明细
|
||||
expect(body).toContain("permissions?.includes('order_edit')");
|
||||
expect(body).toContain('canForceEdit,');
|
||||
const service = readFileSync(
|
||||
new URL('../src/services/mainSystemItemSkuMappingService.ts', import.meta.url),
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* 报价单「一客户一单」(2026-10-19 开发者裁决)路由层契约:
|
||||
* · 新建:勾 N 个客户 ⇒ 调 N 次建单(每次 1 个客户),返回 created_count=N;
|
||||
* · 编辑:本单客户不变;追加的客户若**名下无报价单** ⇒ 以本单数据为模板建新单;
|
||||
* · 编辑:追加的客户若**名下已有报价单** ⇒ 400,且不建任何单。
|
||||
*/
|
||||
|
||||
const H = vi.hoisted(() => ({
|
||||
createQuoteSheet: vi.fn(),
|
||||
applyEdit: vi.fn(),
|
||||
poolQuery: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../src/middleware/auth', () => ({
|
||||
authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => {
|
||||
req.userId = 'u-1';
|
||||
next();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../src/modules/workflow/context', () => ({
|
||||
getWorkflowCtx: async () => ({ userId: 'u-1', permissions: ['customer_manage'], branchCode: 'BR002', roles: ['admin'] }),
|
||||
requireWorkflowPermission: () => undefined,
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/tenantScope', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/services/tenantScope')>();
|
||||
return {
|
||||
...actual,
|
||||
readOperatingBranchCode: () => 'BR002',
|
||||
getEffectiveBranchCode: () => 'BR002',
|
||||
invalidateTenantContextCache: () => undefined,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../src/services/quoteSheetService', () => ({
|
||||
createQuoteSheet: (...args: unknown[]) => H.createQuoteSheet(...args),
|
||||
}));
|
||||
|
||||
vi.mock('../src/services/quoteSheetEditService', () => ({
|
||||
applyQuoteSheetEditAndRequestDeliveryReview: (...args: unknown[]) => H.applyEdit(...args),
|
||||
}));
|
||||
|
||||
vi.mock('../src/db', () => ({
|
||||
pool: { query: (...args: unknown[]) => H.poolQuery(...args) },
|
||||
getRawPoolQuery: () => H.poolQuery,
|
||||
}));
|
||||
|
||||
const { mountQuoteWorkflowRoutes } = await import('../src/modules/workflow/routes/quoteRoutes');
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
const router = express.Router();
|
||||
mountQuoteWorkflowRoutes(router);
|
||||
app.use('/api/workflow', router);
|
||||
|
||||
const ITEM = { sku_code: 'SKU1', sale_price: 10, cost_price: 6 };
|
||||
|
||||
beforeEach(() => {
|
||||
H.createQuoteSheet.mockReset();
|
||||
H.applyEdit.mockReset();
|
||||
H.poolQuery.mockReset();
|
||||
H.createQuoteSheet.mockImplementation(async (input: any) => ({
|
||||
quote_sheet_code: `QS-${input.customerCodes[0]}`,
|
||||
items: [{ sku_code: 'SKU1', sale_price: 10, cost_price: 6, unit: '斤' }],
|
||||
title: input.title ?? null,
|
||||
quote_cycle: input.quoteCycle ?? null,
|
||||
effective_at: input.effectiveAt ?? null,
|
||||
}));
|
||||
H.applyEdit.mockResolvedValue({ data: { quote_sheet_code: 'QS-A', items: [{ sku_code: 'SKU1', sale_price: 10, cost_price: 6 }] }, delivery_handoff: null });
|
||||
// 默认:客户名下一律没有报价单
|
||||
H.poolQuery.mockImplementation(async (sql: string) => {
|
||||
const text = String(sql);
|
||||
if (text.includes('FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1')) {
|
||||
return { rows: [{ customer_code: 'CUS-A' }], rowCount: 1 };
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
});
|
||||
|
||||
describe('新建:勾 N 个客户 ⇒ 生成 N 张(一客户一单)', () => {
|
||||
it('3 个客户 ⇒ 调 3 次建单,每次只带 1 个客户,created_count=3', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/workflow/quote/sheet')
|
||||
.send({ customer_codes: ['CUS-A', 'CUS-B', 'CUS-C'], items: [ITEM] });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(H.createQuoteSheet).toHaveBeenCalledTimes(3);
|
||||
const calls = H.createQuoteSheet.mock.calls.map((c) => (c[0] as any).customerCodes);
|
||||
expect(calls).toEqual([['CUS-A'], ['CUS-B'], ['CUS-C']]);
|
||||
expect(res.body.created_count).toBe(3);
|
||||
});
|
||||
|
||||
it('1 个客户 ⇒ 只建 1 张,created_count=1', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/workflow/quote/sheet')
|
||||
.send({ customer_codes: ['CUS-A'], items: [ITEM] });
|
||||
expect(res.status).toBe(200);
|
||||
expect(H.createQuoteSheet).toHaveBeenCalledTimes(1);
|
||||
expect(res.body.created_count).toBe(1);
|
||||
});
|
||||
|
||||
it('一个客户都没选 ⇒ 400,不建单', async () => {
|
||||
const res = await request(app).post('/api/workflow/quote/sheet').send({ customer_codes: [], items: [ITEM] });
|
||||
expect(res.status).toBe(400);
|
||||
expect(H.createQuoteSheet).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('编辑:本单客户不变;追加的客户按本单模板新建', () => {
|
||||
it('追加一个名下无报价单的客户 ⇒ 保存本单后,为它建 1 张新单', async () => {
|
||||
const res = await request(app)
|
||||
.put('/api/workflow/quote/sheets/QS-A')
|
||||
.send({ customer_codes: ['CUS-A', 'CUS-B'], items: [ITEM] });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(H.applyEdit).toHaveBeenCalledTimes(1);
|
||||
expect(H.createQuoteSheet).toHaveBeenCalledTimes(1);
|
||||
expect((H.createQuoteSheet.mock.calls[0][0] as any).customerCodes).toEqual(['CUS-B']);
|
||||
expect(res.body.created_count).toBe(1);
|
||||
});
|
||||
|
||||
it('追加的客户名下已有报价单 ⇒ 400,且不建任何单', async () => {
|
||||
H.poolQuery.mockImplementation(async (sql: string) => {
|
||||
const text = String(sql);
|
||||
if (text.includes('FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1')) {
|
||||
return { rows: [{ customer_code: 'CUS-A' }], rowCount: 1 };
|
||||
}
|
||||
// 追加客户查重:CUS-B 已有报价单
|
||||
if (text.includes('ANY($1::text[])')) {
|
||||
return { rows: [{ customer_code: 'CUS-B' }], rowCount: 1 };
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.put('/api/workflow/quote/sheets/QS-A')
|
||||
.send({ customer_codes: ['CUS-A', 'CUS-B'], items: [ITEM] });
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toBe('customer_already_quoted');
|
||||
expect(H.createQuoteSheet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('只提交本单自己的客户 ⇒ 不新建任何单', async () => {
|
||||
const res = await request(app)
|
||||
.put('/api/workflow/quote/sheets/QS-A')
|
||||
.send({ customer_codes: ['CUS-A'], items: [ITEM] });
|
||||
expect(res.status).toBe(200);
|
||||
expect(H.createQuoteSheet).not.toHaveBeenCalled();
|
||||
expect(res.body.created_count).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -3,12 +3,11 @@ import request from 'supertest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* SEC-4(2026-10-19):全局角色/角色权限写操作仅 `super_admin`。
|
||||
*
|
||||
* 漏洞:`role_permissions` / `role_definitions` 是全局表(无 branch_code),
|
||||
* 分公司 `admin` 也能 POST/PUT/DELETE ⇒ 可给自己/其它分公司改全局权限(垂直提权)。
|
||||
* 修复(D1 最小可行):三个写端点要求 super_admin;admin 403,且 PUT 必须在
|
||||
* **取连接/开事务之前**拒绝(无 DELETE/INSERT 写 SQL)。GET 保持现状(admin 可读)。
|
||||
* SEC-4(2026-10-19,同日**修订**):
|
||||
* · 角色定义的新建/删除:仍仅 `super_admin`(会改变全局角色集合)。
|
||||
* · **角色权限的修改:由「管理员」维护**(开发者裁决:这块就是管理员的权限),
|
||||
* 但管理员不能改 `admin` / `super_admin` 两个角色(防自我提权)。
|
||||
* · 拒绝一律发生在取连接/开事务之前(零写 SQL)。GET 读路径不受影响。
|
||||
*
|
||||
* 本文件 mock 鉴权/租户上下文/角色服务,只验 HTTP 面与写 SQL 边界。
|
||||
*/
|
||||
@@ -106,21 +105,30 @@ beforeEach(() => {
|
||||
|
||||
const writeSql = () => H.clientSql.filter((sql) => /DELETE FROM role_permissions|INSERT INTO role_permissions/i.test(sql));
|
||||
|
||||
describe('SEC-4:admin 对全局角色写端点一律 403 且零写 SQL', () => {
|
||||
it('POST / ⇒ 403,不创建角色', async () => {
|
||||
describe('SEC-4(修订):admin 可维护角色权限,但不能改 admin/super_admin,也不能建删角色', () => {
|
||||
it('POST / ⇒ 403,不创建角色(角色定义仍仅超管)', async () => {
|
||||
const res = await request(app).post('/api/roles').send({ role_code: 'x', role_name: 'X' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(H.createRoleDefinition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('PUT /:roleCode/permissions ⇒ 403,且**连接/事务都没开始**(无 DELETE/INSERT)', async () => {
|
||||
it('PUT /:roleCode/permissions(普通角色)⇒ 200,执行 DELETE+INSERT', async () => {
|
||||
const res = await request(app)
|
||||
.put('/api/roles/operator/permissions')
|
||||
.send({ permission_ids: ['perm-1'] });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error).toBe('forbidden');
|
||||
expect(H.connect).not.toHaveBeenCalled();
|
||||
expect(writeSql()).toEqual([]);
|
||||
expect(res.status).toBe(200);
|
||||
expect(writeSql().length).toBe(2);
|
||||
});
|
||||
|
||||
it('PUT 到 admin / super_admin 角色 ⇒ 403,且零写 SQL(防自我提权)', async () => {
|
||||
for (const role of ['admin', 'super_admin']) {
|
||||
H.clientSql = [];
|
||||
const res = await request(app)
|
||||
.put(`/api/roles/${role}/permissions`)
|
||||
.send({ permission_ids: ['perm-1'] });
|
||||
expect(res.status).toBe(403);
|
||||
expect(writeSql()).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it('DELETE /:roleCode ⇒ 403,不删除角色', async () => {
|
||||
|
||||
@@ -284,6 +284,9 @@ export interface OrderDetailDeliveryNotePanelProps {
|
||||
onCostPriceCommit?: (skuCode: string, costPrice: number) => void;
|
||||
/** 待补录:实收可填(明细仍可能锁定) */
|
||||
canEditReceivedQty?: boolean;
|
||||
/** 单行取消库存抵扣(2026-10-19):待分拣(45)仍可用;50+ 后端拒绝 */
|
||||
onCancelStockCover?: (item: OrderItem) => void;
|
||||
cancelStockCoverItemId?: string | null;
|
||||
}
|
||||
|
||||
export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanelProps> = ({
|
||||
@@ -337,6 +340,8 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
showCostPrice = false,
|
||||
onCostPriceCommit,
|
||||
canEditReceivedQty = false,
|
||||
onCancelStockCover,
|
||||
cancelStockCoverItemId = null,
|
||||
}) => {
|
||||
const { t, locale } = useI18n();
|
||||
const ownerOptions = [
|
||||
@@ -724,7 +729,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto border border-slate-700 dark:border-slate-500">
|
||||
<div className="overflow-x-hidden border border-slate-700 dark:border-slate-500">
|
||||
{loading ? (
|
||||
<div className="px-4 py-10 text-center text-sm text-slate-500">
|
||||
<Loader2 className="w-5 h-5 animate-spin inline-block mr-2" />
|
||||
@@ -733,10 +738,31 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
) : items.length === 0 ? (
|
||||
<div className="px-4 py-10 text-center text-sm text-slate-500">{t('orders.detail.emptyItems')}</div>
|
||||
) : (
|
||||
<table className="w-full border-collapse text-sm min-w-[860px]">
|
||||
<table className="w-full table-fixed border-collapse text-xs">
|
||||
<colgroup>
|
||||
{[
|
||||
'2.5%',
|
||||
'2.5%',
|
||||
'14%',
|
||||
'4%',
|
||||
'3%',
|
||||
'3%',
|
||||
'7%',
|
||||
'5%',
|
||||
'3%',
|
||||
...(showCostPrice ? ['6%', '6%'] : []),
|
||||
...(hideSalePrice ? [] : ['4%']),
|
||||
'6%',
|
||||
'5%',
|
||||
'8%',
|
||||
...(showEditCols ? ['5%', '6%', '10%'] : []),
|
||||
].map((w, i) => (
|
||||
<col key={i} style={{ width: w }} />
|
||||
))}
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr className="bg-slate-50 dark:bg-slate-800">
|
||||
<th className="w-8 border border-slate-700 dark:border-slate-500 px-1 py-1.5 text-center">
|
||||
<th className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 text-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={t('orders.detail.selectAllBatchReports')}
|
||||
@@ -776,7 +802,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
].map((label) => (
|
||||
<th
|
||||
key={label}
|
||||
className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 text-xs font-semibold whitespace-nowrap"
|
||||
className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 text-[11px] font-semibold whitespace-normal break-words leading-tight"
|
||||
>
|
||||
{label}
|
||||
</th>
|
||||
@@ -837,7 +863,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
key={item.id}
|
||||
className={`align-top ${item.inspection_failed ? 'bg-rose-50 dark:bg-rose-950/30' : ''}`}
|
||||
>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 text-center w-8">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 text-center">
|
||||
{(() => {
|
||||
const hasBatchReport = (item.batch_report_files || []).length > 0;
|
||||
return (
|
||||
@@ -852,10 +878,10 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
);
|
||||
})()}
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 text-center tabular-nums w-10">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 text-center tabular-nums">
|
||||
{seq}
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 min-w-[10rem]">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 min-w-0">
|
||||
{rowEditable ? (
|
||||
<div className="space-y-0.5 min-w-0">
|
||||
<SkuNameSelector
|
||||
@@ -905,7 +931,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 w-[6rem]">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 w-auto">
|
||||
{/**
|
||||
* 商品规格(录单录入 / 人工修正)。
|
||||
* 可编辑行给输入框(2026-10-16 开发者:「这边规格是可以在订单详情这块修改的」),
|
||||
@@ -931,7 +957,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 w-[5.5rem]">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 w-auto">
|
||||
<InboundPhotoThumbs
|
||||
photos={item.inbound_photos}
|
||||
onOpen={(index) => {
|
||||
@@ -942,7 +968,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 w-[5.5rem]">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1.5 w-auto">
|
||||
<QualityReportThumbs
|
||||
files={item.quality_report_files}
|
||||
onOpenImage={(images, index) => {
|
||||
@@ -952,7 +978,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
}}
|
||||
/>
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 min-w-[8.5rem]">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 min-w-0">
|
||||
{/*
|
||||
**加工方式与「是否加工」由我方设置**(2026-10-14 开发者校正:
|
||||
「真实的商品加工方式 是我们直接来设置 而不是被主系统定死」)。
|
||||
@@ -1166,7 +1192,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
formatReceivedQty(item.received_qty)
|
||||
)}
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 min-w-[6rem] text-center">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-2 py-1.5 min-w-0 text-center">
|
||||
{rowEditable ? (
|
||||
<input
|
||||
type="text"
|
||||
@@ -1183,7 +1209,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
</td>
|
||||
{showEditCols ? (
|
||||
<>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1 min-w-[7rem]">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1 min-w-0">
|
||||
<SearchableSelect
|
||||
value={item.category_code || ''}
|
||||
onChange={(value) => onUpdateCategory(item.id, value || '')}
|
||||
@@ -1209,7 +1235,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
onCreateFromQuery={(name) => onCreateCategory?.(item.id, name)}
|
||||
/>
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1 min-w-[8rem]">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1 min-w-0">
|
||||
<SearchableSelect
|
||||
value={item.supplier_code || ''}
|
||||
onChange={(supplierCode) => {
|
||||
@@ -1300,7 +1326,7 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
]}
|
||||
/>
|
||||
</td>
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1 text-center w-14">
|
||||
<td className="border border-slate-700 dark:border-slate-500 px-1 py-1 text-center">
|
||||
{isMainSystemOrder ? (
|
||||
<div className="inline-flex flex-col items-stretch gap-1">
|
||||
{/**
|
||||
@@ -1343,7 +1369,18 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
{t('orders.detail.stockout')}
|
||||
</button>
|
||||
)}
|
||||
{/* 2026-10-17 开发者裁决:主系统同步过来的行**也允许删除**
|
||||
{Number(item.cover_qty || 0) > 1e-9 && !item.is_returned && (orderStatus ?? 0) < 50 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onCancelStockCover?.(item)}
|
||||
disabled={!onCancelStockCover || cancelStockCoverItemId === String(item.id)}
|
||||
title={t('orders.detail.cancelCoverConfirm')}
|
||||
className="inline-flex px-1.5 py-1 text-xs font-medium text-rose-700 hover:bg-rose-50 rounded disabled:opacity-40 whitespace-nowrap"
|
||||
>
|
||||
{t('orders.detail.cancelCover')}
|
||||
</button>
|
||||
) : null}
|
||||
{/* 2026-10-17 开发者裁决:主系统同步过来的行**也允许删除**
|
||||
(废行/发错商品不再只有「缺货」一条路;删单仍禁止)。
|
||||
删除后服务层会把该行的主系统台账置 cancelled,下一轮不会复活。
|
||||
已入库的行仍走「退货」而不是硬删(与自建行同一条规则)。 */}
|
||||
@@ -1387,7 +1424,18 @@ export const OrderDetailDeliveryNotePanel: React.FC<OrderDetailDeliveryNotePanel
|
||||
{t('orders.coverSku.select')}
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
{Number(item.cover_qty || 0) > 1e-9 && !item.is_returned && (orderStatus ?? 0) < 50 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onCancelStockCover?.(item)}
|
||||
disabled={!onCancelStockCover || cancelStockCoverItemId === String(item.id)}
|
||||
title={t('orders.detail.cancelCoverConfirm')}
|
||||
className="inline-flex px-1.5 py-1 text-xs font-medium text-rose-700 hover:bg-rose-50 rounded disabled:opacity-40 whitespace-nowrap"
|
||||
>
|
||||
{t('orders.detail.cancelCover')}
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveItem(item)}
|
||||
disabled={
|
||||
|
||||
@@ -82,7 +82,8 @@ describe('录单行 · 规格字段', () => {
|
||||
|
||||
it('⑧ 订单详情:规格可编辑(写回 onUpdateItem)且切换商品时跟随新 SKU 的规格', () => {
|
||||
const panel = read('./OrderDetailDeliveryNotePanel.tsx');
|
||||
const cell = panel.slice(panel.indexOf("w-[6rem]\">"), panel.indexOf('<InboundPhotoThumbs'));
|
||||
const specIdx = panel.indexOf("value={String(item.spec || '')");
|
||||
const cell = panel.slice(panel.lastIndexOf('<td', specIdx), panel.indexOf('</td>', specIdx));
|
||||
expect(cell, '可编辑行给输入框').toContain('rowEditable ? (');
|
||||
expect(cell).toContain('value={String(item.spec || \'\')}');
|
||||
expect(cell).toContain('onUpdateItem(item.id, { spec: e.target.value.slice(0, 60) })');
|
||||
|
||||
@@ -417,6 +417,10 @@ export const orders: MessageDict = {
|
||||
'detail.selfPurchase': 'Self-purchase',
|
||||
'detail.unassigned': 'Unassigned',
|
||||
'detail.stockCover': 'Inventory cover',
|
||||
'detail.cancelCover': 'Cancel cover',
|
||||
'detail.cancelCoverConfirm': 'Cancel the inventory cover for this item? You will need to assign a supplier or self-purchase again.',
|
||||
'detail.cancelCoverDone': 'Inventory cover cancelled for this item',
|
||||
'detail.cancelCoverFail': 'Failed to cancel inventory cover',
|
||||
'detail.coverCostHint': 'Inventory cover cost = weighted average of covered batches; ¥{cover} booked for this line ({qty} covered)',
|
||||
'coverBatch.editCost': 'Edit cost',
|
||||
'coverBatch.editTitle': 'Edit inbound cost of batch {batch}',
|
||||
|
||||
@@ -159,6 +159,7 @@ export const quotes: MessageDict = {
|
||||
'toast.submittedForApproval': 'Submitted for approval',
|
||||
'toast.submittedForDeliveryReview': 'Submitted to delivery for review',
|
||||
'toast.submitForDeliveryFail': 'Failed to submit for delivery review',
|
||||
'toast.createdMany': 'Created {count} quote sheets',
|
||||
'toast.created': 'Quote sheet created and active',
|
||||
'toast.updateFail': 'Update failed',
|
||||
'toast.createFail': 'Create failed',
|
||||
|
||||
@@ -417,6 +417,10 @@ export const orders: MessageDict = {
|
||||
'detail.selfPurchase': 'Swakelola',
|
||||
'detail.unassigned': 'Belum dialokasi',
|
||||
'detail.stockCover': 'Penutupan stok',
|
||||
'detail.cancelCover': 'Batalkan penutupan',
|
||||
'detail.cancelCoverConfirm': 'Batalkan penutupan stok untuk item ini? Anda perlu menetapkan pemasok atau swakelola lagi.',
|
||||
'detail.cancelCoverDone': 'Penutupan stok item dibatalkan',
|
||||
'detail.cancelCoverFail': 'Gagal membatalkan penutupan stok',
|
||||
'detail.coverCostHint': 'Biaya penutupan stok = rata-rata tertimbang batch; ¥{cover} untuk baris ini ({qty} ditutup)',
|
||||
'coverBatch.editCost': 'Ubah biaya',
|
||||
'coverBatch.editTitle': 'Ubah biaya batch {batch}',
|
||||
|
||||
@@ -164,6 +164,7 @@ export const quotes: MessageDict = {
|
||||
'toast.submitForDeliveryFail': 'Gagal mengirim ke pengiriman',
|
||||
'toast.updated':
|
||||
'Lembar penawaran diperbarui; hanya memengaruhi pesanan berikutnya',
|
||||
'toast.createdMany': 'Dibuat {count} lembar penawaran',
|
||||
'toast.created': 'Lembar penawaran dibuat dan aktif',
|
||||
'toast.updateFail': 'Gagal memperbarui',
|
||||
'toast.createFail': 'Gagal membuat',
|
||||
|
||||
@@ -410,6 +410,10 @@ export const orders: MessageDict = {
|
||||
'detail.selfPurchase': '自采',
|
||||
'detail.unassigned': '未分配',
|
||||
'detail.stockCover': '库存抵扣',
|
||||
'detail.cancelCover': '取消抵扣',
|
||||
'detail.cancelCoverConfirm': '确定取消该商品的库存抵扣?取消后需重新分配供应商/自采。',
|
||||
'detail.cancelCoverDone': '已取消该商品的库存抵扣',
|
||||
'detail.cancelCoverFail': '取消库存抵扣失败',
|
||||
'detail.coverCostHint': '库存抵扣成本 = 被抵扣批次加权均价;本行已计入 ¥{cover}(抵扣 {qty} 斤)',
|
||||
'coverBatch.editCost': '改成本',
|
||||
'coverBatch.editTitle': '修改批次 {batch} 的入库成本',
|
||||
|
||||
@@ -155,6 +155,7 @@ export const quotes: MessageDict = {
|
||||
'toast.submittedForApproval': '已提交审核',
|
||||
'toast.submittedForDeliveryReview': '已提交配送商审核',
|
||||
'toast.submitForDeliveryFail': '提交配送商审核失败',
|
||||
'toast.createdMany': '已生成 {count} 张报价单',
|
||||
'toast.created': '报价单已创建并生效',
|
||||
'toast.updateFail': '修改失败',
|
||||
'toast.createFail': '创建失败',
|
||||
|
||||
@@ -665,6 +665,11 @@ export const QuoteVersionManagement: React.FC = () => {
|
||||
|
||||
const addCustomerFromSelector = (customer: CustomerOption) => {
|
||||
if (form.customer_codes.includes(customer.customer_code)) return;
|
||||
/**
|
||||
* 2026-10-19 开发者裁决:**一个客户一张报价单**。
|
||||
* 编辑本单时自己的客户不变;这里勾选其它客户 = **追加**,
|
||||
* 保存时以本单数据为模板给它们各建一张(名下有报价单的会被后端拒绝)。
|
||||
*/
|
||||
setForm((f) => ({
|
||||
...f,
|
||||
customer_codes: [...f.customer_codes, customer.customer_code],
|
||||
@@ -925,8 +930,11 @@ export const QuoteVersionManagement: React.FC = () => {
|
||||
* 然后自动发一条「配送商销售价确认」申请给对方审核(配送商审核通过后才写他自己那边的成本价)。
|
||||
* 传递失败不回滚已生效的改价,只提示原因(可在「配送商销售价确认」tab 重新发起)。
|
||||
*/
|
||||
const newSheets = Number((response as any)?.created_count || 0);
|
||||
if (response.delivery_handoff && response.delivery_handoff.ok === false) {
|
||||
notify.error(response.delivery_handoff.message || t('quotes.toast.updateFail'));
|
||||
} else if (newSheets > 0) {
|
||||
notify.success(t('quotes.toast.createdMany', { count: newSheets }));
|
||||
} else {
|
||||
notify.success(t('quotes.toast.updated'));
|
||||
}
|
||||
@@ -935,8 +943,13 @@ export const QuoteVersionManagement: React.FC = () => {
|
||||
setViewFilter('active');
|
||||
if (wasActiveView) await loadSheets();
|
||||
} else {
|
||||
await createQuoteSheetApi(payload);
|
||||
notify.success(t('quotes.toast.created'));
|
||||
const createdResult = await createQuoteSheetApi(payload);
|
||||
const generatedCount = Number((createdResult as any)?.created_count || 1);
|
||||
notify.success(
|
||||
generatedCount > 1
|
||||
? t('quotes.toast.createdMany', { count: generatedCount })
|
||||
: t('quotes.toast.created')
|
||||
);
|
||||
closeFormModal();
|
||||
const wasActiveView = viewFilter === 'active';
|
||||
setViewFilter('active');
|
||||
|
||||
@@ -135,6 +135,20 @@ interface CustomerSkuAlias {
|
||||
usage_count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 「散客」内建客户(2026-10-18 开发者裁决:散客就是客户下拉里的一个客户,
|
||||
* 不再单独给一个勾选框)。编码 `__RETAIL__` 与订单列表/后端的零售口径一致:
|
||||
* 选它录单 = 只建单 + 全额库存抵扣(待扣除),确认扣除即完成,不走采购/分拣/配送。
|
||||
* 库里若有 `__RETAIL__` 行则用库里的(按编码去重,避免出现两条「散客」)。
|
||||
*/
|
||||
const RETAIL_CUSTOMER_OPTION = {
|
||||
customer_code: '__RETAIL__',
|
||||
company_name: '散客',
|
||||
address: null as string | null,
|
||||
settlement_days: null as number | null,
|
||||
delivery_time: null as string | null,
|
||||
};
|
||||
|
||||
const getTomorrow = () => getDefaultDeliveryDate();
|
||||
|
||||
// ==================== 主组件 ====================
|
||||
@@ -271,8 +285,11 @@ export const CustomerOrder: React.FC = () => {
|
||||
const customersRef = useRef(customers);
|
||||
customersRef.current = customers;
|
||||
const submitOrderRef = useRef<() => Promise<void>>(async () => {});
|
||||
/** 散客录单模式(2026-10-15):只建单+全额库存抵扣,无采购/分拣/配送;录完点『确认完成』即完成 */
|
||||
const [retailMode, setRetailMode] = useState(false);
|
||||
/**
|
||||
* 散客模式:**由所选客户决定**(2026-10-18 开发者裁决:散客就是客户下拉里的一个客户)。
|
||||
* 选「散客」= 只建单 + 全额库存抵扣,无采购/分拣/配送。
|
||||
*/
|
||||
const retailMode = selectedCustomer?.customer_code === RETAIL_CUSTOMER_OPTION.customer_code;
|
||||
const [catalogReady, setCatalogReady] = useState(false);
|
||||
const [pendingIntake, setPendingIntake] = useState<OrderEntryIntake | null>(null);
|
||||
useEffect(() => {
|
||||
@@ -436,7 +453,6 @@ export const CustomerOrder: React.FC = () => {
|
||||
const [filteredSkus, setFilteredSkus] = useState<SkuMapping[]>([]);
|
||||
|
||||
// 切换操作分公司时重新加载数据并重置录单状态
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (isSuperAdmin && !effectiveBranchCode) return;
|
||||
fetchInitialData();
|
||||
@@ -465,7 +481,7 @@ export const CustomerOrder: React.FC = () => {
|
||||
}, [location.key]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedCustomer) {
|
||||
if (selectedCustomer && selectedCustomer.customer_code !== RETAIL_CUSTOMER_OPTION.customer_code) {
|
||||
fetchCustomerSkus(selectedCustomer.customer_code);
|
||||
fetchCustomerAliases(selectedCustomer.customer_code);
|
||||
fetchProcessingAliases(selectedCustomer.customer_code);
|
||||
@@ -590,9 +606,13 @@ export const CustomerOrder: React.FC = () => {
|
||||
(c: { customer_code?: string }) =>
|
||||
c.customer_code === INDEPENDENT_INBOUND_CUSTOMER_OPTION.customer_code
|
||||
);
|
||||
setCustomers(
|
||||
hasIndependentInbound ? customerRows : [INDEPENDENT_INBOUND_CUSTOMER_OPTION, ...customerRows]
|
||||
const hasRetail = customerRows.some(
|
||||
(c: { customer_code?: string }) => c.customer_code === RETAIL_CUSTOMER_OPTION.customer_code
|
||||
);
|
||||
const withSentinels = hasIndependentInbound
|
||||
? customerRows
|
||||
: [INDEPENDENT_INBOUND_CUSTOMER_OPTION, ...customerRows];
|
||||
setCustomers(hasRetail ? withSentinels : [RETAIL_CUSTOMER_OPTION, ...withSentinels]);
|
||||
|
||||
// 加载SKU列表 + 品类名称(客户端 JOIN,避免 Supabase embed 语法导致的 SQL 错误)
|
||||
const [skuResult, catResult] = await Promise.all([
|
||||
@@ -1157,7 +1177,6 @@ export const CustomerOrder: React.FC = () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// 灌入依赖解析结果与客户目录,不跟 map 函数引用绑定
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [pendingIntake, catalogReady, customers]);
|
||||
|
||||
const updateItemCategory = useCallback((id: string, categoryCode: string) => {
|
||||
@@ -2156,29 +2175,10 @@ export const CustomerOrder: React.FC = () => {
|
||||
</p>
|
||||
</div>
|
||||
{/**
|
||||
* 「散客录单」入口开关(2026-10-15 需求,2026-10-16 补回)。
|
||||
*
|
||||
* ⚠️ 此前**全仓没有任何地方能打开 `retailMode`**(只有 `useState(false)` 与提交分支)
|
||||
* ⇒ 界面永远进不了散客模式(开发者报障「录单页没有散客录单」);
|
||||
* 本处把入口补回来,并配套契约测试防再丢。权限由后端 `POST /orders/retail` 把关。
|
||||
* 「散客」不再是独立勾选框(2026-10-18 开发者裁决):
|
||||
* 它是客户下拉里的一个客户(编码 `__RETAIL__`),与普通客户一起选。
|
||||
* 选中散客时在客户选择器下方给出「只扣库存」的说明(见下方 retailMode 提示)。
|
||||
*/}
|
||||
<div className="shrink-0 pb-0.5">
|
||||
<label
|
||||
className="app-foreground-muted inline-flex items-center gap-1.5 text-xs cursor-pointer select-none"
|
||||
title={t('orders.retailModeHint')}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={retailMode}
|
||||
onChange={(e) => setRetailMode(e.target.checked)}
|
||||
className="rounded border-gray-300"
|
||||
/>
|
||||
{t('orders.retailMode')}
|
||||
</label>
|
||||
{retailMode && (
|
||||
<p className="app-foreground-muted text-[11px] mt-0.5 max-w-[18rem]">{t('orders.retailModeHint')}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
<label className="app-foreground-muted block text-[11px] font-medium mb-0.5">{t('orders.deliveryDate')}</label>
|
||||
<div className="relative">
|
||||
@@ -2263,17 +2263,22 @@ export const CustomerOrder: React.FC = () => {
|
||||
parsingLabel={t('orders.parsing')}
|
||||
className="flex-1 min-h-0"
|
||||
headerLeading={
|
||||
<CustomerSelector
|
||||
customers={customers}
|
||||
selectedCustomer={selectedCustomer}
|
||||
requiredEmpty
|
||||
className="w-full min-w-0"
|
||||
onSelect={(customer) => {
|
||||
setSelectedCustomer(customer);
|
||||
setCustomerSearchQuery(customer.company_name);
|
||||
setShowCustomerDropdown(false);
|
||||
}}
|
||||
/>
|
||||
<>
|
||||
{retailMode ? (
|
||||
<p className="app-foreground-muted text-[11px] mb-1 max-w-[24rem]">{t('orders.retailModeHint')}</p>
|
||||
) : null}
|
||||
<CustomerSelector
|
||||
customers={customers}
|
||||
selectedCustomer={selectedCustomer}
|
||||
requiredEmpty
|
||||
className="w-full min-w-0"
|
||||
onSelect={(customer) => {
|
||||
setSelectedCustomer(customer);
|
||||
setCustomerSearchQuery(customer.company_name);
|
||||
setShowCustomerDropdown(false);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
imageSlot={
|
||||
<div
|
||||
|
||||
@@ -111,6 +111,7 @@ import {
|
||||
getHistoricalFinalizeAllowlistApi,
|
||||
historicalFinalizeOrderApi,
|
||||
applyInventoryOffsetApi,
|
||||
cancelOrderItemStockCoverApi,
|
||||
} from '../../../utils/workflowApi';
|
||||
import { useCategoryRows } from '../../../hooks/useCategoryRows';
|
||||
import { useRowClickOrDoubleClick } from '../../../hooks/useRowClickOrDoubleClick';
|
||||
@@ -255,7 +256,7 @@ export const OrderManagement: React.FC = () => {
|
||||
canEditOrderItems: canEditOrderItemsPermission,
|
||||
isAdmin,
|
||||
canEditCompleted: canEditCompletedOrder,
|
||||
canForceEdit: hasRole(['super_admin', 'admin']) || hasPermission('order_force_edit'),
|
||||
canForceEdit: hasRole(['super_admin', 'admin']) || hasPermission('order_force_edit') || hasPermission('order_edit'),
|
||||
};
|
||||
const canEditItemsForOrder = (order: Pick<Order, 'order_status' | 'created_at'>) => {
|
||||
const status = Number(order.order_status);
|
||||
@@ -3160,6 +3161,36 @@ export const OrderManagement: React.FC = () => {
|
||||
setInventoryOffsetCode(null);
|
||||
}
|
||||
};
|
||||
/** 单行取消库存抵扣(2026-10-19):45 待分拣仍可用,取消后需重新选择供应商/自采 */
|
||||
const [cancelCoverItemId, setCancelCoverItemId] = useState<string | null>(null);
|
||||
const handleCancelStockCover = async (item: OrderItem) => {
|
||||
if (!selectedOrder) return;
|
||||
if (!window.confirm(t('orders.detail.cancelCoverConfirm'))) return;
|
||||
const itemId = String(item.id);
|
||||
setCancelCoverItemId(itemId);
|
||||
try {
|
||||
const res = await cancelOrderItemStockCoverApi(selectedOrder.order_code, itemId);
|
||||
const nextStatus = Number(res?.data?.order_status_after);
|
||||
const patch = {
|
||||
cover_qty: 0,
|
||||
stock_cover_qty: 0,
|
||||
supplier_code: 'UNASSIGNED',
|
||||
supplier_name: t('orders.detail.unassigned'),
|
||||
allocation_hint: undefined,
|
||||
} as Partial<OrderItem>;
|
||||
setOrderItems((prev) => prev.map((row) => (String(row.id) === itemId ? { ...row, ...patch } : row)));
|
||||
setEditItems((prev) => prev.map((row) => (String(row.id) === itemId ? { ...row, ...patch } : row)));
|
||||
if (Number.isFinite(nextStatus) && nextStatus > 0) {
|
||||
setSelectedOrder((prev) => (prev ? { ...prev, order_status: nextStatus } : prev));
|
||||
}
|
||||
notify.success(t('orders.detail.cancelCoverDone'));
|
||||
} catch (error: any) {
|
||||
notify.error(error instanceof Error ? error.message : t('orders.detail.cancelCoverFail'));
|
||||
} finally {
|
||||
setCancelCoverItemId(null);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const openAutoAdvanceConfig = async () => {
|
||||
setShowAutoAdvanceConfig(true);
|
||||
@@ -4601,6 +4632,8 @@ export const OrderManagement: React.FC = () => {
|
||||
canEditPrice={canEditOrderPrice}
|
||||
hideSalePrice={isIndependentInboundCustomer(selectedOrder.customer_code)}
|
||||
orderStatus={selectedOrder.order_status}
|
||||
onCancelStockCover={handleCancelStockCover}
|
||||
cancelStockCoverItemId={cancelCoverItemId}
|
||||
loading={orderItemsLoading}
|
||||
items={detailDisplayItems}
|
||||
groupedItems={detailGroupedItems}
|
||||
|
||||
@@ -6390,6 +6390,21 @@ export async function historicalFinalizeOrderApi(orderCode: string) {
|
||||
* 场景:主系统分配单在分配那一刻**库存还没上新** ⇒ 抵扣 0、缺口全转采购;补录库存后点这个按钮重跑分配路线。
|
||||
* 后端复用既有 `reprocessOrderAllocation`(行锁 + 幂等 + 重规划采购),返回 `message` 直接给界面提示。
|
||||
*/
|
||||
/** 单行取消库存抵扣(2026-10-19):待分拣(45)仍可取消单个商品的抵扣库存;50+ 拒绝。 */
|
||||
export async function cancelOrderItemStockCoverApi(orderCode: string, itemId: string) {
|
||||
return workflowFetch<{
|
||||
data: {
|
||||
cancelled: boolean;
|
||||
coverQty: number;
|
||||
skuCode: string | null;
|
||||
order_status_after: number | null;
|
||||
};
|
||||
}>(`/orders/${encodeURIComponent(orderCode)}/items/${encodeURIComponent(itemId)}/cancel-stock-cover`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function applyInventoryOffsetApi(orderCode: string) {
|
||||
return workflowFetch<{
|
||||
data: {
|
||||
|
||||
Reference in New Issue
Block a user