Files
SupplierSystem/src/utils/exportDataBuilders.ts
T
Ubuntu bf94aa0a1f
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
feat(订单成本口径): C 块 —— 供应商第三个分类「库存抵扣」(写入点+8处归零+第三张表+全域非厂商守卫)
开发者 2026-10-14:「开始做 C 块;文案你自己编写;布局自行调整」,并确认
「独立进货就是一个客户、这个客户就是他自己、相当于补充库存」、
「订单管理列表就可以不用隐藏独立进货单了」(后者本轮未动)。
设计文 docs/design/20261014-订单成本排除独立进货与库存成本分类.md §6.1(本轮新增)。

## 取值与写入
- 新增 `STOCK_COVER_SUPPLIER_CODE='STOCK_COVER'` / 名称「库存抵扣」(服务端 + 前端 allocationRules 同名常量)。
- `applyStockCoverForOrderItem`(唯一把 stock_cover_qty 写大的入口)在**同一条 UPDATE**里维护标记:
  全额抵扣 ⇒ `supplier_code='STOCK_COVER'`;部分抵扣 ⇒ **不动**(缺口仍要厂商/自采,§5.1);
  释放/归零且原标记是 STOCK_COVER ⇒ 回退 `UNASSIGNED`。片段 `STOCK_COVER_SUPPLIER_SQL` 与
  **8 处归零点**共用(本文件 7 处 + inventoryReservationReplenishService 1 处),漏一处即留脏标记。

## 商品成本第三张表(页面 + 导出)
- 分桶取「或」:写入点打的标记 **或** 全额抵扣事实(`stock_cover_qty >= quantity`),且要求 `stock_cover_qty > 0`
  ⇒ **历史全额抵扣行无需回填**即进第三桶;释放后残留标记落自采表。
- `SkuCostSourceFilter` / 路由 / 列表与导出两个接口都放行 `stock_cover`;第三张表 `xl:grid-cols-3`、
  标题「库存抵扣」、表头「库存成本合计 ¥x · n 个商品」(该表采购成本恒 0)。
- 订单详情供应商下拉新增第三项「库存抵扣」;订单列表/订单导出/打印供货清单都不再出现裸码或空白。

## 全域「非厂商」守卫(R1 排查,新增 hasRealSupplierCode + NON_VENDOR_SUPPLIER_SQL_LIST)
- 会**静默造脏数据/抹掉标记**的三处最要命:`orderAllocationService` 结果落库安全网与 pending 过滤、
  `purchaseSupplierAssignService` 转供应商黑名单(原本不传 supplier_code 会静默建 STOCK_COVER 备货)、
  `orderManageItemsService` 加菜裸 INSERT 备货与 `isAssignedExternalSupplier`(否则保存会取消在途自采+删分拣行)。
- 其余 A 清单:竞价 `isRealBidSupplier` + 回写额外再挡一次、结算/应付×3、成本来源标签、退货红冲、
  验收单/再归属、备货成本回填、待备货/采购列表、商品指定供应商(后端拒 + 前端候选滤)。
- **B 类一行不动**(`isUnassignedSupplier` 系列):对"是否还要再分配"而言「已有供应商」就是对的。

## 实测(真库 BR002/BR003,服务函数直调,见 §6.1.5)
| 分支/周期 | 供应采购 | 自采采购 | 库存抵扣 |
| BR002 202610 | 0 行 ¥0 | 0 行 ¥0 | **3 行 / ¥137** |
| BR002 MOBILE | 0 行 ¥0 | 6 行 / ¥187 | **3 行 / ¥54** |
| BR003 MOBILE | 0 行 ¥0 | 4 行 / ¥61.8 | **8 行 / ¥942.2** |
三张表行数 = 表头合计,逐项对账相等;导出按来源筛同样落第三桶。
标记 SQL 语义在真库事务内验证并 ROLLBACK:全额→STOCK_COVER;部分(原标记)→UNASSIGNED;
部分(原厂商)→不动;释放归零→UNASSIGNED。

