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

参考配送系统口径并适配供应商:报价单优先,共享单跳过;无报价单只更新已存在 customer_skus,不新建;加菜/0价/同值跳过;下单写全部、改单只写变价行;非阻塞+合并审计。
This commit is contained in:
Ubuntu
2026-10-27 19:04:50 +08:00
parent ce55c8648a
commit 85a1f74ac0
5 changed files with 267 additions and 1 deletions
@@ -94,6 +94,18 @@ body:`{ sku_code, sale_price: number, target_type?: 'quote_sheet'|'customer_sk
改动点:`orderPricingService`(提交/预填/单位变更兜底)、`orderItemHelpers.fillBidPrices`、小程序客户商品接口(如有)。
显式客户商品库价不乘折扣。
## 5.1 录单/改单销售价回写(2026-10-27 追加,参考配送系统)
订单提交成功 / 改单保存成功后,非阻塞回写订单行销售价:
1. 客户执行中报价单含该 SKU:
- 报价单只绑定一个客户 → 写 `sale_price + price`,并置 `sale_price_manual=true`;
- 绑定多个客户 → 跳过(避免把 A 客户成交价串给 B 客户)。
2. 否则只更新**已存在**的 `customer_skus.sale_price`,不 INSERT;
3. 两者都没有、加菜行、`price<=0` → 跳过;
4. 同值不写;提交写全部订单行,改单只写本次价格变化的行;
5. 失败只记日志,不影响下单/保存;成功后合并一条 `order_sale_price_writeback` 审计。
## 6. UI(供应商版)
- 单客户:显示来源(报价单/商品库/订单)+ 当前销售价;铅笔就地编辑并保存。
@@ -806,6 +806,25 @@ export async function submitMobileCustomerOrder(
}
}
// 录单成功后回写价格主数据(报价单优先/商品库仅更新),失败不阻断下单。
try {
const { writeBackOrderSalePrices } = await import('./orderSalePriceWritebackService');
await writeBackOrderSalePrices({
customerCode: input.customerCode,
orderCode,
branchCode: input.branchCode,
operatorId: input.userId || null,
items: pricedForInsert.map((item: any) => ({
sku_code: item.sku_code ? String(item.sku_code) : null,
item_name: item.item_name ? String(item.item_name) : null,
price: item.price,
is_extra_dish: item.is_extra_dish,
})),
});
} catch (err) {
console.warn('[customerOrderSubmit] 销售价回写失败(不影响下单)', orderCode, err);
}
const statusResult = await pool.query(`SELECT order_status FROM orders WHERE order_code = $1`, [orderCode]);
const orderStatus = Number(statusResult.rows[0]?.order_status || 20);
+34 -1
View File
@@ -972,6 +972,7 @@ export async function syncOrderManageItems(params: {
}> = [];
const inboundReattributeItemIds = new Set<string>();
let existingItemsForAudit: ExistingOrderItemForAudit[] = [];
let orderCustomerCode: string | null = null;
const client = await connectExclusiveTenantClient();
/** 先改后通知:本次明细保存中被改动的"主系统行"价/量变更(COMMIT 后异步通知主系统) */
let priceQtyNotices: ReturnType<typeof collectMainSystemPriceQtyChanges> = [];
@@ -979,13 +980,16 @@ export async function syncOrderManageItems(params: {
await client.query('BEGIN');
const lockedOrder = await client.query(
`SELECT order_status, branch_code, created_at
`SELECT order_status, branch_code, customer_code, created_at
FROM orders WHERE order_code = $1 FOR UPDATE`,
[orderCode]
);
if (!lockedOrder.rowCount) {
throw Object.assign(new Error('订单不存在'), { status: 404, code: 'not_found' });
}
orderCustomerCode = lockedOrder.rows[0]?.customer_code
? String(lockedOrder.rows[0].customer_code)
: null;
const lockedStatus = Number(lockedOrder.rows[0].order_status) || 0;
if (lockedStatus !== orderStatus) {
throw Object.assign(new Error('订单状态已变更,请刷新后重试'), {
@@ -2298,6 +2302,35 @@ export async function syncOrderManageItems(params: {
[orderCode]
);
// 改单仅回写价格发生变化的行(不重写全部行);失败不阻断保存。
try {
const oldPriceById = new Map(
existingItemsForAudit.map((row) => [String(row.id), Number(row.price) || 0])
);
const changed = items.rows.filter((row) => {
const old = oldPriceById.get(String(row.id));
// 新增行没有旧价也要回写;已有行只在价格变化时回写。
return old == null || Math.abs(old - (Number(row.price) || 0)) > 1e-9;
});
if (changed.length) {
const { writeBackOrderSalePrices } = await import('./orderSalePriceWritebackService');
await writeBackOrderSalePrices({
customerCode: orderCustomerCode || '',
orderCode,
branchCode: order.branch_code || null,
operatorId: params.operatorId || null,
items: changed.map((row) => ({
sku_code: row.sku_code ? String(row.sku_code) : null,
item_name: row.item_name ? String(row.item_name) : null,
price: row.price,
is_extra_dish: row.is_extra_dish,
})),
});
}
} catch (err) {
console.warn('[order-items] 销售价回写失败(不影响改单)', orderCode, err);
}
return {
total_amount: totalAmount,
total_weight: totalWeight,
@@ -0,0 +1,162 @@
import { pool } from '../db';
import { writeAuditLog } from './auditService';
/**
* 录单/改单销售价回写价格主数据(供应商版,2026-10-27)。
*
* 触发:订单提交成功 / 改单保存成功后(不阻塞主流程,失败只日志)。
* 规则:
* 1) 客户执行中报价单含该 SKU:若报价单绑定客户数 > 1,跳过(共享报价单不串价);
* 否则写 quote item sale_price+price,并置 sale_price_manual=true;
* 2) 无报价单:只更新已存在的 customer_skus(不 INSERT);
* 3) 两者都没有 / 加菜 / price<=0:跳过。
* 只写价格主数据,不写订单/结算/库存;所有写用 IS DISTINCT FROM 避免同值抖动。
*/
export interface OrderSalePriceWritebackItem {
sku_code?: string | null;
item_name?: string | null;
price?: number | string | null;
is_extra_dish?: boolean | string | number | null;
}
export interface OrderSalePriceWritebackResult {
quote_updated: number;
customer_sku_updated: number;
skipped: number;
}
const trim = (v: unknown) => String(v ?? '').trim();
export async function writeBackOrderSalePrices(input: {
customerCode: string;
orderCode: string;
branchCode?: string | null;
operatorId?: string | null;
operatorName?: string | null;
items: OrderSalePriceWritebackItem[];
}): Promise<OrderSalePriceWritebackResult> {
const customerCode = trim(input.customerCode);
const orderCode = trim(input.orderCode);
const branchCode = trim(input.branchCode) || null;
const result: OrderSalePriceWritebackResult = {
quote_updated: 0,
customer_sku_updated: 0,
skipped: 0,
};
if (!customerCode || !orderCode) return result;
const entries = new Map<string, number>();
for (const item of input.items || []) {
const extra = item?.is_extra_dish;
if (extra === true || extra === 't' || extra === 'true' || extra === 1) {
result.skipped += 1;
continue;
}
const skuCode = trim(item?.sku_code);
const price = Number(item?.price);
if (!skuCode || !Number.isFinite(price) || price <= 0) {
result.skipped += 1;
continue;
}
entries.set(skuCode, Math.round(price * 10000) / 10000);
}
if (!entries.size) return result;
const quoteChanges: Array<{ sku_code: string; sale_price: number; quote_sheet_code: string }> = [];
const customerSkuChanges: Array<{ sku_code: string; sale_price: number }> = [];
for (const [skuCode, price] of entries) {
const params: unknown[] = [customerCode, skuCode];
let branchFilter = '';
if (branchCode) {
params.push(branchCode);
branchFilter = `AND (qs.branch_code IS NULL OR qs.branch_code = $${params.length})`;
}
// 先查报价单及绑定客户数;共享报价单(绑定>1)不能把某客户成交价串给其他客户。
const quoteMeta = await pool.query(
`SELECT qs.quote_sheet_code,
(SELECT COUNT(*)::int FROM customer_quote_sheet_customers c2
WHERE c2.quote_sheet_code = qs.quote_sheet_code) AS customer_count
FROM customer_quote_sheet_items i
JOIN customer_quote_sheets qs ON qs.quote_sheet_code = i.quote_sheet_code
JOIN customer_quote_sheet_customers qsc ON qsc.quote_sheet_code = qs.quote_sheet_code
WHERE qsc.customer_code = $1 AND i.sku_code = $2
AND qs.status = 1 AND qs.approval_status = 30
AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
${branchFilter}
LIMIT 1`,
params
);
const quoteRow = quoteMeta.rows[0];
if (quoteRow) {
if (Number(quoteRow.customer_count) > 1) {
result.skipped += 1;
continue;
}
const updated = await pool.query(
`UPDATE customer_quote_sheet_items i
SET sale_price = $1::numeric,
price = $1::numeric,
sale_price_manual = true
FROM customer_quote_sheets qs
WHERE i.quote_sheet_code = qs.quote_sheet_code
AND i.quote_sheet_code = $3
AND i.sku_code = $2
AND (i.sale_price IS DISTINCT FROM $1::numeric
OR i.price IS DISTINCT FROM $1::numeric
OR COALESCE(i.sale_price_manual, false) = false)`,
[price, skuCode, String(quoteRow.quote_sheet_code)]
);
if ((updated.rowCount || 0) > 0) {
quoteChanges.push({
sku_code: skuCode,
sale_price: price,
quote_sheet_code: String(quoteRow.quote_sheet_code),
});
}
continue;
}
// 商品库只更新已存在行,不 INSERT。
const updated = await pool.query(
`UPDATE customer_skus
SET sale_price = $1::numeric,
price_updated_at = NOW(),
price_updated_by = $3::uuid,
updated_at = NOW()
WHERE customer_code = $2
AND sku_code = $4
AND sale_price IS DISTINCT FROM $1::numeric`,
[price, customerCode, trim(input.operatorId) || null, skuCode]
);
if ((updated.rowCount || 0) > 0) {
customerSkuChanges.push({ sku_code: skuCode, sale_price: price });
}
}
result.quote_updated = quoteChanges.length;
result.customer_sku_updated = customerSkuChanges.length;
if (quoteChanges.length || customerSkuChanges.length) {
try {
await writeAuditLog({
operatorId: trim(input.operatorId) || null,
operatorName: input.operatorName || null,
operationType: 'order_sale_price_writeback',
targetTable: 'order_items',
targetId: orderCode,
newValue: {
customer_code: customerCode,
order_code: orderCode,
quote_sheet_items: quoteChanges,
customer_skus: customerSkuChanges,
},
branchCode,
actionCategory: 'price',
});
} catch (error) {
console.warn('[order-sale-price-writeback] 审计失败', error);
}
}
return result;
}
@@ -0,0 +1,40 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8');
const svc = read('src/services/orderSalePriceWritebackService.ts');
const submit = read('src/services/customerOrderSubmitService.ts');
const manage = read('src/services/orderManageItemsService.ts');
describe('订单销售价回写价格主数据', () => {
it('过滤加菜/0 价、按 SKU 去重、共享报价单跳过', () => {
expect(svc).toContain('is_extra_dish');
expect(svc).toContain('price <= 0');
expect(svc).toContain('entries.set(skuCode');
expect(svc).toContain('customer_count) > 1');
expect(svc).toContain('result.skipped += 1');
});
it('报价单优先并置 manual;无报价单只更新已有 customer_skus,不 INSERT', () => {
expect(svc).toContain('sale_price_manual = true');
expect(svc).toContain('UPDATE customer_quote_sheet_items');
expect(svc).toContain('UPDATE customer_skus');
expect(svc).not.toContain('INSERT INTO customer_skus');
expect(svc).toContain('IS DISTINCT FROM');
expect(svc).toContain("operationType: 'order_sale_price_writeback'");
});
it('提交路径在 syncCustomerMappings 之后调用 pricedForInsert', () => {
const syncIdx = submit.indexOf('await syncCustomerMappings({');
const writeIdx = submit.indexOf('writeBackOrderSalePrices({');
expect(syncIdx).toBeGreaterThan(-1);
expect(writeIdx).toBeGreaterThan(syncIdx);
expect(submit).toContain('items: pricedForInsert.map');
});
it('改单只回写 price 变化的行', () => {
expect(manage).toContain('existingItemsForAudit.map((row) => [String(row.id), Number(row.price)');
expect(manage).toContain('Math.abs(old - (Number(row.price) || 0)) > 1e-9');
expect(manage).toContain('items: changed.map');
});
});