feat(成本排行): 二期客户销售价编辑与安全护栏
按供应商报价单/客户商品库结构落地:迁移价格字段与手工标记;报价单/商品库改价、指定报价单与共享单409、同值不改、0/null拒绝、superadmin操作分公司、自动加成/完成回写/报价单编辑/订单改成本不覆盖人工价;录单取价新增客户商品库档;成本排行铅笔编辑。未部署。
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
# 供应商系统 · 商品成本排行客户销售价编辑(二期)
|
||||
|
||||
- 日期:2026-10-27
|
||||
- 状态:按开发者确认「先一步步来」落地;一期只读已提交 `b8a7837` / `89e9a83`
|
||||
- 关联冻结面:`finance-freeze`、`product-freeze`、供应链取价链路
|
||||
- 任务 id:`supplier-sku-price-edit`
|
||||
|
||||
## 1. 业务差异(为什么不直接复制配送系统)
|
||||
|
||||
供应商系统与配送系统不是同一套业务:
|
||||
|
||||
1. 我方报价单 `customer_quote_sheet_items`:
|
||||
- `sale_price` = 我方对客户的销售价;
|
||||
- `price` = 历史兼容/同步价,读取时 `sale_price ?? price`;
|
||||
- `cost_price` = 成本价(只读);
|
||||
- 报价单有 `auto_sale_price_by_cost` + `markup_ratio`,完成供货时可能自动重写销售价。
|
||||
2. `customer_skus` 已有 `price_preference` / `discount_rate`,但没有显式销售价。
|
||||
3. 成本排行已经包含库存抵扣成本、自采/供应商拆分、仓内加工成本;新增价格字段**不得参与**成本/毛利计算。
|
||||
|
||||
## 2. 数据
|
||||
|
||||
新增迁移(所有 tenant schema + tenant_template):
|
||||
|
||||
`customer_skus`:
|
||||
|
||||
| 列 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `sale_price` | NUMERIC(12,4) NULL | 客户商品库显式销售价,>0 才生效 |
|
||||
| `cost_price` | NUMERIC(12,4) NULL | 客户商品库成本价(本期只读展示) |
|
||||
| `price_updated_at` | TIMESTAMPTZ NULL | 最近改价时间 |
|
||||
| `price_updated_by` | UUID NULL | 最近改价人 |
|
||||
|
||||
`customer_quote_sheet_items`:
|
||||
|
||||
| 列 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `sale_price_manual` | BOOLEAN NOT NULL DEFAULT false | 人工改价标记;自动加成不得覆盖 |
|
||||
|
||||
`price_preference` / `discount_rate` 保留,不合并、不改写。
|
||||
|
||||
## 3. 只读排行
|
||||
|
||||
`marginQueryService.getSkuDirectCosts` 每行增加:
|
||||
|
||||
```ts
|
||||
price_source?: 'quote' | 'customer_sku' | 'order';
|
||||
sale_price?: number | null;
|
||||
cost_price?: number | null;
|
||||
quote_sheet_options?: Array<{ code; title; customer_code; sale_price }>;
|
||||
sale_price_targets?: Array<{
|
||||
target_type: 'quote_sheet' | 'customer_sku';
|
||||
customer_code: string;
|
||||
customer_name?: string | null;
|
||||
quote_sheet_code?: string;
|
||||
title?: string | null;
|
||||
sale_price: number;
|
||||
}>;
|
||||
```
|
||||
|
||||
- 单客户:报价单优先 → customer_skus.sale_price → 订单单位成本。
|
||||
- 全部客户:报价单 + customer_skus 目标合并去重。
|
||||
- 任何新字段不参与金额/毛利率/排序。
|
||||
|
||||
## 4. 改价接口
|
||||
|
||||
`PUT /workflow/customers/:customerCode/sku-sale-price`
|
||||
|
||||
body:`{ sku_code, sale_price: number, target_type?: 'quote_sheet'|'customer_sku', quote_sheet_code?: string }`;`sale_price` 必须是 **>0** 的两位小数。**二期不支持 0/null 清空**(避免把报价单写成 0 价卡住分拣/回写,也避免手改标记无法恢复)。
|
||||
|
||||
权限:`cost_manage` / `finance_manage` / `customer_manage`。
|
||||
|
||||
写目标:
|
||||
|
||||
1. 前端指定 `target_type=quote_sheet` 且报价单仍生效、包含 SKU、且该报价单只绑定一个客户 → 写 `customer_quote_sheet_items.sale_price + price`,并置 `sale_price_manual=true`;
|
||||
多客户共用报价单 → 409,不跨客户改价;
|
||||
2. 否则 upsert `customer_skus.sale_price`;
|
||||
3. 不写订单/结算/库存。
|
||||
|
||||
`quoteMarkupSalePriceService` 自动调价、`preparationCostService` 完成回写都跳过 `sale_price_manual=true` 的行;报价单编辑 DELETE+INSERT 时按 SKU 保留该标记。
|
||||
|
||||
## 5. 录单取价
|
||||
|
||||
在供应商现有取价链路上插入一档:
|
||||
|
||||
```text
|
||||
生效报价单 sale_price
|
||||
→ customer_skus.sale_price(新增,>0)
|
||||
→ 最近成交价
|
||||
→ 中标价
|
||||
→ price_preference × discount_rate
|
||||
→ 0
|
||||
```
|
||||
|
||||
改动点:`orderPricingService`(提交/预填/单位变更兜底)、`orderItemHelpers.fillBidPrices`、小程序客户商品接口(如有)。
|
||||
显式客户商品库价不乘折扣。
|
||||
|
||||
## 6. UI(供应商版)
|
||||
|
||||
- 单客户:显示来源(报价单/商品库/订单)+ 当前销售价;铅笔就地编辑并保存。
|
||||
- 全部客户:显示报价单/商品库目标价格区间;行单击展开目标列表,逐行输入,失焦/回车保存。
|
||||
- 成本排行保持现有库存抵扣、自采/供应商、加工成本展示;毛利率只保留一处、黑色。
|
||||
- 不在行内展示编辑说明小字;不新增非必要文案。
|
||||
|
||||
## 7. 验收
|
||||
|
||||
1. 迁移幂等;4 列/1 列存在。
|
||||
2. 单客户报价单改价:写 quote item,下一次录单取新价;自动加成不覆盖。
|
||||
3. 单客户非报价单改价:写 customer_skus,下一次录单取新价。
|
||||
4. 全部客户逐目标改价,失败行不显示未落库值。
|
||||
5. 排行金额/毛利率与改价前**完全一致**。
|
||||
6. 权限 403、super_admin + 操作分公司、审计 old_value、清理/回滚。
|
||||
7. 订单/库存/结算零写入。
|
||||
@@ -0,0 +1,18 @@
|
||||
-- 2026-10-27:客户商品库显式销售价/成本价 + 报价单人工改价标记(二期)
|
||||
-- 所有 tenant schema + tenant_template;幂等;不删 price_preference / discount_rate。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||||
LOOP
|
||||
EXECUTE format('ALTER TABLE %I.customer_skus ADD COLUMN IF NOT EXISTS sale_price NUMERIC(12,4)', sch);
|
||||
EXECUTE format('ALTER TABLE %I.customer_skus ADD COLUMN IF NOT EXISTS cost_price NUMERIC(12,4)', sch);
|
||||
EXECUTE format('ALTER TABLE %I.customer_skus ADD COLUMN IF NOT EXISTS price_updated_at TIMESTAMPTZ', sch);
|
||||
EXECUTE format('ALTER TABLE %I.customer_skus ADD COLUMN IF NOT EXISTS price_updated_by UUID', sch);
|
||||
EXECUTE format('ALTER TABLE %I.customer_quote_sheet_items ADD COLUMN IF NOT EXISTS sale_price_manual BOOLEAN NOT NULL DEFAULT false', sch);
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
deleteCustomer,
|
||||
} from '../../../services/customerOps';
|
||||
import { getWorkflowCtx, requireWorkflowPermission } from '../context';
|
||||
import { getEffectiveBranchCode, readOperatingBranchCode } from '../../../services/tenantScope';
|
||||
import { requireAdminRole } from '../context';
|
||||
import { getGeoProvider, isValidLatLng } from '../../../services/geoProvider';
|
||||
|
||||
@@ -49,6 +50,51 @@ router.post('/customers/:customerCode/self-pickup', authMiddleware, async (req:
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 客户商品库/执行中报价单销售价(二期):有生效报价单且含 SKU ⇒ 写报价单;
|
||||
* 否则 upsert customer_skus。只写价格,不写订单/结算/库存。
|
||||
*/
|
||||
router.put('/customers/:customerCode/sku-sale-price', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
if (!ctx) return res.status(401).json({ error: 'unauthorized', error_description: '未登录' });
|
||||
if (!ctx.isSuperAdmin) {
|
||||
requireWorkflowPermission(ctx, ['cost_manage', 'finance_manage', 'customer_manage']);
|
||||
}
|
||||
const customerCode = String(req.params.customerCode || '').trim();
|
||||
const skuCode = String(req.body?.sku_code || '').trim();
|
||||
const branchCode = String(
|
||||
getEffectiveBranchCode(ctx, readOperatingBranchCode(req)) || ''
|
||||
).trim();
|
||||
if (!customerCode || !skuCode) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少客户或商品编码' });
|
||||
}
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' });
|
||||
}
|
||||
const { setCustomerSkuSalePrice } = await import('../../../services/customerSkuPriceService');
|
||||
const data = await setCustomerSkuSalePrice({
|
||||
customerCode,
|
||||
skuCode,
|
||||
salePrice: req.body?.sale_price ?? null,
|
||||
branchCode,
|
||||
operatorId: req.userId || null,
|
||||
operatorRole: (ctx?.roles || []).join(',') || null,
|
||||
targetType:
|
||||
req.body?.target_type === 'quote_sheet' || req.body?.target_type === 'customer_sku'
|
||||
? req.body.target_type
|
||||
: null,
|
||||
quoteSheetCode: String(req.body?.quote_sheet_code || '').trim() || null,
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '保存客户销售价失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/customers/geocode-address', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { resolveActiveQuoteSheetForCustomer } from './quoteSheetService';
|
||||
|
||||
export type CustomerSkuPriceTarget = 'quote_sheet' | 'customer_sku';
|
||||
|
||||
function bad(message: string, code = 'invalid_request', status = 400) {
|
||||
return Object.assign(new Error(message), { status, code });
|
||||
}
|
||||
|
||||
function validCode(value: string) {
|
||||
return value.length > 0 && value.length <= 64 && /^[A-Za-z0-9._:-]+$/.test(value);
|
||||
}
|
||||
|
||||
export async function setCustomerSkuSalePrice(input: {
|
||||
customerCode: string;
|
||||
skuCode: string;
|
||||
salePrice: number | null;
|
||||
branchCode: string;
|
||||
operatorId?: string | null;
|
||||
operatorRole?: string | null;
|
||||
/** 前端明确指定写目标;不传则保持旧调用自选(兼容)。 */
|
||||
targetType?: CustomerSkuPriceTarget | null;
|
||||
/** 前端指定报价单时,必须写这张单,避免排行显示 A、实际写 B。 */
|
||||
quoteSheetCode?: string | null;
|
||||
}): Promise<{
|
||||
target: CustomerSkuPriceTarget;
|
||||
sale_price: number;
|
||||
quote_sheet_code?: string;
|
||||
customer_code: string;
|
||||
sku_code: string;
|
||||
unchanged?: boolean;
|
||||
}> {
|
||||
const customerCode = String(input.customerCode || '').trim();
|
||||
const skuCode = String(input.skuCode || '').trim();
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const raw = input.salePrice;
|
||||
if (!customerCode || !skuCode) throw bad('缺少客户或商品编码');
|
||||
if (!branchCode) throw bad('缺少分公司', 'branch_required');
|
||||
if (!validCode(customerCode)) throw bad('客户编码无效');
|
||||
if (!validCode(skuCode)) throw bad('商品编码无效');
|
||||
// 明确只接受正数:0/null 会让报价单行变成 0 价并卡分拣/回写,二期不提供“清空”。
|
||||
if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0) {
|
||||
throw bad('销售价必须是大于 0 的数字', 'invalid_sale_price');
|
||||
}
|
||||
// 报价单/客户商品库价格列是两位小数;按实际落库精度返回,避免“返回 9.999、库里 10.00”的假值。
|
||||
const price = Math.round(raw * 100) / 100;
|
||||
if (!(price > 0)) throw bad('销售价四舍五入后必须大于 0', 'invalid_sale_price');
|
||||
if (price > 99999999.9999) throw bad('销售价超出允许范围', 'invalid_sale_price');
|
||||
|
||||
const customerCheck = await pool.query(
|
||||
`SELECT 1 FROM customers
|
||||
WHERE customer_code = $1 AND branch_code = $2
|
||||
LIMIT 1`,
|
||||
[customerCode, branchCode]
|
||||
);
|
||||
if (!customerCheck.rowCount) {
|
||||
throw bad('客户不存在或不属于当前分公司', 'customer_not_found', 404);
|
||||
}
|
||||
|
||||
const requestedTarget = input.targetType || null;
|
||||
const requestedSheet = String(input.quoteSheetCode || '').trim() || null;
|
||||
if (requestedTarget === 'quote_sheet' && !requestedSheet) {
|
||||
throw bad('缺少报价单编码', 'quote_sheet_required');
|
||||
}
|
||||
if (requestedSheet && requestedTarget !== 'quote_sheet') {
|
||||
throw bad('指定报价单时必须传 target_type=quote_sheet', 'invalid_price_target');
|
||||
}
|
||||
if (requestedTarget === 'customer_sku' && requestedSheet) {
|
||||
throw bad('客户商品库目标不能指定报价单', 'invalid_price_target');
|
||||
}
|
||||
|
||||
const client = await pool.connect();
|
||||
let target: CustomerSkuPriceTarget = 'customer_sku';
|
||||
let quoteSheetCode: string | undefined;
|
||||
let oldSalePrice: number | null = null;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
let sheetCode: string | null = null;
|
||||
if (requestedTarget === 'quote_sheet') {
|
||||
// 必须写前端展示的那张单,且它对本客户仍然生效。
|
||||
const active = await client.query(
|
||||
`SELECT 1
|
||||
FROM customer_quote_sheets qs
|
||||
JOIN customer_quote_sheet_customers qsc
|
||||
ON qsc.quote_sheet_code = qs.quote_sheet_code
|
||||
WHERE qs.quote_sheet_code = $1
|
||||
AND qsc.customer_code = $2
|
||||
AND qs.status = 1
|
||||
AND qs.approval_status = 30
|
||||
AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
|
||||
AND (qs.branch_code IS NULL OR qs.branch_code = $3)
|
||||
LIMIT 1`,
|
||||
[requestedSheet, customerCode, branchCode]
|
||||
);
|
||||
if (!active.rowCount) throw bad('报价单已失效或不属于该客户', 'quote_sheet_changed', 409);
|
||||
const shared = await client.query(
|
||||
`SELECT COUNT(*)::int AS n
|
||||
FROM customer_quote_sheet_customers
|
||||
WHERE quote_sheet_code = $1`,
|
||||
[requestedSheet]
|
||||
);
|
||||
if (Number(shared.rows[0]?.n) > 1) {
|
||||
throw bad(
|
||||
'该报价单绑定多个客户,不能就地改价,避免改动其他客户价格',
|
||||
'quote_sheet_shared_customer',
|
||||
409
|
||||
);
|
||||
}
|
||||
sheetCode = requestedSheet;
|
||||
} else if (requestedTarget !== 'customer_sku') {
|
||||
sheetCode = await resolveActiveQuoteSheetForCustomer(
|
||||
client as unknown as PoolClient,
|
||||
customerCode,
|
||||
branchCode
|
||||
);
|
||||
}
|
||||
|
||||
let wroteQuote = false;
|
||||
if (sheetCode) {
|
||||
const current = await client.query(
|
||||
`SELECT COALESCE(NULLIF(sale_price, 0), NULLIF(price, 0))::float AS current_price
|
||||
FROM customer_quote_sheet_items
|
||||
WHERE quote_sheet_code = $1 AND sku_code = $2
|
||||
FOR UPDATE`,
|
||||
[sheetCode, skuCode]
|
||||
);
|
||||
if (!current.rowCount) {
|
||||
if (requestedTarget === 'quote_sheet') {
|
||||
throw bad('该商品不在指定报价单中', 'quote_sheet_item_missing', 409);
|
||||
}
|
||||
} else {
|
||||
oldSalePrice = Number(current.rows[0]?.current_price) || null;
|
||||
if (oldSalePrice != null && Math.abs(oldSalePrice - price) < 0.005) {
|
||||
await client.query('COMMIT');
|
||||
return {
|
||||
target: 'quote_sheet',
|
||||
sale_price: price,
|
||||
quote_sheet_code: sheetCode,
|
||||
customer_code: customerCode,
|
||||
sku_code: skuCode,
|
||||
unchanged: true,
|
||||
};
|
||||
}
|
||||
const updated = await client.query(
|
||||
`UPDATE customer_quote_sheet_items
|
||||
SET sale_price = $1, price = $1, sale_price_manual = true
|
||||
WHERE quote_sheet_code = $2 AND sku_code = $3`,
|
||||
[price, sheetCode, skuCode]
|
||||
);
|
||||
if (updated.rowCount) {
|
||||
wroteQuote = true;
|
||||
target = 'quote_sheet';
|
||||
quoteSheetCode = sheetCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!wroteQuote) {
|
||||
if (requestedTarget === 'quote_sheet') {
|
||||
throw bad('报价单改价失败', 'quote_sheet_write_failed', 409);
|
||||
}
|
||||
const current = await client.query(
|
||||
`SELECT sale_price::float AS sale_price
|
||||
FROM customer_skus
|
||||
WHERE customer_code = $1 AND sku_code = $2
|
||||
FOR UPDATE`,
|
||||
[customerCode, skuCode]
|
||||
);
|
||||
oldSalePrice = Number(current.rows[0]?.sale_price) || null;
|
||||
if (oldSalePrice != null && Math.abs(oldSalePrice - price) < 0.005) {
|
||||
await client.query('COMMIT');
|
||||
return {
|
||||
target: 'customer_sku',
|
||||
sale_price: price,
|
||||
customer_code: customerCode,
|
||||
sku_code: skuCode,
|
||||
unchanged: true,
|
||||
};
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO customer_skus
|
||||
(customer_code, sku_code, branch_code, sale_price, price_updated_at, price_updated_by)
|
||||
VALUES ($1, $2, $3, $4, NOW(), $5::uuid)
|
||||
ON CONFLICT (customer_code, sku_code) DO UPDATE
|
||||
SET sale_price = EXCLUDED.sale_price,
|
||||
price_updated_at = NOW(),
|
||||
price_updated_by = EXCLUDED.price_updated_by`,
|
||||
[customerCode, skuCode, branchCode, price, input.operatorId || null]
|
||||
);
|
||||
target = 'customer_sku';
|
||||
quoteSheetCode = undefined;
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
|
||||
try {
|
||||
await writeAuditLog({
|
||||
operatorId: input.operatorId || null,
|
||||
operatorRole: input.operatorRole || null,
|
||||
operationType: 'customer_sku_sale_price_update',
|
||||
targetTable: target === 'quote_sheet' ? 'customer_quote_sheet_items' : 'customer_skus',
|
||||
targetId: target === 'quote_sheet' ? `${quoteSheetCode}:${skuCode}` : `${customerCode}:${skuCode}`,
|
||||
oldValue: { sale_price: oldSalePrice },
|
||||
newValue: {
|
||||
customer_code: customerCode,
|
||||
sku_code: skuCode,
|
||||
sale_price: price,
|
||||
target,
|
||||
quote_sheet_code: quoteSheetCode || null,
|
||||
},
|
||||
branchCode,
|
||||
actionCategory: 'pricing',
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('[customer-sku-price] 审计失败', error);
|
||||
}
|
||||
return {
|
||||
target,
|
||||
sale_price: price,
|
||||
...(quoteSheetCode ? { quote_sheet_code: quoteSheetCode } : {}),
|
||||
customer_code: customerCode,
|
||||
sku_code: skuCode,
|
||||
};
|
||||
}
|
||||
@@ -1255,14 +1255,21 @@ export interface SkuDirectCostRow {
|
||||
customer_code: string;
|
||||
sale_price: number;
|
||||
}>;
|
||||
/** 只读:按客户去重后的报价单销售价区间 */
|
||||
/** 只读:按客户去重的价格目标(报价单优先,其次客户商品库) */
|
||||
sale_price_targets?: Array<{
|
||||
target_type: 'quote_sheet' | 'customer_sku';
|
||||
customer_code: string;
|
||||
min: number;
|
||||
max: number;
|
||||
customer_name?: string | null;
|
||||
quote_sheet_code?: string;
|
||||
title?: string | null;
|
||||
sale_price: number;
|
||||
min?: number;
|
||||
max?: number;
|
||||
}>;
|
||||
/** 只读:本行售价来源(有报价单优先) */
|
||||
price_source?: 'quote' | 'order' | null;
|
||||
/** 单客户:当前生效销售价与来源 */
|
||||
sale_price?: number | null;
|
||||
cost_price?: number | null;
|
||||
price_source?: 'quote' | 'customer_sku' | 'order' | null;
|
||||
}
|
||||
|
||||
/** 商品成本排行列表(无分页);默认按毛利率降序 */
|
||||
@@ -1310,8 +1317,21 @@ export async function getSkuDirectCosts(
|
||||
ORDER BY qs.effective_at DESC NULLS LAST, qs.quote_sheet_code`,
|
||||
[skuCodes, customer, branch]
|
||||
);
|
||||
const customerSkuRows = await pool.query(
|
||||
`SELECT cs.customer_code, c.company_name AS customer_name, cs.sku_code,
|
||||
cs.sale_price::float AS sale_price, cs.cost_price::float AS cost_price
|
||||
FROM customer_skus cs
|
||||
LEFT JOIN customers c ON c.customer_code = cs.customer_code
|
||||
WHERE cs.sku_code = ANY($1::text[])
|
||||
AND COALESCE(cs.sale_price, 0) > 0
|
||||
AND ($2::text IS NULL OR cs.customer_code = $2)
|
||||
AND ($3::text IS NULL OR cs.branch_code IS NULL OR cs.branch_code = $3)`,
|
||||
[skuCodes, customer, branch]
|
||||
);
|
||||
type PriceTarget = NonNullable<SkuDirectCostRow['sale_price_targets']>[number];
|
||||
const optionsBySku = new Map<string, NonNullable<SkuDirectCostRow['quote_sheet_options']>>();
|
||||
const targetsBySku = new Map<string, Map<string, { min: number; max: number }>>();
|
||||
const targetsBySku = new Map<string, Map<string, PriceTarget>>();
|
||||
const costBySku = new Map<string, number>();
|
||||
for (const q of quoteRows.rows) {
|
||||
const sku = String(q.sku_code || '').trim();
|
||||
const customerCodeValue = String(q.customer_code || '').trim();
|
||||
@@ -1326,25 +1346,61 @@ export async function getSkuDirectCosts(
|
||||
const options = optionsBySku.get(sku) || [];
|
||||
options.push(option);
|
||||
optionsBySku.set(sku, options);
|
||||
const targets = targetsBySku.get(sku) || new Map<string, { min: number; max: number }>();
|
||||
const prev = targets.get(customerCodeValue);
|
||||
targets.set(customerCodeValue, {
|
||||
min: prev ? Math.min(prev.min, price) : price,
|
||||
max: prev ? Math.max(prev.max, price) : price,
|
||||
});
|
||||
const targets = targetsBySku.get(sku) || new Map<string, PriceTarget>();
|
||||
if (!targets.has(customerCodeValue)) {
|
||||
targets.set(customerCodeValue, {
|
||||
target_type: 'quote_sheet',
|
||||
customer_code: customerCodeValue,
|
||||
quote_sheet_code: String(q.code || ''),
|
||||
title: q.title ? String(q.title) : null,
|
||||
sale_price: price,
|
||||
});
|
||||
}
|
||||
targetsBySku.set(sku, targets);
|
||||
}
|
||||
for (const q of customerSkuRows.rows) {
|
||||
const sku = String(q.sku_code || '').trim();
|
||||
const customerCodeValue = String(q.customer_code || '').trim();
|
||||
const price = Number(q.sale_price);
|
||||
if (!sku || !customerCodeValue || !(price > 0)) continue;
|
||||
const cost = Number(q.cost_price);
|
||||
if (cost > 0 && !costBySku.has(sku)) costBySku.set(sku, cost);
|
||||
const targets = targetsBySku.get(sku) || new Map<string, PriceTarget>();
|
||||
// 同一客户:报价单优先;只有没有报价单时才用 customer_skus。
|
||||
if (!targets.has(customerCodeValue)) {
|
||||
targets.set(customerCodeValue, {
|
||||
target_type: 'customer_sku',
|
||||
customer_code: customerCodeValue,
|
||||
customer_name: q.customer_name ? String(q.customer_name) : null,
|
||||
sale_price: price,
|
||||
});
|
||||
}
|
||||
targetsBySku.set(sku, targets);
|
||||
}
|
||||
for (const row of rows) {
|
||||
const sku = String(row.sku_code || '').trim();
|
||||
const options = optionsBySku.get(sku) || [];
|
||||
const targets = [...(targetsBySku.get(sku)?.entries() || [])].map(([code, range]) => ({
|
||||
customer_code: code,
|
||||
min: range.min,
|
||||
max: range.max,
|
||||
}));
|
||||
const targets = [...(targetsBySku.get(sku)?.values() || [])];
|
||||
row.quote_sheet_options = options;
|
||||
row.sale_price_targets = targets;
|
||||
row.price_source = targets.length ? 'quote' : Number(row.sales_amount) > 0 ? 'order' : null;
|
||||
const selected = customer ? targets.find((target) => target.customer_code === customer) : null;
|
||||
const orderUnitPrice =
|
||||
Number(row.quantity) > 0 && Number(row.sales_amount) > 0
|
||||
? Math.round((Number(row.sales_amount) / Number(row.quantity)) * 100) / 100
|
||||
: null;
|
||||
row.sale_price = selected?.sale_price ?? orderUnitPrice;
|
||||
row.cost_price = costBySku.get(sku) ?? null;
|
||||
row.price_source = selected
|
||||
? selected.target_type === 'quote_sheet'
|
||||
? 'quote'
|
||||
: 'customer_sku'
|
||||
: targets.some((target) => target.target_type === 'quote_sheet')
|
||||
? 'quote'
|
||||
: targets.length
|
||||
? 'customer_sku'
|
||||
: Number(row.sales_amount) > 0
|
||||
? 'order'
|
||||
: null;
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
@@ -139,18 +139,32 @@ export async function resolveSkuPricesForCustomer(
|
||||
),
|
||||
trimmedCustomer
|
||||
? db.query(
|
||||
`SELECT sku_code, price_preference AS price, discount_rate FROM customer_skus
|
||||
WHERE customer_code = $1 AND sku_code = ANY($2)`,
|
||||
`SELECT sku_code, price_preference AS price, discount_rate, sale_price
|
||||
FROM customer_skus
|
||||
WHERE customer_code = $1 AND sku_code = ANY($2)`,
|
||||
[trimmedCustomer, codes]
|
||||
)
|
||||
: Promise.resolve({
|
||||
rows: [] as Array<{ sku_code: string; price: unknown; discount_rate: unknown }>,
|
||||
rows: [] as Array<{
|
||||
sku_code: string;
|
||||
price: unknown;
|
||||
discount_rate: unknown;
|
||||
sale_price: unknown;
|
||||
}>,
|
||||
}),
|
||||
]);
|
||||
|
||||
const quoteMap = firstPriceBySku(quoteResult.rows);
|
||||
const bidMap = firstPriceBySku(bidResult.rows);
|
||||
const preferenceMap = firstPriceBySku(customerSkuResult.rows);
|
||||
const explicitCustomerSkuMap = new Map<string, number>();
|
||||
for (const row of customerSkuResult.rows as Array<{ sku_code: string; sale_price: unknown }>) {
|
||||
const code = String(row.sku_code || '').trim();
|
||||
const sale = Number(row.sale_price) || 0;
|
||||
if (code && sale > 0 && !explicitCustomerSkuMap.has(code)) {
|
||||
explicitCustomerSkuMap.set(code, sale);
|
||||
}
|
||||
}
|
||||
const discountBySku = new Map<string, unknown>();
|
||||
for (const row of customerSkuResult.rows) {
|
||||
const code = String(row.sku_code || '').trim();
|
||||
@@ -159,9 +173,20 @@ export async function resolveSkuPricesForCustomer(
|
||||
|
||||
const result = new Map<string, number>();
|
||||
for (const code of codes) {
|
||||
const base = quoteMap.get(code) ?? bidMap.get(code) ?? preferenceMap.get(code) ?? 0;
|
||||
// 报价单优先(保持既有折扣语义)
|
||||
const quoteBase = quoteMap.get(code) ?? 0;
|
||||
if (quoteBase > 0) {
|
||||
result.set(code, applySaleDiscount(quoteBase, discountBySku.get(code)));
|
||||
continue;
|
||||
}
|
||||
// 客户商品库显式价是约定价:优先于中标/偏好,且不乘折扣。
|
||||
const explicit = explicitCustomerSkuMap.get(code) ?? 0;
|
||||
if (explicit > 0) {
|
||||
result.set(code, explicit);
|
||||
continue;
|
||||
}
|
||||
const base = bidMap.get(code) ?? preferenceMap.get(code) ?? 0;
|
||||
if (!(base > 0)) continue;
|
||||
// 报价/中标/偏好基准价 × 客户商品库折扣率
|
||||
result.set(code, applySaleDiscount(base, discountBySku.get(code)));
|
||||
}
|
||||
return result;
|
||||
@@ -200,6 +225,29 @@ export async function resolveSkuPricesAnyUnitForCustomer(
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 客户商品库显式销售价:sku -> sale_price(>0,不乘折扣) */
|
||||
async function resolveCustomerSkuSalePrices(
|
||||
customerCode: string,
|
||||
skuCodes: string[],
|
||||
db: Db = pool
|
||||
): Promise<Map<string, number>> {
|
||||
const codes = [...new Set(skuCodes.filter(Boolean))];
|
||||
const result = new Map<string, number>();
|
||||
if (!codes.length || !customerCode.trim()) return result;
|
||||
const r = await db.query(
|
||||
`SELECT sku_code, sale_price::float AS sale_price
|
||||
FROM customer_skus
|
||||
WHERE customer_code = $1 AND sku_code = ANY($2) AND COALESCE(sale_price, 0) > 0`,
|
||||
[customerCode.trim(), codes]
|
||||
);
|
||||
for (const row of r.rows) {
|
||||
const code = String(row.sku_code || '').trim();
|
||||
const price = Number(row.sale_price) || 0;
|
||||
if (code && price > 0 && !result.has(code)) result.set(code, price);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 客户执行中报价单:sku -> 销售价(约定执行价,不再乘折扣) */
|
||||
async function resolveActiveQuoteSheetSalePrices(
|
||||
customerCode: string,
|
||||
@@ -256,6 +304,9 @@ export async function resolveSkuSalePriceForUnitChange(
|
||||
const sheetSale = sheetMap.get(code) ?? 0;
|
||||
if (sheetSale > 0) return sheetSale;
|
||||
|
||||
const customerSkuSale = (await resolveCustomerSkuSalePrices(customer, [code], db)).get(code) ?? 0;
|
||||
if (customerSkuSale > 0) return customerSkuSale;
|
||||
|
||||
const byUnit = await resolveSkuPriceForCustomer(customer, code, settlementUnit, db);
|
||||
if (byUnit != null && byUnit > 0) return byUnit;
|
||||
|
||||
@@ -289,8 +340,9 @@ export async function enrichPrefillRowsWithPrices(
|
||||
sku_name: row.sku_name,
|
||||
sku_code: row.sku_code,
|
||||
}));
|
||||
const [sheetSaleMap, lastSalePrices, priceMap] = await Promise.all([
|
||||
const [sheetSaleMap, customerSkuSaleMap, lastSalePrices, priceMap] = await Promise.all([
|
||||
resolveActiveQuoteSheetSalePrices(customerCode, skuCodes, branchCode),
|
||||
resolveCustomerSkuSalePrices(customerCode, skuCodes),
|
||||
resolveLastSalePriceList({ customerCode, branchCode, items: lastSaleItems }),
|
||||
resolveSkuPricesForCustomer(customerCode, skuCodes, pool, false),
|
||||
]);
|
||||
@@ -298,12 +350,15 @@ export async function enrichPrefillRowsWithPrices(
|
||||
const quantity = Math.max(1, Math.round(Number(row.avg_qty) || 1));
|
||||
const lastSale = lastSalePrices[index];
|
||||
const sheetSale = sheetSaleMap.get(row.sku_code) ?? 0;
|
||||
const customerSkuSale = customerSkuSaleMap.get(row.sku_code) ?? 0;
|
||||
const price =
|
||||
sheetSale > 0
|
||||
? sheetSale
|
||||
: lastSale != null && lastSale > 0
|
||||
? lastSale
|
||||
: priceMap.get(row.sku_code) ?? 0;
|
||||
: customerSkuSale > 0
|
||||
? customerSkuSale
|
||||
: lastSale != null && lastSale > 0
|
||||
? lastSale
|
||||
: priceMap.get(row.sku_code) ?? 0;
|
||||
return {
|
||||
...row,
|
||||
quantity,
|
||||
@@ -339,8 +394,9 @@ export async function enrichOrderItemsWithPrices<
|
||||
(item) => !(Number(item.price) > 0) && Boolean(resolveItemDisplayName(item))
|
||||
);
|
||||
|
||||
const [sheetSaleMap, lastSalePrices, priceMap] = await Promise.all([
|
||||
const [sheetSaleMap, customerSkuSaleMap, lastSalePrices, priceMap] = await Promise.all([
|
||||
resolveActiveQuoteSheetSalePrices(customerCode, skuCodes, branchCode),
|
||||
resolveCustomerSkuSalePrices(customerCode, skuCodes),
|
||||
needLastSale
|
||||
? resolveLastSalePriceList({ customerCode, branchCode, items })
|
||||
: Promise.resolve(items.map(() => null as number | null)),
|
||||
@@ -356,9 +412,14 @@ export async function enrichOrderItemsWithPrices<
|
||||
if (!(price > 0)) {
|
||||
const lastSale = lastSalePrices[index];
|
||||
const sheetSale = code ? sheetSaleMap.get(code) ?? 0 : 0;
|
||||
const customerSkuSale = code ? customerSkuSaleMap.get(code) ?? 0 : 0;
|
||||
if (sheetSale > 0) {
|
||||
price = sheetSale;
|
||||
priceSource = 'quote_sheet';
|
||||
} else if (customerSkuSale > 0) {
|
||||
// 客户商品库显式销售价:不乘折扣;优先于最近成交价
|
||||
price = customerSkuSale;
|
||||
priceSource = 'customer_sku';
|
||||
} else if (lastSale != null && lastSale > 0) {
|
||||
// 上次成交价不再乘折扣
|
||||
price = lastSale;
|
||||
|
||||
@@ -84,11 +84,13 @@ async function syncQuoteCostFromPreparation(
|
||||
END,
|
||||
sale_price = CASE
|
||||
WHEN $5::numeric IS NULL THEN sale_price
|
||||
WHEN COALESCE(i.sale_price_manual, false) = true THEN sale_price
|
||||
WHEN $6::boolean AND COALESCE(i.sale_price, 0) <> 0 THEN sale_price
|
||||
ELSE $5::numeric
|
||||
END,
|
||||
price = CASE
|
||||
WHEN $5::numeric IS NULL THEN price
|
||||
WHEN COALESCE(i.sale_price_manual, false) = true THEN price
|
||||
WHEN $6::boolean AND COALESCE(i.sale_price, 0) <> 0 THEN price
|
||||
ELSE $5::numeric
|
||||
END
|
||||
|
||||
@@ -74,7 +74,7 @@ export async function applyQuoteMarkupSalePriceAtSupplyCompletion(
|
||||
if (!quoteSheetCode) continue;
|
||||
|
||||
const quote = await db.query(
|
||||
`SELECT qs.auto_sale_price_by_cost, i.markup_ratio
|
||||
`SELECT qs.auto_sale_price_by_cost, i.markup_ratio, i.sale_price_manual
|
||||
FROM customer_quote_sheets qs
|
||||
JOIN customer_quote_sheet_items i ON i.quote_sheet_code = qs.quote_sheet_code
|
||||
WHERE qs.quote_sheet_code = $1 AND i.sku_code = $2
|
||||
@@ -82,6 +82,8 @@ export async function applyQuoteMarkupSalePriceAtSupplyCompletion(
|
||||
[quoteSheetCode, skuCode]
|
||||
);
|
||||
if (!quote.rows[0]?.auto_sale_price_by_cost || quote.rows[0]?.markup_ratio == null) continue;
|
||||
// 人工改价优先:自动加成不得覆盖 sale_price_manual=true 的报价行。
|
||||
if (quote.rows[0]?.sale_price_manual === true) continue;
|
||||
const markup = Number(quote.rows[0].markup_ratio);
|
||||
if (!Number.isFinite(markup) || markup < 0) continue;
|
||||
const salePrice = Math.round(finalCost * (1 + markup / 100) * 100) / 100;
|
||||
@@ -104,7 +106,7 @@ export async function applyQuoteMarkupSalePriceAtSupplyCompletion(
|
||||
await db.query(
|
||||
`UPDATE customer_quote_sheet_items
|
||||
SET sale_price = $1, price = $1
|
||||
WHERE quote_sheet_code = $2 AND sku_code = $3`,
|
||||
WHERE quote_sheet_code = $2 AND sku_code = $3 AND COALESCE(sale_price_manual, false) = false`,
|
||||
[salePrice, quoteSheetCode, skuCode]
|
||||
);
|
||||
updated += 1;
|
||||
|
||||
@@ -1522,7 +1522,7 @@ export async function approvePriceProposal(input: {
|
||||
// ⭐ T3 唯一写价语句:按 (quote_sheet_code, sku_code) 定点 UPDATE,只改 sale_price/price 两列
|
||||
const updatedRow = await client.query<{ id: string }>(
|
||||
`UPDATE customer_quote_sheet_items
|
||||
SET sale_price = $3, price = $3
|
||||
SET sale_price = $3, price = $3, sale_price_manual = true
|
||||
WHERE quote_sheet_code = $1 AND sku_code = $2
|
||||
RETURNING id::text AS id`,
|
||||
[quoteSheetCode, skuCode, price]
|
||||
|
||||
@@ -741,6 +741,17 @@ export async function applyQuoteSheetUpdate(
|
||||
}
|
||||
|
||||
if (items) {
|
||||
// 报价单编辑是 DELETE+INSERT;必须保留人工改价标记,否则一次编辑就会
|
||||
// 让自动加成/完成回写重新覆盖客户在成本排行里定的价。
|
||||
const manualRows = await client.query<{ sku_code: string; sale_price_manual: boolean }>(
|
||||
`SELECT sku_code, sale_price_manual
|
||||
FROM customer_quote_sheet_items
|
||||
WHERE quote_sheet_code = $1`,
|
||||
[input.quoteSheetCode]
|
||||
);
|
||||
const manualBySku = new Map(
|
||||
manualRows.rows.map((row) => [String(row.sku_code || '').trim(), row.sale_price_manual === true])
|
||||
);
|
||||
await client.query(`DELETE FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [
|
||||
input.quoteSheetCode,
|
||||
]);
|
||||
@@ -748,8 +759,8 @@ export async function applyQuoteSheetUpdate(
|
||||
const item = items[i];
|
||||
await client.query(
|
||||
`INSERT INTO customer_quote_sheet_items
|
||||
(quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, markup_ratio, sort_order)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||
(quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, markup_ratio, sort_order, sale_price_manual)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
||||
[
|
||||
input.quoteSheetCode,
|
||||
item.sku_code.trim(),
|
||||
@@ -760,6 +771,7 @@ export async function applyQuoteSheetUpdate(
|
||||
readSalePrice(item),
|
||||
readMarkupRatio(item),
|
||||
i,
|
||||
manualBySku.get(item.sku_code.trim()) === true,
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -1040,11 +1052,13 @@ export async function upsertCustomerQuoteItemCosts(
|
||||
ELSE i.cost_price
|
||||
END,
|
||||
sale_price = CASE
|
||||
WHEN COALESCE(i.sale_price_manual, false) = true THEN sale_price
|
||||
WHEN $6::boolean = false OR $2::numeric <= 0 THEN sale_price
|
||||
WHEN $7::boolean THEN CASE WHEN COALESCE(sale_price, 0) = 0 THEN $2::numeric ELSE sale_price END
|
||||
ELSE $2::numeric
|
||||
END,
|
||||
price = CASE
|
||||
WHEN COALESCE(i.sale_price_manual, false) = true THEN price
|
||||
WHEN $6::boolean = false OR $2::numeric <= 0 THEN price
|
||||
WHEN $7::boolean THEN CASE WHEN COALESCE(sale_price, 0) = 0 THEN $2::numeric ELSE price END
|
||||
ELSE $2::numeric
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8');
|
||||
const migration = read('../migrations/20261087_customer_sku_price_fields.sql');
|
||||
const svc = read('src/services/customerSkuPriceService.ts');
|
||||
const route = read('src/modules/workflow/routes/customerRoutes.ts');
|
||||
const markup = read('src/services/quoteMarkupSalePriceService.ts');
|
||||
const pricing = read('src/services/orderPricingService.ts');
|
||||
const helpers = readFileSync(new URL('../../src/utils/orderItemHelpers.ts', import.meta.url), 'utf8');
|
||||
const margin = read('src/services/marginQueryService.ts');
|
||||
const page = readFileSync(
|
||||
new URL('../../src/pages/finance/costAccounting/CostAccountingPanel.tsx', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('客户 SKU 销售价二期', () => {
|
||||
it('迁移幂等且覆盖 4 列 + 手工标记,不删旧列', () => {
|
||||
expect(migration).toContain('ADD COLUMN IF NOT EXISTS sale_price NUMERIC(12,4)');
|
||||
expect(migration).toContain('ADD COLUMN IF NOT EXISTS cost_price NUMERIC(12,4)');
|
||||
expect(migration).toContain('ADD COLUMN IF NOT EXISTS price_updated_at TIMESTAMPTZ');
|
||||
expect(migration).toContain('ADD COLUMN IF NOT EXISTS price_updated_by UUID');
|
||||
expect(migration).toContain('ADD COLUMN IF NOT EXISTS sale_price_manual BOOLEAN NOT NULL DEFAULT false');
|
||||
});
|
||||
|
||||
it('接口:报价单优先,否则 customer_skus;审计;不写订单/库存/结算', () => {
|
||||
expect(svc).toContain("target = 'quote_sheet'");
|
||||
expect(svc).toContain('sale_price_manual = true');
|
||||
expect(svc).toContain('INSERT INTO customer_skus');
|
||||
expect(svc).toContain('customer_sku_sale_price_update');
|
||||
expect(svc).not.toMatch(/UPDATE orders|INSERT INTO order_items|inventory|settlement/i);
|
||||
expect(route).toContain("'/customers/:customerCode/sku-sale-price'");
|
||||
expect(route).toContain("['cost_manage', 'finance_manage', 'customer_manage']");
|
||||
});
|
||||
|
||||
it('自动加成跳过人工改价', () => {
|
||||
expect(markup).toContain('i.sale_price_manual');
|
||||
expect(markup).toContain('sale_price_manual === true');
|
||||
expect(markup).toContain('COALESCE(sale_price_manual, false) = false');
|
||||
});
|
||||
|
||||
it('录单取价:报价单 → customer_skus.sale_price → 最近成交;前端 helper 同序', () => {
|
||||
expect(pricing).toContain('resolveCustomerSkuSalePrices');
|
||||
expect(pricing).toContain('customerSkuSale > 0');
|
||||
expect(helpers).toContain("select('sku_code, price_preference, discount_rate, sale_price')");
|
||||
expect(helpers).toContain('customerSkuSaleMap.get(code)');
|
||||
});
|
||||
|
||||
it('排行合并 quote_sheet/customer_sku targets 且不改金额字段', () => {
|
||||
expect(margin).toContain("target_type: 'quote_sheet'");
|
||||
expect(margin).toContain("target_type: 'customer_sku'");
|
||||
expect(margin).toContain("price_source");
|
||||
const attach = margin.slice(margin.indexOf('const rows = paged.data'), margin.indexOf('return rows;', margin.indexOf('const rows = paged.data')));
|
||||
expect(attach).not.toContain('gross_margin =');
|
||||
expect(attach).not.toContain('total_cost =');
|
||||
});
|
||||
|
||||
it('前端单客户铅笔 + 全部客户逐目标输入,无保存按钮', () => {
|
||||
expect(page).toContain('setCustomerSkuSalePriceApi');
|
||||
expect(page).toContain('Pencil');
|
||||
expect(page).toContain("t('finance.cost.rank.editSalePrice')");
|
||||
expect(page).toContain('onBlur={(e) => {');
|
||||
expect(page).not.toContain("t('finance.cost.rank.savePrice')");
|
||||
});
|
||||
});
|
||||
@@ -147,9 +147,15 @@ export const finance: MessageDict = {
|
||||
'cost.rank.sales': 'Sales ¥{amount}',
|
||||
'cost.rank.unitCost': 'Unit cost ¥{amount}',
|
||||
'cost.rank.marginPct': 'Margin {pct}%',
|
||||
'cost.rank.sourceOrderLabel': 'Order',
|
||||
'cost.rank.sourceQuoteLabel': 'Quote',
|
||||
'cost.rank.sourceQuote': 'Quote sale price {price}',
|
||||
'cost.rank.quoteSheets': 'Quote sheets',
|
||||
'cost.rank.sourceCustomerSkuLabel': 'Product library',
|
||||
'cost.rank.priceTargets': 'Price targets',
|
||||
'cost.rank.editSalePrice': 'Edit sale price',
|
||||
'cost.rank.invalidSalePrice': 'Invalid sale price',
|
||||
'cost.rank.savePriceFailed': 'Failed to save sale price',
|
||||
'cost.rank.quoteNearSale': ' (quote cost ≈ sale price)',
|
||||
'cost.rank.quoteNearSaleShort': ' · quote cost ≈ sale price',
|
||||
'cost.rank.skuCode': 'SKU code',
|
||||
|
||||
@@ -147,9 +147,15 @@ export const finance: MessageDict = {
|
||||
'cost.rank.sales': 'Jual ¥{amount}',
|
||||
'cost.rank.unitCost': 'Biaya satuan ¥{amount}',
|
||||
'cost.rank.marginPct': 'Margin {pct}%',
|
||||
'cost.rank.sourceOrderLabel': 'Pesanan',
|
||||
'cost.rank.sourceQuoteLabel': 'Penawaran',
|
||||
'cost.rank.sourceQuote': 'Harga jual penawaran {price}',
|
||||
'cost.rank.quoteSheets': 'Lembar penawaran',
|
||||
'cost.rank.sourceCustomerSkuLabel': 'Katalog produk',
|
||||
'cost.rank.priceTargets': 'Target harga',
|
||||
'cost.rank.editSalePrice': 'Ubah harga jual',
|
||||
'cost.rank.invalidSalePrice': 'Harga jual tidak valid',
|
||||
'cost.rank.savePriceFailed': 'Gagal menyimpan harga jual',
|
||||
'cost.rank.quoteNearSale': ' (biaya kuota ≈ harga jual)',
|
||||
'cost.rank.quoteNearSaleShort': ' · biaya kuota ≈ harga jual',
|
||||
'cost.rank.skuCode': 'Kode SKU',
|
||||
|
||||
@@ -147,9 +147,15 @@ export const finance: MessageDict = {
|
||||
'cost.rank.sales': '销售 ¥{amount}',
|
||||
'cost.rank.unitCost': '单位成本 ¥{amount}',
|
||||
'cost.rank.marginPct': '毛利率 {pct}%',
|
||||
'cost.rank.sourceOrderLabel': '订单',
|
||||
'cost.rank.sourceQuoteLabel': '报价单',
|
||||
'cost.rank.sourceQuote': '报价单 销售价 {price}',
|
||||
'cost.rank.quoteSheets': '报价单',
|
||||
'cost.rank.sourceCustomerSkuLabel': '商品库',
|
||||
'cost.rank.priceTargets': '价格目标',
|
||||
'cost.rank.editSalePrice': '修改销售价',
|
||||
'cost.rank.invalidSalePrice': '销售价无效',
|
||||
'cost.rank.savePriceFailed': '保存销售价失败',
|
||||
'cost.rank.quoteNearSale': '(报价成本≈售价)',
|
||||
'cost.rank.quoteNearSaleShort': ' · 报价成本≈售价',
|
||||
'cost.rank.skuCode': '商品编码',
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
Upload,
|
||||
Loader2,
|
||||
Unlink,
|
||||
Pencil,
|
||||
} from 'lucide-react';
|
||||
import { notify } from '../../../utils/notify';
|
||||
import { supabase } from '../../../supabase/client';
|
||||
@@ -61,6 +62,7 @@ import {
|
||||
getMarginSummaryApi,
|
||||
getMarginRowsApi,
|
||||
getSkuDirectCostsApi,
|
||||
setCustomerSkuSalePriceApi,
|
||||
getSkuDirectCostsPagedApi,
|
||||
listOrderCostDetailsInWindowApi,
|
||||
extractFreeCostPaymentVouchersApi,
|
||||
@@ -1059,6 +1061,64 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
|
||||
/** 成本明细 Tab:按成本构成桶筛选(总览下钻) */
|
||||
const [recordsCostBucket, setRecordsCostBucket] = useState<string | null>(null);
|
||||
const [skuCostDetails, setSkuCostDetails] = useState<SkuCostDetail[]>([]);
|
||||
const [skuPriceEditKey, setSkuPriceEditKey] = useState<string | null>(null);
|
||||
const [skuPriceDraft, setSkuPriceDraft] = useState('');
|
||||
const [skuPriceSavingKey, setSkuPriceSavingKey] = useState<string | null>(null);
|
||||
const saveSkuPrice = async (
|
||||
customerCode: string,
|
||||
skuCode: string,
|
||||
raw: string,
|
||||
targetType?: 'quote_sheet' | 'customer_sku',
|
||||
quoteSheetCode?: string | null
|
||||
) => {
|
||||
const key = `${skuCode}:${customerCode}`;
|
||||
const value = Number(raw);
|
||||
if (raw.trim() === '' || !Number.isFinite(value) || value <= 0) {
|
||||
notify.error(t('finance.cost.rank.invalidSalePrice'));
|
||||
return false;
|
||||
}
|
||||
setSkuPriceSavingKey(key);
|
||||
try {
|
||||
const { data } = await setCustomerSkuSalePriceApi({
|
||||
customerCode,
|
||||
sku_code: skuCode,
|
||||
sale_price: value,
|
||||
target_type: targetType,
|
||||
quote_sheet_code: quoteSheetCode || undefined,
|
||||
});
|
||||
setSkuCostDetails((rows) =>
|
||||
rows.map((row) => {
|
||||
if (row.sku_code !== skuCode) return row;
|
||||
const targets = (row.sale_price_targets || []).map((target) =>
|
||||
target.customer_code === customerCode
|
||||
? { ...target, sale_price: Number(data?.sale_price) || 0 }
|
||||
: target
|
||||
);
|
||||
return {
|
||||
...row,
|
||||
sale_price:
|
||||
customerFilter === customerCode
|
||||
? Number(data?.sale_price) || 0
|
||||
: row.sale_price,
|
||||
sale_price_targets: targets,
|
||||
price_source:
|
||||
customerFilter === customerCode
|
||||
? data?.target === 'quote_sheet'
|
||||
? 'quote'
|
||||
: 'customer_sku'
|
||||
: row.price_source,
|
||||
};
|
||||
})
|
||||
);
|
||||
setSkuPriceEditKey(null);
|
||||
return true;
|
||||
} catch (error) {
|
||||
notify.error(error instanceof Error ? error.message : t('finance.cost.rank.savePriceFailed'));
|
||||
return false;
|
||||
} finally {
|
||||
setSkuPriceSavingKey(null);
|
||||
}
|
||||
};
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [defaultRange] = useState(() => initialFinanceDateRangeFromUrl(searchParams));
|
||||
const [dateFrom, setDateFrom] = useState(defaultRange.date_from);
|
||||
@@ -1871,9 +1931,19 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
|
||||
sale_price_targets: Array.isArray(row.sale_price_targets)
|
||||
? (row.sale_price_targets as SkuCostDetail['sale_price_targets'])
|
||||
: [],
|
||||
sale_price:
|
||||
row.sale_price == null || row.sale_price === ''
|
||||
? null
|
||||
: safeAmount(row.sale_price, 0),
|
||||
cost_price:
|
||||
row.cost_price == null || row.cost_price === ''
|
||||
? null
|
||||
: safeAmount(row.cost_price, 0),
|
||||
price_source:
|
||||
row.price_source === 'quote' || row.price_source === 'order'
|
||||
? (row.price_source as 'quote' | 'order')
|
||||
row.price_source === 'quote' ||
|
||||
row.price_source === 'customer_sku' ||
|
||||
row.price_source === 'order'
|
||||
? (row.price_source as 'quote' | 'customer_sku' | 'order')
|
||||
: null,
|
||||
};
|
||||
});
|
||||
@@ -2702,18 +2772,33 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
|
||||
Math.abs(sku.gross_margin) < 0.05 &&
|
||||
sku.sales_amount > 0 &&
|
||||
Math.abs(sku.sales_amount - sku.total_cost) < 0.02;
|
||||
const targetPrices = (sku.sale_price_targets || []).flatMap((target) => [
|
||||
Number(target.min) || 0,
|
||||
Number(target.max) || 0,
|
||||
]).filter((price) => price > 0);
|
||||
const allPriceTargets = sku.sale_price_targets || [];
|
||||
const quoteTargets = allPriceTargets.filter(
|
||||
(target) => target.target_type === 'quote_sheet'
|
||||
);
|
||||
const skuPriceTargets = allPriceTargets.filter(
|
||||
(target) => target.target_type === 'customer_sku'
|
||||
);
|
||||
const rangeTargets = allPriceTargets;
|
||||
const targetPrices = rangeTargets
|
||||
.map((target) => Number(target.sale_price) || 0)
|
||||
.filter((price) => price > 0);
|
||||
const quoteMin = targetPrices.length ? Math.min(...targetPrices) : 0;
|
||||
const quoteMax = targetPrices.length ? Math.max(...targetPrices) : 0;
|
||||
const quoteRange =
|
||||
quoteMin > 0
|
||||
? Math.abs(quoteMax - quoteMin) < 0.005
|
||||
? `¥${quoteMin.toFixed(2)}`
|
||||
: `¥${quoteMin.toFixed(2)}~¥${quoteMax.toFixed(2)}`
|
||||
: '';
|
||||
const rangeLabel = (min: number, max: number) =>
|
||||
Math.abs(max - min) < 0.005
|
||||
? `¥${min.toFixed(2)}`
|
||||
: `¥${min.toFixed(2)}~¥${max.toFixed(2)}`;
|
||||
const quoteRange = quoteMin > 0 ? rangeLabel(quoteMin, quoteMax) : '';
|
||||
const rangeSource = quoteTargets.length
|
||||
? 'quote'
|
||||
: skuPriceTargets.length
|
||||
? 'customer_sku'
|
||||
: null;
|
||||
const singleOrderPrice =
|
||||
customerFilter && Number(sku.sale_price) > 0
|
||||
? Number(sku.sale_price)
|
||||
: 0;
|
||||
const rowExpanded = expandedSkuCode === sku.sku_code;
|
||||
return (
|
||||
<div
|
||||
@@ -2747,12 +2832,93 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
|
||||
</span>
|
||||
</div>
|
||||
<div className="app-foreground-muted flex flex-wrap items-center gap-x-4 gap-y-1 text-xs mt-1">
|
||||
{quoteRange ? (
|
||||
{quoteRange || singleOrderPrice > 0 || Boolean(customerFilter) ? (
|
||||
<>
|
||||
<span className="app-foreground-muted text-[10px] leading-none">
|
||||
{t('finance.cost.rank.sourceQuoteLabel')}
|
||||
{t(
|
||||
quoteRange
|
||||
? rangeSource === 'quote'
|
||||
? 'finance.cost.rank.sourceQuoteLabel'
|
||||
: 'finance.cost.rank.sourceCustomerSkuLabel'
|
||||
: 'finance.cost.rank.sourceOrderLabel'
|
||||
)}
|
||||
</span>
|
||||
<span>{t('finance.cost.col.salePrice')} {quoteRange}</span>
|
||||
<span>
|
||||
{t('finance.cost.col.salePrice')}{' '}
|
||||
{quoteRange ||
|
||||
(singleOrderPrice > 0
|
||||
? `¥${singleOrderPrice.toFixed(2)}`
|
||||
: '—')}
|
||||
</span>
|
||||
{!customerFilter ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('finance.cost.rank.editSalePrice')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setExpandedSkuCode((cur) => (cur === sku.sku_code ? null : sku.sku_code));
|
||||
}}
|
||||
className="p-0.5 text-gray-400 hover:text-gray-700"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
</button>
|
||||
) : null}
|
||||
{customerFilter ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('finance.cost.rank.editSalePrice')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setSkuPriceEditKey(`${sku.sku_code}:${customerFilter}`);
|
||||
setSkuPriceDraft(String(sku.sale_price ?? quoteMin));
|
||||
}}
|
||||
className="p-0.5 text-gray-400 hover:text-gray-700"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
</button>
|
||||
{skuPriceEditKey === `${sku.sku_code}:${customerFilter}` ? (
|
||||
<input
|
||||
autoFocus
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={skuPriceDraft}
|
||||
disabled={skuPriceSavingKey === `${sku.sku_code}:${customerFilter}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onChange={(e) => setSkuPriceDraft(e.target.value)}
|
||||
onBlur={() => {
|
||||
const old = Number(sku.sale_price ?? quoteMin);
|
||||
const next = Number(skuPriceDraft);
|
||||
if (skuPriceDraft.trim() === '' || next === old) {
|
||||
setSkuPriceEditKey(null);
|
||||
setSkuPriceDraft('');
|
||||
return;
|
||||
}
|
||||
const target = allPriceTargets.find(
|
||||
(item) => item.customer_code === customerFilter
|
||||
);
|
||||
void saveSkuPrice(
|
||||
customerFilter,
|
||||
sku.sku_code,
|
||||
skuPriceDraft,
|
||||
target?.target_type ?? 'customer_sku',
|
||||
target?.quote_sheet_code
|
||||
).then((ok) => {
|
||||
if (!ok) setSkuPriceDraft(String(old));
|
||||
});
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
else if (e.key === 'Escape') {
|
||||
setSkuPriceEditKey(null);
|
||||
setSkuPriceDraft('');
|
||||
}
|
||||
}}
|
||||
className="w-20 px-1 py-0.5 text-xs border rounded"
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
<span>· {t('finance.cost.rank.unitCost', { amount: rankUnitCost.toFixed(2) })}</span>
|
||||
</>
|
||||
) : (
|
||||
@@ -2799,12 +2965,53 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
|
||||
<p className="app-foreground-muted">{t('finance.cost.rank.directTotal')}</p>
|
||||
<p className="app-foreground font-medium">¥{sku.total_cost.toLocaleString()}</p>
|
||||
</div>
|
||||
{sku.quote_sheet_options?.length ? (
|
||||
{(sku.sale_price_targets?.length ?? 0) > 0 ? (
|
||||
<div className="col-span-2 sm:col-span-3">
|
||||
<p className="app-foreground-muted">{t('finance.cost.rank.quoteSheets')}</p>
|
||||
<p className="app-foreground font-medium break-all">
|
||||
{sku.quote_sheet_options.map((q) => q.title || q.code).join('、')}
|
||||
</p>
|
||||
<p className="app-foreground-muted">{t('finance.cost.rank.priceTargets')}</p>
|
||||
<div className="mt-1 space-y-1">
|
||||
{sku.sale_price_targets!.map((target) => {
|
||||
const key = `${sku.sku_code}:${target.customer_code}`;
|
||||
return (
|
||||
<div key={`${key}:${target.target_type}`} className="flex items-center gap-2">
|
||||
<span className="app-foreground min-w-0 flex-1 truncate">
|
||||
{target.customer_name || target.customer_code}
|
||||
{target.target_type === 'quote_sheet'
|
||||
? ` · ${target.title || target.quote_sheet_code || t('finance.cost.rank.sourceQuoteLabel')}`
|
||||
: ` · ${t('finance.cost.rank.sourceCustomerSkuLabel')}`}
|
||||
</span>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
defaultValue={Number(target.sale_price).toFixed(2)}
|
||||
disabled={skuPriceSavingKey === key}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
const input = e.currentTarget;
|
||||
const old = Number(target.sale_price);
|
||||
const next = Number(input.value);
|
||||
if (input.value.trim() === '' || next === old) {
|
||||
input.value = old.toFixed(2);
|
||||
return;
|
||||
}
|
||||
void saveSkuPrice(
|
||||
target.customer_code,
|
||||
sku.sku_code,
|
||||
input.value,
|
||||
target.target_type,
|
||||
target.quote_sheet_code
|
||||
).then((ok) => {
|
||||
if (!ok) input.value = old.toFixed(2);
|
||||
});
|
||||
}}
|
||||
className="w-24 px-1 py-0.5 text-xs border rounded"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<div>
|
||||
|
||||
@@ -136,8 +136,19 @@ export interface SkuCostDetail {
|
||||
customer_code: string;
|
||||
sale_price: number;
|
||||
}>;
|
||||
sale_price_targets?: Array<{ customer_code: string; min: number; max: number }>;
|
||||
price_source?: 'quote' | 'order' | null;
|
||||
sale_price_targets?: Array<{
|
||||
target_type: 'quote_sheet' | 'customer_sku';
|
||||
customer_code: string;
|
||||
customer_name?: string | null;
|
||||
quote_sheet_code?: string;
|
||||
title?: string | null;
|
||||
sale_price: number;
|
||||
min?: number;
|
||||
max?: number;
|
||||
}>;
|
||||
sale_price?: number | null;
|
||||
cost_price?: number | null;
|
||||
price_source?: 'quote' | 'customer_sku' | 'order' | null;
|
||||
}
|
||||
|
||||
export type CostDayGroup = {
|
||||
|
||||
@@ -102,12 +102,10 @@ export async function fillBidPrices<
|
||||
}
|
||||
}
|
||||
|
||||
// 客户商品库显式价(sale_price)必须参与判断,但它只能在本段之后异步查回;
|
||||
// 因此先把所有“缺价且带 SKU”的行纳入查询,再在下面按 报价单 > 客户商品库 > 最近成交价 取价。
|
||||
const stillNeedSku = items.filter(
|
||||
(item, index) =>
|
||||
!(Number(item.price) > 0) &&
|
||||
!(lastSalePrices[index] != null && (lastSalePrices[index] as number) > 0) &&
|
||||
!(item.skuCode && sheetSaleOf(item.skuCode) > 0) &&
|
||||
Boolean(item.skuCode)
|
||||
(item) => !(Number(item.price) > 0) && Boolean(item.skuCode)
|
||||
);
|
||||
const codes = [...new Set(stillNeedSku.map((item) => item.skuCode).filter(Boolean))];
|
||||
|
||||
@@ -125,7 +123,7 @@ export async function fillBidPrices<
|
||||
needPreference
|
||||
? supabase
|
||||
.from('customer_skus')
|
||||
.select('sku_code, price_preference, discount_rate')
|
||||
.select('sku_code, price_preference, discount_rate, sale_price')
|
||||
.eq('customer_code', customerCode)
|
||||
.in('sku_code', codes)
|
||||
: Promise.resolve({
|
||||
@@ -133,6 +131,7 @@ export async function fillBidPrices<
|
||||
sku_code: string;
|
||||
price_preference: unknown;
|
||||
discount_rate: unknown;
|
||||
sale_price: unknown;
|
||||
}>,
|
||||
error: null,
|
||||
}),
|
||||
@@ -146,6 +145,10 @@ export async function fillBidPrices<
|
||||
customerSkuResult.data as Array<{ sku_code: string; price_preference: unknown }> | null,
|
||||
(row) => Number(row.price_preference) || 0
|
||||
);
|
||||
const customerSkuSaleMap: Map<string, number> = firstPriceBySku(
|
||||
customerSkuResult.data as Array<{ sku_code: string; sale_price: unknown }> | null,
|
||||
(row) => Number(row.sale_price) || 0
|
||||
);
|
||||
const discountBySku = new Map<string, unknown>();
|
||||
for (const row of (customerSkuResult.data || []) as Array<{
|
||||
sku_code: string;
|
||||
@@ -163,6 +166,9 @@ export async function fillBidPrices<
|
||||
if (code && sheetSaleOf(code) > 0) {
|
||||
// 报价单售价为约定执行价,不再叠加折扣
|
||||
price = sheetSaleOf(code);
|
||||
} else if (code && (customerSkuSaleMap.get(code) ?? 0) > 0) {
|
||||
// 客户商品库显式价:不乘折扣
|
||||
price = customerSkuSaleMap.get(code) as number;
|
||||
} else if (lastSale != null && lastSale > 0) {
|
||||
price = lastSale;
|
||||
} else if (code) {
|
||||
|
||||
@@ -6588,6 +6588,33 @@ export async function applyInventoryOffsetApi(orderCode: string) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function setCustomerSkuSalePriceApi(input: {
|
||||
customerCode: string;
|
||||
sku_code: string;
|
||||
sale_price: number | null;
|
||||
target_type?: 'quote_sheet' | 'customer_sku';
|
||||
quote_sheet_code?: string;
|
||||
}) {
|
||||
return workflowFetch<{
|
||||
data: {
|
||||
target: 'quote_sheet' | 'customer_sku';
|
||||
sale_price: number;
|
||||
quote_sheet_code?: string;
|
||||
customer_code: string;
|
||||
sku_code: string;
|
||||
};
|
||||
}>(`/customers/${encodeURIComponent(input.customerCode)}/sku-sale-price`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
sku_code: input.sku_code,
|
||||
sale_price: input.sale_price,
|
||||
// 必须透传:共享报价单/多活跃报价单时服务端据此校验并写指定单。
|
||||
target_type: input.target_type,
|
||||
quote_sheet_code: input.quote_sheet_code,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 主系统商品名对不上导致抵扣扣不上(2026-10-12):候选「**有可扣库存**」的 SKU(同分公司)。
|
||||
* 设计:docs/design/20261104-主系统商品名映射与手动选抵扣库存.md
|
||||
|
||||
Reference in New Issue
Block a user