feat(成本排行): 一期接入执行中报价单来源与销售价区间
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

只读:全部客户显示报价单销售价区间,单客户显示报价价;行单击展开;黑字统一;不改金额/毛利率/订单,无迁移和写接口。
This commit is contained in:
Ubuntu
2026-10-27 17:51:23 +08:00
parent f524e6b6db
commit b8a7837027
7 changed files with 171 additions and 41 deletions
+73 -1
View File
@@ -1248,6 +1248,21 @@ export interface SkuDirectCostRow {
gross_profit: number;
gross_margin: number;
sales_amount: number;
/** 只读:执行中报价单可选价(按 SKU) */
quote_sheet_options?: Array<{
code: string;
title: string | null;
customer_code: string;
sale_price: number;
}>;
/** 只读:按客户去重后的报价单销售价区间 */
sale_price_targets?: Array<{
customer_code: string;
min: number;
max: number;
}>;
/** 只读:本行售价来源(有报价单优先) */
price_source?: 'quote' | 'order' | null;
}
/** 商品成本排行列表(无分页);默认按毛利率降序 */
@@ -1274,7 +1289,64 @@ export async function getSkuDirectCosts(
null,
customerCode
);
return paged.data;
const rows = paged.data;
if (!rows.length) return rows;
const skuCodes = [...new Set(rows.map((row) => String(row.sku_code || '').trim()).filter(Boolean))];
if (!skuCodes.length) return rows;
const customer = customerCode ? String(customerCode).trim() : null;
const branch = ctx?.branchCode ? String(ctx.branchCode).trim() : null;
const quoteRows = await pool.query(
`SELECT qs.quote_sheet_code AS code, qs.title, qsc.customer_code, qsi.sku_code,
COALESCE(NULLIF(qsi.sale_price, 0), qsi.price)::float AS sale_price
FROM customer_quote_sheets qs
JOIN customer_quote_sheet_customers qsc ON qsc.quote_sheet_code = qs.quote_sheet_code
JOIN customer_quote_sheet_items qsi ON qsi.quote_sheet_code = qs.quote_sheet_code
WHERE qs.status = 1 AND qs.approval_status = 30
AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
AND qsi.sku_code = ANY($1::text[])
AND COALESCE(NULLIF(qsi.sale_price, 0), qsi.price) > 0
AND ($2::text IS NULL OR qsc.customer_code = $2)
AND ($3::text IS NULL OR qs.branch_code IS NULL OR qs.branch_code = $3)
ORDER BY qs.effective_at DESC NULLS LAST, qs.quote_sheet_code`,
[skuCodes, customer, branch]
);
const optionsBySku = new Map<string, NonNullable<SkuDirectCostRow['quote_sheet_options']>>();
const targetsBySku = new Map<string, Map<string, { min: number; max: number }>>();
for (const q of quoteRows.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 option = {
code: String(q.code || ''),
title: q.title ? String(q.title) : null,
customer_code: customerCodeValue,
sale_price: price,
};
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,
});
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,
}));
row.quote_sheet_options = options;
row.sale_price_targets = targets;
row.price_source = targets.length ? 'quote' : Number(row.sales_amount) > 0 ? 'order' : null;
}
return rows;
}
/**
@@ -0,0 +1,37 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const margin = readFileSync(new URL('../src/services/marginQueryService.ts', import.meta.url), 'utf8');
const page = readFileSync(
new URL('../../src/pages/finance/costAccounting/CostAccountingPanel.tsx', import.meta.url),
'utf8'
);
const types = readFileSync(
new URL('../../src/pages/finance/costAccounting/types.ts', import.meta.url),
'utf8'
);
describe('成本排行只读报价单展示', () => {
it('后端只在 getSkuDirectCosts 追加字段,条件用生效报价单/绑定客户/正价', () => {
expect(margin).toContain('quote_sheet_options');
expect(margin).toContain('sale_price_targets');
expect(margin).toContain('price_source');
expect(margin).toContain('qs.status = 1 AND qs.approval_status = 30');
expect(margin).toContain('qs.expires_at IS NULL OR qs.expires_at > NOW()');
expect(margin).toContain('customer_quote_sheet_customers');
expect(margin).toContain('COALESCE(NULLIF(qsi.sale_price, 0), qsi.price) > 0');
});
it('前端类型/区间/单客户文案/单击展开/毛利率只一处', () => {
expect(types).toContain('quote_sheet_options');
expect(types).toContain('sale_price_targets');
expect(page).toContain('quoteMin');
expect(page).toContain('quoteMax');
expect(page).toContain("t('finance.cost.rank.sourceQuote'");
expect(page).toContain("target.closest('input, button, a, label')");
expect(page).toContain("setExpandedSkuCode((cur) => (cur === sku.sku_code ? null : sku.sku_code))");
expect(page).not.toContain("t('finance.cost.rank.grossAmt')\n }`}");
// 毛利率只保留内联一处(不再渲染右上角与展开区)
expect((page.match(/t\('finance\.cost\.rank\.marginPct'/g) || []).length).toBe(1);
});
});
+3 -1
View File
@@ -141,12 +141,14 @@ export const finance: MessageDict = {
'cost.rank.sortLow': 'Low to high',
'cost.rank.collapse': 'Collapse',
'cost.rank.expand': 'Expand',
'cost.rank.rowTitle': 'Double-click to toggle product details',
'cost.rank.rowTitle': 'Click to toggle product details',
'cost.rank.cardTitle': 'Double-click to toggle full ranking',
'cost.rank.purchase': 'Cost ¥{amount}',
'cost.rank.sales': 'Sales ¥{amount}',
'cost.rank.unitCost': 'Unit cost ¥{amount}',
'cost.rank.marginPct': 'Margin {pct}%',
'cost.rank.sourceQuote': 'Quote sale price {price}',
'cost.rank.quoteSheets': 'Quote sheets',
'cost.rank.quoteNearSale': ' (quote cost ≈ sale price)',
'cost.rank.quoteNearSaleShort': ' · quote cost ≈ sale price',
'cost.rank.skuCode': 'SKU code',
+3 -1
View File
@@ -141,12 +141,14 @@ export const finance: MessageDict = {
'cost.rank.sortLow': 'Rendah ke tinggi',
'cost.rank.collapse': 'Tutup',
'cost.rank.expand': 'Perluas',
'cost.rank.rowTitle': 'Klik ganda untuk rincian produk',
'cost.rank.rowTitle': 'Klik untuk rincian produk',
'cost.rank.cardTitle': 'Klik ganda untuk ranking penuh',
'cost.rank.purchase': 'Biaya ¥{amount}',
'cost.rank.sales': 'Jual ¥{amount}',
'cost.rank.unitCost': 'Biaya satuan ¥{amount}',
'cost.rank.marginPct': 'Margin {pct}%',
'cost.rank.sourceQuote': 'Harga jual penawaran {price}',
'cost.rank.quoteSheets': 'Lembar penawaran',
'cost.rank.quoteNearSale': ' (biaya kuota ≈ harga jual)',
'cost.rank.quoteNearSaleShort': ' · biaya kuota ≈ harga jual',
'cost.rank.skuCode': 'Kode SKU',
+3 -1
View File
@@ -141,12 +141,14 @@ export const finance: MessageDict = {
'cost.rank.sortLow': '从低到高',
'cost.rank.collapse': '收起',
'cost.rank.expand': '展开',
'cost.rank.rowTitle': '双击展开或收起该商品明细',
'cost.rank.rowTitle': '点击展开或收起该商品明细',
'cost.rank.cardTitle': '双击展开或收起完整排行',
'cost.rank.purchase': '成本 ¥{amount}',
'cost.rank.sales': '销售 ¥{amount}',
'cost.rank.unitCost': '单位成本 ¥{amount}',
'cost.rank.marginPct': '毛利率 {pct}%',
'cost.rank.sourceQuote': '报价单 销售价 {price}',
'cost.rank.quoteSheets': '报价单',
'cost.rank.quoteNearSale': '(报价成本≈售价)',
'cost.rank.quoteNearSaleShort': ' · 报价成本≈售价',
'cost.rank.skuCode': '商品编码',
@@ -1865,6 +1865,16 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
gross_profit: safeAmount(row.gross_profit, 0),
gross_margin: safeAmount(row.gross_margin, 0),
sales_amount: safeAmount(row.sales_amount, 0),
quote_sheet_options: Array.isArray(row.quote_sheet_options)
? (row.quote_sheet_options as SkuCostDetail['quote_sheet_options'])
: [],
sale_price_targets: Array.isArray(row.sale_price_targets)
? (row.sale_price_targets as SkuCostDetail['sale_price_targets'])
: [],
price_source:
row.price_source === 'quote' || row.price_source === 'order'
? (row.price_source as 'quote' | 'order')
: null,
};
});
@@ -2692,13 +2702,19 @@ 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 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 rowExpanded = expandedSkuCode === sku.sku_code;
const marginTone =
rankMarginPct < -5
? 'text-red-600'
: rankMarginPct > 5
? 'text-emerald-700'
: 'app-foreground';
return (
<div
key={`${sku.sku_code}-${sku.is_extra_dish ? 'extra' : 'base'}-${sku.purchase_self_cost > 0 ? 'self' : 'sup'}`}
@@ -2709,8 +2725,9 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
: 'border-transparent hover:border-gray-200 hover:bg-gray-50/70'
}`}
title={t('finance.cost.rank.rowTitle')}
onDoubleClick={(e) => {
e.stopPropagation();
onClick={(e) => {
const target = e.target as HTMLElement;
if (target.closest('input, button, a, label')) return;
setExpandedSkuCode((cur) => (cur === sku.sku_code ? null : sku.sku_code));
}}
>
@@ -2728,23 +2745,20 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
isIndependentSelfPurchase={sku.is_independent_self_purchase}
/>
</span>
<span className={`text-sm font-bold shrink-0 ${marginTone}`}>
{sku.sales_amount > 0 ? `${rankMarginPct.toFixed(1)}%` : '—'}
</span>
</div>
<div className="app-foreground-muted flex flex-wrap items-center gap-x-4 gap-y-1 text-xs mt-1">
<span>{t('finance.cost.rank.purchase', { amount: rankPurchaseAmount.toLocaleString() })}</span>
<span>{t('finance.cost.rank.sales', { amount: sku.sales_amount.toLocaleString() })}</span>
{quoteRange ? (
<span className="app-foreground">
{t('finance.cost.rank.sourceQuote', { price: quoteRange })}
</span>
) : (
<>
<span>{t('finance.cost.rank.purchase', { amount: rankPurchaseAmount.toLocaleString() })}</span>
<span>{t('finance.cost.rank.sales', { amount: sku.sales_amount.toLocaleString() })}</span>
</>
)}
<span>{t('finance.cost.rank.unitCost', { amount: rankUnitCost.toFixed(2) })}</span>
<span
className={
rankMarginPct < -5
? 'text-red-600 font-medium'
: rankMarginPct > 5
? 'text-emerald-700 font-medium'
: 'app-foreground'
}
>
<span className="app-foreground font-medium">
{t('finance.cost.rank.marginPct', { pct: rankMarginPct.toFixed(1) })}
{marginApproxZero ? t('finance.cost.rank.quoteNearSale') : ''}
</span>
@@ -2781,6 +2795,14 @@ 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 ? (
<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>
</div>
) : null}
<div>
<p className="app-foreground-muted">{t('finance.cost.rank.grossAmt')}</p>
<p
@@ -2791,21 +2813,6 @@ export const CostAccountingPanel: React.FC<CostAccountingPanelProps> = ({
¥{sku.gross_profit.toLocaleString()}
</p>
</div>
<div>
<p className="app-foreground-muted">{t('finance.cost.col.grossMarginPct')}</p>
<p
className={`font-medium ${
sku.gross_margin < -0.05
? 'text-red-600'
: sku.gross_margin > 0.05
? 'text-emerald-700'
: 'app-foreground'
}`}
>
{sku.gross_margin.toFixed(1)}%
{marginApproxZero ? t('finance.cost.rank.quoteNearSaleShort') : ''}
</p>
</div>
</div>
) : null}
</div>
@@ -130,6 +130,14 @@ export interface SkuCostDetail {
gross_profit: number;
gross_margin: number;
sales_amount: number;
quote_sheet_options?: Array<{
code: string;
title: string | null;
customer_code: string;
sale_price: number;
}>;
sale_price_targets?: Array<{ customer_code: string; min: number; max: number }>;
price_source?: 'quote' | 'order' | null;
}
export type CostDayGroup = {