## 回归
- 后端 25 failed / 407 passed(干净 HEAD 890c055 为 27/396)⇒ **无新增失败**,另 2 个文件转好;
- 前端 2 failed / 163 passed(与基线同集合:SystemConfig.allowZeroCost、PickingManagement.outboundPhotoPreview);
- `tsc --noEmit`(前端)与 `tsc --noEmit -p server/tsconfig.json --module esnext` 均 0 错;
- 门禁 8 通过 / 1 已知红(check-ai-cost) / 1 未执行(verify-facts)。

## 未做(需裁决,见 §8 D 组)
D1 实时采购成本分桶(财务冻结)、D2 发车/入库照 skip_inbound(配送冻结)、
D3 改派真厂商的取消在途(分拣冻结)、D4 退货改派批次对齐、D5 小程序订单详情同改。
2026-10-14 17:32:29 +08:00

495 lines
16 KiB
TypeScript

import { supabase } from '../supabase/client';
import { isStockCoverSupplierCode, STOCK_COVER_SUPPLIER_NAME } from './allocationRules';
import { getQuoteSheetApi, listQuoteSheetsApi } from './workflowApi';
import { getStatementLinesApi, fetchDeliveryPrintLinesApi } from './workflowApi';
import type {
OrderExportRow,
QuoteExportRow,
StatementExportRow,
DeliveryExportRow,
} from './exportColumnPresets';
import { formatChinaDateTime } from './chinaDate';
import { formatCustomerDeliveryDeadlineDateTime } from './customerDeliveryDeadline';
function positivePrice(v: unknown): number {
const n = Number(v);
return Number.isFinite(n) && n > 0 ? n : 0;
}
async function loadQuoteCostMapByCustomer(customerCode: string): Promise<Map<string, number>> {
const code = String(customerCode || '').trim();
if (!code) return new Map();
try {
const list = await listQuoteSheetsApi({ view: 'active', customerCode: code, limit: 10 });
const sheets = (list.data || []) as Array<{ quote_sheet_code?: string }>;
const map = new Map<string, number>();
for (const sheet of sheets) {
if (!sheet?.quote_sheet_code) continue;
const detail = await getQuoteSheetApi(sheet.quote_sheet_code);
const items =
(
detail.data as {
items?: Array<{ sku_code?: string; cost_price?: number }>;
}
)?.items || [];
for (const row of items) {
const sku = String(row.sku_code || '').trim();
if (!sku) continue;
const cost = positivePrice(row.cost_price);
const prev = map.get(sku) || 0;
if (cost > 0 && cost >= prev) map.set(sku, cost);
else if (!map.has(sku)) map.set(sku, cost);
}
}
return map;
} catch {
return new Map();
}
}
export async function buildOrderExportRows(
orders: OrderExportRow[],
expandItems: boolean
): Promise<OrderExportRow[]> {
if (!expandItems || orders.length === 0) {
return orders;
}
type OrderItemRow = {
id?: string;
order_code: string;
sku_code?: string;
item_name?: string;
quantity?: number;
unit?: string;
price?: number;
locked_price?: number;
amount?: number;
unit_cost?: number;
processing_method?: string;
category_name?: string;
supplier_code?: string;
};
const orderCodes = orders.map((o) => o.order_code).filter(Boolean);
const { data: items, error } = await supabase
.from('order_items')
.select(
'id, order_code, sku_code, item_name, quantity, unit, price, locked_price, amount, unit_cost, processing_method, category_name, supplier_code'
)
.in('order_code', orderCodes);
if (error) throw error;
const orderItems = (items || []) as OrderItemRow[];
const skuCodes = [...new Set(orderItems.map((i) => i.sku_code).filter(Boolean))] as string[];
let skuMap = new Map<string, string>();
if (skuCodes.length) {
const { data: skus } = await supabase.from('skus').select('sku_code, sku_name').in('sku_code', skuCodes);
skuMap = new Map((skus || []).map((s: { sku_code: string; sku_name: string }) => [s.sku_code, s.sku_name]));
}
const supplierCodes = [
...new Set(orderItems.map((i) => String(i.supplier_code || '').trim()).filter(Boolean)),
];
let supplierNameMap = new Map<string, string>();
if (supplierCodes.length) {
const { data: suppliers } = await supabase
.from('suppliers')
.select('supplier_code, company_name')
.in('supplier_code', supplierCodes);
supplierNameMap = new Map(
(suppliers || []).map((s: { supplier_code: string; company_name: string }) => [
s.supplier_code,
s.company_name,
])
);
}
const { data: preps } = await supabase
.from('supplier_preparations')
.select('order_code, sku_code, supplier_code, purchase_price, is_stockout')
.in('order_code', orderCodes);
const { data: purchases } = await supabase
.from('purchase_orders')
.select('order_code, sku_code, source_id, actual_price, purchase_price, purchase_status')
.in('order_code', orderCodes);
// 与服务端筛选一致:按 order+sku 取 MAX(purchase_price)
const prepByOrderSku = new Map<string, number>();
for (const prep of preps || []) {
if (prep.is_stockout) continue;
const price = positivePrice(prep.purchase_price);
if (price <= 0) continue;
const keySku = `${prep.order_code}|${prep.sku_code}`;
prepByOrderSku.set(keySku, Math.max(prepByOrderSku.get(keySku) || 0, price));
}
const purchaseByItemId = new Map<string, number>();
const purchaseByOrderSku = new Map<string, number>();
for (const po of purchases || []) {
if (Number(po.purchase_status) < 20) continue;
const price = positivePrice(po.actual_price) || positivePrice(po.purchase_price);
if (price <= 0) continue;
if (po.source_id) purchaseByItemId.set(String(po.source_id), price);
const key = `${po.order_code}|${po.sku_code}`;
purchaseByOrderSku.set(key, Math.max(purchaseByOrderSku.get(key) || 0, price));
}
const customerCodes = [
...new Set(orders.map((o) => String(o.customer_code || '').trim()).filter(Boolean)),
];
const quoteCostByCustomer = new Map<string, Map<string, number>>();
await Promise.all(
customerCodes.map(async (code) => {
quoteCostByCustomer.set(code, await loadQuoteCostMapByCustomer(code));
})
);
const itemsByOrder = new Map<string, OrderItemRow[]>();
orderItems.forEach((item) => {
const list = itemsByOrder.get(item.order_code) || [];
list.push(item);
itemsByOrder.set(item.order_code, list);
});
const resolveCostPrice = (
_order: OrderExportRow,
item: {
id?: string;
sku_code?: string;
unit_cost?: number;
}
): number => {
if (item.unit_cost != null && Number.isFinite(Number(item.unit_cost))) {
return Math.max(0, Number(item.unit_cost) || 0);
}
const sku = String(item.sku_code || '');
const prepHit = positivePrice(prepByOrderSku.get(`${_order.order_code}|${sku}`));
if (prepHit > 0) return prepHit;
const byId = item.id ? positivePrice(purchaseByItemId.get(String(item.id))) : 0;
if (byId > 0) return byId;
const byOrderSku = positivePrice(purchaseByOrderSku.get(`${_order.order_code}|${sku}`));
if (byOrderSku > 0) return byOrderSku;
const customer = String(_order.customer_code || '').trim();
return positivePrice(quoteCostByCustomer.get(customer)?.get(sku));
};
const rows: OrderExportRow[] = [];
for (const order of orders) {
const orderItems = itemsByOrder.get(order.order_code) || [];
if (orderItems.length === 0) {
rows.push(order);
continue;
}
let matched = 0;
for (const item of orderItems) {
const salePrice =
positivePrice((item as { locked_price?: number }).locked_price) ||
positivePrice(item.price) ||
0;
const costPrice = resolveCostPrice(order, item);
matched += 1;
const qty = Number(item.quantity) || 0;
const amount =
item.amount != null && Number(item.amount) !== 0
? Number(item.amount)
: Math.round(qty * salePrice * 100) / 100;
rows.push({
...order,
sku_code: item.sku_code,
sku_name: item.item_name || skuMap.get(String(item.sku_code || '')) || item.sku_code,
item_name: item.item_name,
quantity: item.quantity,
unit: item.unit,
price: salePrice,
cost_price: costPrice,
amount,
processing_method: item.processing_method,
category_name: item.category_name,
// 库存抵扣(STOCK_COVER)不是厂商:导出不要打出裸码,落中文名
supplier_name: isStockCoverSupplierCode(item.supplier_code)
? STOCK_COVER_SUPPLIER_NAME
: supplierNameMap.get(String(item.supplier_code || '')) || item.supplier_code || undefined,
});
}
if (matched === 0) {
rows.push(order);
}
}
return rows;
}
export async function buildQuoteExportRows(
sheets: Array<{
quote_sheet_code: string;
title?: string | null;
version_no?: number;
quote_cycle?: string | null;
customer_names?: string | null;
approval_status?: number;
effective_at?: string | null;
expires_at?: string | null;
items?: Array<{
sku_code: string;
sku_name?: string;
unit?: string;
price: number;
cost_price?: number;
sale_price?: number;
}>;
customers?: Array<{ customer_code: string; company_name: string }>;
}>,
expandItems: boolean
): Promise<QuoteExportRow[]> {
const rows: QuoteExportRow[] = [];
for (const sheet of sheets) {
let detail = sheet;
if (expandItems && !sheet.items?.length) {
try {
const { data } = await getQuoteSheetApi(sheet.quote_sheet_code);
detail = { ...sheet, ...(data as typeof sheet) };
} catch {
detail = sheet;
}
}
const header: QuoteExportRow = {
quote_sheet_code: sheet.quote_sheet_code,
title: sheet.title || undefined,
version_no: sheet.version_no,
quote_cycle: sheet.quote_cycle || undefined,
customer_names:
sheet.customer_names ||
(detail.customers || []).map((c) => c.company_name).join('、') ||
undefined,
approval_status: sheet.approval_status,
effective_at: sheet.effective_at || undefined,
expires_at: sheet.expires_at || undefined,
};
if (!expandItems || !(detail.items || []).length) {
rows.push(header);
continue;
}
for (const item of detail.items || []) {
rows.push({
...header,
sku_code: item.sku_code,
sku_name: item.sku_name,
unit: item.unit,
price: item.price,
cost_price: item.cost_price,
sale_price: item.sale_price ?? item.price,
});
}
}
return rows;
}
export async function buildStatementExportRows(
statements: StatementExportRow[],
statementType: 'customer' | 'supplier',
expandItems: boolean
): Promise<StatementExportRow[]> {
if (!expandItems) {
return statementType === 'customer'
? appendCustomerStatementSummary(statements)
: statements;
}
const rows: StatementExportRow[] = [];
for (const statement of statements) {
try {
const { data } = await getStatementLinesApi(statement.statement_no, statementType);
const lines = (data || []) as Array<{
order_code?: string;
sku_code?: string;
sku_name?: string;
quantity?: number;
unit_price?: number;
line_amount?: number;
price_source?: string;
category_name?: string;
}>;
if (!lines.length) {
rows.push(statement);
continue;
}
for (const line of lines) {
rows.push({
...statement,
order_code: line.order_code,
sku_code: line.sku_code,
sku_name: line.sku_name,
quantity: line.quantity,
unit_price: line.unit_price,
line_amount: line.line_amount,
price_source: line.price_source,
category_name: line.category_name,
});
}
} catch {
rows.push(statement);
}
}
return statementType === 'customer' ? appendCustomerStatementSummary(rows) : rows;
}
function appendCustomerStatementSummary(rows: StatementExportRow[]): StatementExportRow[] {
if (!rows.length) return rows;
const statementTotals = new Map<string, number>();
for (const row of rows) {
if (row.is_summary_row || !row.statement_no) continue;
statementTotals.set(row.statement_no, Number(row.total_amount || 0));
}
const grandTotal = [...statementTotals.values()].reduce((sum, amount) => sum + amount, 0);
if (!statementTotals.size) {
const headerTotal = rows.reduce((sum, row) => sum + Number(row.total_amount || 0), 0);
if (headerTotal <= 0) return rows;
return [
...rows,
{
statement_no: '',
party_code: '',
party_name: '合计',
cycle_code: '',
total_amount: Math.round(headerTotal * 100) / 100,
is_summary_row: true,
},
];
}
return [
...rows,
{
statement_no: '',
party_code: '',
party_name: '合计',
cycle_code: '',
total_amount: Math.round(grandTotal * 100) / 100,
is_summary_row: true,
},
];
}
export async function buildDeliveryExportRows(
tasks: Array<{
task_code?: string;
order_code: string;
customer_code?: string;
customer_name?: string;
customer_phone?: string;
address?: string;
delivery_person?: string;
delivery_person_phone?: string;
status?: string;
estimated_time?: string;
delivery_date?: string | null;
actual_time?: string;
items?: Array<{ sku_name: string; quantity: number; unit: string }>;
}>,
expandItems: boolean
): Promise<DeliveryExportRow[]> {
const rows: DeliveryExportRow[] = [];
if (!expandItems || tasks.length === 0) {
for (const task of tasks) {
rows.push({
task_code: task.task_code,
order_code: task.order_code,
customer_code: task.customer_code,
customer_name: task.customer_name,
customer_phone: task.customer_phone,
address: task.address,
delivery_person: task.delivery_person,
delivery_person_phone: task.delivery_person_phone,
status: task.status,
estimated_time:
formatCustomerDeliveryDeadlineDateTime(task.delivery_date, task.estimated_time) ||
task.estimated_time ||
'',
actual_time: task.actual_time ? formatChinaDateTime(task.actual_time) : '',
});
}
return rows;
}
const orderCodes = tasks.map((t) => t.order_code).filter(Boolean);
const { lines } = await fetchDeliveryPrintLinesApi(orderCodes);
const linesByOrder = new Map<string, typeof lines>();
for (const line of lines) {
const list = linesByOrder.get(line.order_code) || [];
list.push(line);
linesByOrder.set(line.order_code, list);
}
for (const task of tasks) {
const header: DeliveryExportRow = {
task_code: task.task_code,
order_code: task.order_code,
customer_code: task.customer_code,
customer_name: task.customer_name,
customer_phone: task.customer_phone,
address: task.address,
delivery_person: task.delivery_person,
delivery_person_phone: task.delivery_person_phone,
status: task.status,
estimated_time:
formatCustomerDeliveryDeadlineDateTime(task.delivery_date, task.estimated_time) ||
task.estimated_time ||
'',
actual_time: task.actual_time ? formatChinaDateTime(task.actual_time) : '',
};
const orderLines = linesByOrder.get(task.order_code) || [];
if (!orderLines.length) {
rows.push(header);
continue;
}
let seq = 0;
for (const line of orderLines) {
seq += 1;
rows.push({
...header,
seq_no: seq,
sku_code: line.sku_code,
sku_name: line.sku_name,
customer_alias: line.customer_alias || undefined,
category_name: line.category_name || undefined,
spec: line.spec || undefined,
origin: line.origin || undefined,
quantity: line.quantity,
unit: line.unit,
price: line.price,
amount: line.amount,
actual_amount: line.actual_amount ?? undefined,
picked_qty: line.picked_qty,
loaded_qty: line.loaded_qty,
inspection_actual_qty: line.inspection_actual_qty,
weigh_qty: line.weigh_qty,
weigh_unit: line.weigh_unit || undefined,
base_unit: line.base_unit || undefined,
weigh_qty_base: line.weigh_qty_base,
delivery_qty: line.delivery_qty,
box_no: line.box_no || undefined,
box_count: line.box_count,
processing_method: line.processing_method || undefined,
supplier_name: line.supplier_name || undefined,
is_extra_dish: Boolean(line.is_extra_dish),
});
}
}
return rows;
}