1396 lines
51 KiB
TypeScript
1396 lines
51 KiB
TypeScript
import { pool } from '../db';
|
||
import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||
import { notifyRoleUsers } from './notificationService';
|
||
|
||
export const QUOTE_CYCLE_OPTIONS = {
|
||
week: { label: '周', days: 7 },
|
||
half_month: { label: '半月', days: 15 },
|
||
month: { label: '月', days: 30 },
|
||
half_year: { label: '半年', days: 180 },
|
||
year: { label: '年', days: 365 },
|
||
} as const;
|
||
|
||
export type QuoteCycleKey = keyof typeof QUOTE_CYCLE_OPTIONS;
|
||
|
||
export interface QuoteSheetItemInput {
|
||
sku_code: string;
|
||
unit?: string;
|
||
/** 兼容旧调用,等同于 sale_price */
|
||
price?: number;
|
||
cost_price?: number;
|
||
sale_price?: number;
|
||
/** 成本基础上的加价百分比;20 表示销售价为成本的 120% */
|
||
markup_ratio?: number | null;
|
||
sku_name?: string;
|
||
}
|
||
|
||
function readSalePrice(item: QuoteSheetItemInput): number {
|
||
return Number(item.sale_price ?? item.price) || 0;
|
||
}
|
||
|
||
function readCostPrice(item: QuoteSheetItemInput): number {
|
||
return Math.max(0, Number(item.cost_price) || 0);
|
||
}
|
||
|
||
function resolveBranchCode(
|
||
ctx: TenantContext | null | undefined,
|
||
operatingBranchCode?: string | null
|
||
): string {
|
||
const branchCode = getEffectiveBranchCode(ctx || null, operatingBranchCode);
|
||
if (branchCode) return branchCode;
|
||
if (ctx?.isSuperAdmin) throw new Error('请选择当前操作分公司');
|
||
if (ctx?.branchCode) return ctx.branchCode;
|
||
throw new Error('未分配分公司,无法操作报价单');
|
||
}
|
||
|
||
function branchFilter(
|
||
ctx: TenantContext | null | undefined,
|
||
alias: string,
|
||
params: unknown[],
|
||
operatingBranchCode?: string | null
|
||
) {
|
||
const branchCode = resolveBranchCode(ctx, operatingBranchCode);
|
||
params.push(branchCode);
|
||
return ` AND ${alias}.branch_code = $${params.length}`;
|
||
}
|
||
|
||
export async function assertCustomersInBranch(customerCodes: string[], branchCode: string) {
|
||
const result = await pool.query(
|
||
`SELECT customer_code FROM customers WHERE customer_code = ANY($1) AND branch_code = $2`,
|
||
[customerCodes, branchCode]
|
||
);
|
||
if (result.rows.length !== customerCodes.length) {
|
||
throw new Error('所选客户须属于当前分公司');
|
||
}
|
||
}
|
||
|
||
export function newSheetCode() {
|
||
return `QS${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
|
||
}
|
||
|
||
function newQuoteVersionCode() {
|
||
return `QV${Date.now()}${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
|
||
}
|
||
|
||
export function computeExpiresAt(from: Date, cycle?: string | null): Date | null {
|
||
if (!cycle || !(cycle in QUOTE_CYCLE_OPTIONS)) return null;
|
||
const days = QUOTE_CYCLE_OPTIONS[cycle as QuoteCycleKey].days;
|
||
return new Date(from.getTime() + days * 86400000);
|
||
}
|
||
|
||
function readMarkupRatio(item: QuoteSheetItemInput): number | null {
|
||
if (item.markup_ratio == null) return null;
|
||
const ratio = Number(item.markup_ratio);
|
||
return Number.isFinite(ratio) && ratio >= 0 ? ratio : null;
|
||
}
|
||
|
||
function utcDateKey(value: Date | string | null | undefined): string | null {
|
||
if (!value) return null;
|
||
const date = value instanceof Date ? value : new Date(value);
|
||
return Number.isFinite(date.getTime()) ? date.toISOString().slice(0, 10) : null;
|
||
}
|
||
|
||
export function resolveQuoteSheetUpdateDates(
|
||
existing: {
|
||
quote_cycle?: string | null;
|
||
effective_at?: Date | string | null;
|
||
expires_at?: Date | string | null;
|
||
},
|
||
input: { quoteCycle?: string | null; effectiveAt?: string | null },
|
||
now = new Date()
|
||
): { quoteCycle: string | null | undefined; effectiveAt: Date; expiresAt: Date | null } {
|
||
const requestedEffectiveAt = input.effectiveAt ? new Date(input.effectiveAt) : null;
|
||
if (requestedEffectiveAt && !Number.isFinite(requestedEffectiveAt.getTime())) {
|
||
throw new Error('生效日期无效');
|
||
}
|
||
const effectiveAtChanged = Boolean(
|
||
requestedEffectiveAt && utcDateKey(requestedEffectiveAt) !== utcDateKey(existing.effective_at)
|
||
);
|
||
const quoteCycle = input.quoteCycle !== undefined
|
||
? input.quoteCycle || existing.quote_cycle
|
||
: existing.quote_cycle;
|
||
const cycleChanged = quoteCycle !== existing.quote_cycle;
|
||
const effectiveAt = effectiveAtChanged
|
||
? requestedEffectiveAt!
|
||
: existing.effective_at
|
||
? existing.effective_at instanceof Date ? existing.effective_at : new Date(existing.effective_at)
|
||
: requestedEffectiveAt || now;
|
||
const shouldRecalculateExpiry = effectiveAtChanged || cycleChanged;
|
||
const expiresAt = shouldRecalculateExpiry
|
||
? computeExpiresAt(effectiveAt, quoteCycle)
|
||
: existing.expires_at
|
||
? existing.expires_at instanceof Date ? existing.expires_at : new Date(existing.expires_at)
|
||
: null;
|
||
|
||
return { quoteCycle, effectiveAt, expiresAt };
|
||
}
|
||
|
||
async function nextSheetVersionNo(branchCode: string) {
|
||
const result = await pool.query(
|
||
`SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version
|
||
FROM customer_quote_sheets
|
||
WHERE branch_code = $1`,
|
||
[branchCode]
|
||
);
|
||
return Number(result.rows[0]?.next_version) || 1;
|
||
}
|
||
|
||
async function loadSheetDetail(quoteSheetCode: string) {
|
||
const [sheetResult, itemsResult, customersResult] = await Promise.all([
|
||
pool.query(`SELECT * FROM customer_quote_sheets WHERE quote_sheet_code = $1`, [quoteSheetCode]),
|
||
pool.query(
|
||
`SELECT i.*, s.sku_name AS catalog_name
|
||
FROM customer_quote_sheet_items i
|
||
LEFT JOIN skus s ON s.sku_code = i.sku_code
|
||
WHERE i.quote_sheet_code = $1
|
||
ORDER BY i.sort_order ASC, i.sku_code ASC`,
|
||
[quoteSheetCode]
|
||
),
|
||
pool.query(
|
||
`SELECT c.customer_code, cu.company_name
|
||
FROM customer_quote_sheet_customers c
|
||
JOIN customers cu ON cu.customer_code = c.customer_code
|
||
WHERE c.quote_sheet_code = $1
|
||
ORDER BY cu.company_name ASC`,
|
||
[quoteSheetCode]
|
||
),
|
||
]);
|
||
if (!sheetResult.rows.length) return null;
|
||
return {
|
||
...sheetResult.rows[0],
|
||
items: itemsResult.rows,
|
||
customers: customersResult.rows,
|
||
};
|
||
}
|
||
|
||
/** 创建报价单(多商品 + 多/单客户) */
|
||
/**
|
||
* 编辑阶段「本单客户不变 + 追加客户另建单」的判定(2026-10-19)。
|
||
* 把查询放在 service(路由层禁止裸 SQL,见 routeLayerBoundary 契约测试)。
|
||
*/
|
||
export async function resolveEditCustomerSplit(input: {
|
||
quoteSheetCode: string;
|
||
requestedCustomerCodes: string[];
|
||
/** 必须传:业务表是 FORCE RLS,不带 `app.branch_code` 时查询恒为 0 行(生产事故 2026-10-19) */
|
||
branchCode: string;
|
||
}): Promise<{ ownCustomerCodes: string[]; customersToCreate: string[]; takenCustomerCodes: string[] }> {
|
||
const code = String(input.quoteSheetCode || '').trim();
|
||
const requested = Array.from(new Set(input.requestedCustomerCodes.map((c) => String(c || '').trim()).filter(Boolean)));
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const client = await pool.connect();
|
||
try {
|
||
/**
|
||
* **事务级**设置租户上下文(`true`):事务结束自动失效,绝不能用会话级 false——
|
||
* 连接回池后若残留 `''`,同连接上的其它查询会因 RLS 返回 0 行(生产事故 2026-10-19:
|
||
* 编辑报价单报「报价单不存在」)。
|
||
*/
|
||
await client.query('BEGIN');
|
||
await client.query(`SELECT set_config('app.branch_code', $1, true)`, [branchCode]);
|
||
const current = await client.query<{ customer_code: string }>(
|
||
`SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1`,
|
||
[code]
|
||
);
|
||
let ownCustomerCodes = current.rows.map((r) => String(r.customer_code));
|
||
/**
|
||
* 兜底(生产事故 2026-10-19):若因分公司上下文没命中而查不到本单客户,
|
||
* **绝不能把空列表传给编辑服务**(会 500「请至少选择一个客户」)。
|
||
* 此时以请求里带的客户为准(前端本来就把当前单据的客户一起提交)。
|
||
*/
|
||
if (!ownCustomerCodes.length && requested.length) {
|
||
console.warn('[quote-edit] 本单客户查询为空,回退使用请求客户', {
|
||
quoteSheetCode: code,
|
||
branchCode,
|
||
requested,
|
||
});
|
||
ownCustomerCodes = [...requested];
|
||
}
|
||
const ownSet = new Set(ownCustomerCodes);
|
||
const extra = requested.filter((c) => !ownSet.has(c));
|
||
// 单出口:先算结果,再 COMMIT,最后 return(早退会跳过 COMMIT,把脏事务留给连接池)
|
||
let payload = { ownCustomerCodes, customersToCreate: [] as string[], takenCustomerCodes: [] as string[] };
|
||
if (extra.length) {
|
||
const taken = await client.query<{ customer_code: string }>(
|
||
`SELECT DISTINCT customer_code FROM customer_quote_sheet_customers WHERE customer_code = ANY($1::text[])`,
|
||
[extra]
|
||
);
|
||
const takenCustomerCodes = taken.rows.map((r) => String(r.customer_code));
|
||
const takenSet = new Set(takenCustomerCodes);
|
||
payload = {
|
||
ownCustomerCodes,
|
||
customersToCreate: extra.filter((c) => !takenSet.has(c)),
|
||
takenCustomerCodes,
|
||
};
|
||
}
|
||
await client.query('COMMIT');
|
||
return payload;
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
/** 读取幂等记录(routeLayerBoundary:路由层禁止裸 SQL,故放 service) */
|
||
export async function readQuoteSheetIdempotency(input: { branchCode: string; idemKey: string }) {
|
||
const { rows } = await pool.query<{ request_hash: string; response_json: unknown }>(
|
||
`SELECT request_hash, response_json FROM public.quote_sheet_idempotency
|
||
WHERE branch_code = $1 AND idem_key = $2`,
|
||
[input.branchCode || '', input.idemKey]
|
||
);
|
||
return rows[0] ?? null;
|
||
}
|
||
|
||
/** 写入幂等记录(同 key 并发时 ON CONFLICT DO NOTHING,先写者胜) */
|
||
export async function writeQuoteSheetIdempotency(input: {
|
||
branchCode: string;
|
||
idemKey: string;
|
||
requestHash: string;
|
||
response: unknown;
|
||
}) {
|
||
await pool.query(
|
||
`INSERT INTO public.quote_sheet_idempotency (branch_code, idem_key, request_hash, response_json)
|
||
VALUES ($1, $2, $3, $4::jsonb) ON CONFLICT (branch_code, idem_key) DO NOTHING`,
|
||
[input.branchCode || '', input.idemKey, input.requestHash, JSON.stringify(input.response)]
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 幂等键串行化(红队 #5):同一 (分公司, 幂等键) 的请求必须串行,
|
||
* 否则并发同 key 会各建一套单。返回 release(),调用方必须 finally 释放。
|
||
*/
|
||
export async function acquireQuoteSheetIdempotencyLock(input: {
|
||
branchCode: string;
|
||
idemKey: string;
|
||
}): Promise<{ release: () => Promise<void> }> {
|
||
const client = await pool.connect();
|
||
const key = `quote-sheet-idem:${input.branchCode || ''}:${input.idemKey}`;
|
||
await client.query(`SELECT pg_advisory_lock(hashtext($1))`, [key]);
|
||
return {
|
||
release: async () => {
|
||
try {
|
||
await client.query(`SELECT pg_advisory_unlock(hashtext($1))`, [key]);
|
||
} finally {
|
||
client.release();
|
||
}
|
||
},
|
||
};
|
||
}
|
||
|
||
export async function createQuoteSheet(input: {
|
||
title?: string;
|
||
customerCodes: string[];
|
||
items: QuoteSheetItemInput[];
|
||
autoSalePriceByCost?: boolean;
|
||
quoteCycle?: string | null;
|
||
effectiveAt?: string | null;
|
||
createdBy?: string | null;
|
||
branchCode?: string | null;
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
}) {
|
||
const customerCodes = [...new Set(input.customerCodes.map((c) => c.trim()).filter(Boolean))];
|
||
const items = input.items.filter((i) => i.sku_code?.trim() && readSalePrice(i) > 0);
|
||
if (!customerCodes.length) throw new Error('请至少选择一个客户');
|
||
if (!items.length) throw new Error('请至少添加一个商品');
|
||
|
||
const branchCode = input.branchCode || resolveBranchCode(input.ctx, input.operatingBranchCode);
|
||
await assertCustomersInBranch(customerCodes, branchCode);
|
||
|
||
const quoteSheetCode = newSheetCode();
|
||
const versionNo = await nextSheetVersionNo(branchCode);
|
||
const effectiveAt = input.effectiveAt ? new Date(input.effectiveAt) : new Date();
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
/**
|
||
* 并发防线(红队 #3,2026-10-19):同一 (分公司, 客户) 的建单必须串行,
|
||
* 否则两个请求同时给同一无单客户建单会各建一张生效单。
|
||
* 事务级 advisory lock,提交/回滚自动释放。
|
||
*/
|
||
for (const code of customerCodes) {
|
||
await client.query(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
|
||
`quote-sheet:${input.branchCode || input.operatingBranchCode || ''}:${String(code).toUpperCase()}`,
|
||
]);
|
||
}
|
||
await client.query(
|
||
`INSERT INTO customer_quote_sheets
|
||
(quote_sheet_code, title, version_no, quote_cycle, effective_at, status, approval_status,
|
||
auto_sale_price_by_cost,
|
||
branch_code, created_by, created_at, updated_at)
|
||
VALUES ($1, $2, $3, $4, $5, 0, 10, $6, $7, $8, NOW(), NOW())`,
|
||
[
|
||
quoteSheetCode,
|
||
input.title?.trim() || `报价单 V${versionNo}`,
|
||
versionNo,
|
||
input.quoteCycle || 'month',
|
||
effectiveAt.toISOString(),
|
||
Boolean(input.autoSalePriceByCost),
|
||
input.branchCode || branchCode,
|
||
input.createdBy || null,
|
||
]
|
||
);
|
||
|
||
for (let i = 0; i < customerCodes.length; i += 1) {
|
||
await client.query(
|
||
`INSERT INTO customer_quote_sheet_customers (quote_sheet_code, customer_code) VALUES ($1, $2)`,
|
||
[quoteSheetCode, customerCodes[i]]
|
||
);
|
||
}
|
||
|
||
for (let i = 0; i < items.length; i += 1) {
|
||
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)`,
|
||
[
|
||
quoteSheetCode,
|
||
item.sku_code.trim(),
|
||
item.sku_name?.trim() || null,
|
||
item.unit?.trim() || null,
|
||
readSalePrice(item),
|
||
readCostPrice(item),
|
||
readSalePrice(item),
|
||
readMarkupRatio(item),
|
||
i,
|
||
]
|
||
);
|
||
}
|
||
|
||
await activateQuoteSheet(client, quoteSheetCode, input.createdBy || null);
|
||
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
const detail = await loadSheetDetail(quoteSheetCode);
|
||
/**
|
||
* 报价单已生效 ⇒ **事务提交之后**发一条「配送商销售价确认」申请(A 方向)。
|
||
* 旁路异步 + 吞异常:传递失败不得让建单失败;出网也绝不在事务内。
|
||
* 口径(2026-10-18):本系统**不再**直接写对方成本价,由配送商审核通过后写他自己的。
|
||
*/
|
||
requestDeliveryReviewInBackground(detail?.branch_code, quoteSheetCode);
|
||
return detail;
|
||
}
|
||
|
||
/** 列表:默认当前执行中的报价单 */
|
||
export async function listQuoteSheets(
|
||
ctx?: TenantContext | null,
|
||
options: {
|
||
view?: 'active' | 'history' | 'all';
|
||
customerCode?: string;
|
||
limit?: number;
|
||
operatingBranchCode?: string | null;
|
||
} = {}
|
||
) {
|
||
const view = options.view || 'active';
|
||
const params: unknown[] = [];
|
||
let where = `WHERE 1=1${branchFilter(ctx, 'qs', params, options.operatingBranchCode)}`;
|
||
|
||
if (options.customerCode?.trim()) {
|
||
params.push(options.customerCode.trim());
|
||
where += ` AND EXISTS (
|
||
SELECT 1 FROM customer_quote_sheet_customers qsc
|
||
WHERE qsc.quote_sheet_code = qs.quote_sheet_code AND qsc.customer_code = $${params.length}
|
||
)`;
|
||
}
|
||
|
||
if (view === 'active') {
|
||
where += ` AND (
|
||
qs.approval_status = 30 AND qs.status = 1 AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
|
||
)`;
|
||
} else if (view === 'history') {
|
||
where += ` AND (
|
||
qs.approval_status = 40
|
||
OR qs.status IN (0, 3)
|
||
OR (qs.approval_status = 30 AND qs.expires_at IS NOT NULL AND qs.expires_at <= NOW())
|
||
)`;
|
||
}
|
||
|
||
params.push(Math.min(options.limit || 100, 500));
|
||
const result = await pool.query(
|
||
`SELECT qs.*,
|
||
b.branch_name,
|
||
(SELECT COUNT(*)::int FROM customer_quote_sheet_items WHERE quote_sheet_code = qs.quote_sheet_code) AS item_count,
|
||
(SELECT COUNT(*)::int FROM customer_quote_sheet_customers WHERE quote_sheet_code = qs.quote_sheet_code) AS customer_count,
|
||
(SELECT string_agg(cu.company_name, '、' ORDER BY cu.company_name)
|
||
FROM customer_quote_sheet_customers qsc
|
||
JOIN customers cu ON cu.customer_code = qsc.customer_code
|
||
WHERE qsc.quote_sheet_code = qs.quote_sheet_code) AS customer_names
|
||
FROM customer_quote_sheets qs
|
||
LEFT JOIN branches b ON b.branch_code = qs.branch_code
|
||
${where}
|
||
ORDER BY qs.version_no DESC, qs.created_at DESC
|
||
LIMIT $${params.length}`,
|
||
params
|
||
);
|
||
return result.rows;
|
||
}
|
||
|
||
export async function getQuoteSheet(
|
||
quoteSheetCode: string,
|
||
ctx?: TenantContext | null,
|
||
operatingBranchCode?: string | null
|
||
) {
|
||
const params: unknown[] = [quoteSheetCode];
|
||
const branchSql = branchFilter(ctx, 'customer_quote_sheets', params, operatingBranchCode);
|
||
const exists = await pool.query(
|
||
`SELECT quote_sheet_code FROM customer_quote_sheets WHERE quote_sheet_code = $1 ${branchSql}`,
|
||
params
|
||
);
|
||
if (!exists.rows.length) throw new Error('报价单不存在');
|
||
return loadSheetDetail(quoteSheetCode);
|
||
}
|
||
|
||
/** 提交报价单(兼容旧接口:草稿直接生效,无需审批) */
|
||
export async function submitQuoteSheetForApproval(input: {
|
||
quoteSheetCode: string;
|
||
remark?: string;
|
||
ctx?: TenantContext | null;
|
||
approvedBy?: string | null;
|
||
operatingBranchCode?: string | null;
|
||
}) {
|
||
const params: unknown[] = [input.quoteSheetCode];
|
||
const branchSql = branchFilter(input.ctx, 'customer_quote_sheets', params, input.operatingBranchCode);
|
||
const exists = await pool.query(
|
||
`SELECT quote_sheet_code FROM customer_quote_sheets
|
||
WHERE quote_sheet_code = $1 AND approval_status IN (10, 40) ${branchSql}`,
|
||
params
|
||
);
|
||
if (!exists.rows.length) throw new Error('报价单不存在或已生效');
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
await activateQuoteSheet(client, input.quoteSheetCode, input.approvedBy || null);
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
const detail = await loadSheetDetail(input.quoteSheetCode);
|
||
// 提交报价单(旧接口:提交即生效)⇒ 事务提交之后发申请给配送商审核(旁路,失败不影响审批)
|
||
requestDeliveryReviewInBackground(detail?.branch_code, input.quoteSheetCode);
|
||
return detail;
|
||
}
|
||
|
||
async function activateQuoteSheet(
|
||
client: import('pg').PoolClient,
|
||
quoteSheetCode: string,
|
||
approvedBy?: string | null
|
||
) {
|
||
const result = await client.query(
|
||
`UPDATE customer_quote_sheets
|
||
SET approval_status = 30,
|
||
approved_by = $2,
|
||
approved_at = NOW(),
|
||
status = 1,
|
||
effective_at = COALESCE(effective_at, NOW()),
|
||
expires_at = COALESCE(expires_at, NOW() + (
|
||
CASE quote_cycle
|
||
WHEN 'week' THEN INTERVAL '7 days'
|
||
WHEN 'half_month' THEN INTERVAL '15 days'
|
||
WHEN 'month' THEN INTERVAL '30 days'
|
||
WHEN 'half_year' THEN INTERVAL '180 days'
|
||
WHEN 'year' THEN INTERVAL '365 days'
|
||
ELSE INTERVAL '30 days'
|
||
END
|
||
)),
|
||
updated_at = NOW()
|
||
WHERE quote_sheet_code = $1
|
||
RETURNING *`,
|
||
[quoteSheetCode, approvedBy || null]
|
||
);
|
||
if (!result.rows.length) throw new Error('报价单不存在');
|
||
|
||
const sheet = result.rows[0];
|
||
await client.query(
|
||
`UPDATE customer_quote_sheets SET status = 3, updated_at = NOW()
|
||
WHERE quote_sheet_code <> $1 AND status = 1 AND approval_status = 30
|
||
AND branch_code IS NOT DISTINCT FROM $2
|
||
AND quote_sheet_code IN (
|
||
SELECT qsc1.quote_sheet_code FROM customer_quote_sheet_customers qsc1
|
||
WHERE qsc1.customer_code IN (
|
||
SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1
|
||
)
|
||
)`,
|
||
[quoteSheetCode, sheet.branch_code]
|
||
);
|
||
await materializeQuoteVersions(client, sheet);
|
||
return sheet;
|
||
}
|
||
|
||
/**
|
||
* 物化 `customer_quote_versions`(报价单明细 → 客户版本行,逐客户 × 逐 SKU 升版本)。
|
||
*
|
||
* 导出原因(2026-10-19):报价提议审批通过(`quotePriceProposalService.approvePriceProposal`)
|
||
* 同样改了生效单价格,必须在**同一事务内**物化版本 —— 复用本实现,禁止复制第二份。
|
||
*/
|
||
export async function materializeQuoteVersions(
|
||
client: import('pg').PoolClient,
|
||
sheet: {
|
||
quote_sheet_code: string;
|
||
quote_cycle: string | null;
|
||
expires_at: Date | null;
|
||
branch_code: string | null;
|
||
created_by: string | null;
|
||
},
|
||
options?: { expireSheetVersionsFirst?: boolean }
|
||
) {
|
||
if (options?.expireSheetVersionsFirst) {
|
||
await client.query(
|
||
`UPDATE customer_quote_versions SET status = 0, expired_at = NOW()
|
||
WHERE quote_sheet_code = $1 AND status = 1`,
|
||
[sheet.quote_sheet_code]
|
||
);
|
||
}
|
||
|
||
const [itemsResult, customersResult] = await Promise.all([
|
||
client.query(`SELECT * FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [sheet.quote_sheet_code]),
|
||
client.query(`SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1`, [
|
||
sheet.quote_sheet_code,
|
||
]),
|
||
]);
|
||
|
||
for (const customerRow of customersResult.rows) {
|
||
const customerCode = customerRow.customer_code as string;
|
||
for (const item of itemsResult.rows) {
|
||
const versionResult = await client.query(
|
||
`SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version
|
||
FROM customer_quote_versions WHERE customer_code = $1 AND sku_code = $2`,
|
||
[customerCode, item.sku_code]
|
||
);
|
||
const versionNo = Number(versionResult.rows[0]?.next_version) || 1;
|
||
const quoteVersionCode = newQuoteVersionCode();
|
||
|
||
await client.query(
|
||
`UPDATE customer_quote_versions SET status = 0, expired_at = NOW()
|
||
WHERE customer_code = $1 AND sku_code = $2 AND status = 1
|
||
AND branch_code IS NOT DISTINCT FROM $3`,
|
||
[customerCode, item.sku_code, sheet.branch_code]
|
||
);
|
||
|
||
await client.query(
|
||
`INSERT INTO customer_quote_versions
|
||
(quote_version_code, customer_code, sku_code, unit, price, version_no, source_type,
|
||
branch_code, created_by, status, approval_status, quote_cycle, expires_at, effective_at,
|
||
quote_sheet_code, approved_at)
|
||
VALUES ($1,$2,$3,$4,$5,$6,'quote_sheet',$7,$8,1,30,$9,$10,NOW(),$11,NOW())`,
|
||
[
|
||
quoteVersionCode,
|
||
customerCode,
|
||
item.sku_code,
|
||
item.unit,
|
||
Number(item.sale_price ?? item.price) || 0,
|
||
versionNo,
|
||
sheet.branch_code,
|
||
sheet.created_by,
|
||
sheet.quote_cycle,
|
||
sheet.expires_at,
|
||
sheet.quote_sheet_code,
|
||
]
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
async function assertQuoteSheetAccessible(
|
||
quoteSheetCode: string,
|
||
ctx?: TenantContext | null,
|
||
operatingBranchCode?: string | null
|
||
) {
|
||
const params: unknown[] = [quoteSheetCode];
|
||
const branchSql = branchFilter(ctx, 'customer_quote_sheets', params, operatingBranchCode);
|
||
const result = await pool.query(
|
||
`SELECT * FROM customer_quote_sheets WHERE quote_sheet_code = $1 ${branchSql}`,
|
||
params
|
||
);
|
||
if (!result.rows.length) throw new Error('报价单不存在');
|
||
return result.rows[0];
|
||
}
|
||
|
||
/** 修改执行中的报价单的入参(PUT /quote/sheets/:code 与「待审变更」共用) */
|
||
export type QuoteSheetUpdateInput = {
|
||
quoteSheetCode: string;
|
||
title?: string;
|
||
customerCodes?: string[];
|
||
items?: QuoteSheetItemInput[];
|
||
autoSalePriceByCost?: boolean;
|
||
quoteCycle?: string | null;
|
||
effectiveAt?: string | null;
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
};
|
||
|
||
/** 「仅执行中的报价单可修改」三连守卫(改价审核提交与审核通过应用共用,口径只此一份) */
|
||
export function assertQuoteSheetEditableForUpdate(existing: {
|
||
status: unknown;
|
||
approval_status: unknown;
|
||
expires_at?: Date | string | null;
|
||
}): void {
|
||
if (Number(existing.status) !== 1 || Number(existing.approval_status) !== 30) {
|
||
throw new Error('仅执行中的报价单可修改');
|
||
}
|
||
if (existing.expires_at && new Date(existing.expires_at) <= new Date()) {
|
||
throw new Error('报价单已过期,无法修改');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读「可修改的生效单」并过三连守卫(改价审核提交用;**只读**,不写库)。
|
||
* 返回原始 sheet 行(含 branch_code / version_no / auto_sale_price_by_cost)。
|
||
*/
|
||
export async function loadQuoteSheetForUpdate(
|
||
quoteSheetCode: string,
|
||
ctx?: TenantContext | null,
|
||
operatingBranchCode?: string | null
|
||
) {
|
||
const existing = await assertQuoteSheetAccessible(quoteSheetCode, ctx, operatingBranchCode);
|
||
assertQuoteSheetEditableForUpdate(existing as { status: unknown; approval_status: unknown; expires_at?: Date | null });
|
||
return existing;
|
||
}
|
||
|
||
/** 入参归一(客户去重、明细过滤空行/零价行 + 非空校验):apply 与待审提交共用 */
|
||
export function normalizeQuoteSheetUpdatePayload(input: {
|
||
customerCodes?: string[];
|
||
items?: QuoteSheetItemInput[];
|
||
}): { customerCodes: string[] | null; items: QuoteSheetItemInput[] | null } {
|
||
const customerCodes = input.customerCodes
|
||
? [...new Set(input.customerCodes.map((c) => c.trim()).filter(Boolean))]
|
||
: null;
|
||
const items = input.items
|
||
? input.items.filter((i) => i.sku_code?.trim() && readSalePrice(i) > 0)
|
||
: null;
|
||
if (customerCodes && !customerCodes.length) throw new Error('请至少选择一个客户');
|
||
if (items && !items.length) throw new Error('请至少添加一个商品');
|
||
return { customerCodes, items };
|
||
}
|
||
|
||
/**
|
||
* **应用**一次报价单修改(原 `updateQuoteSheet` 的全部动作,行为逐字不变)。
|
||
*
|
||
* @param options.client 传入时**在调用方事务内**执行(审核通过「单事务应用」用);
|
||
* 不传时自己 BEGIN/COMMIT/ROLLBACK(= 改造前行为,`updateQuoteSheet` 走这条)。
|
||
*/
|
||
export async function applyQuoteSheetUpdate(
|
||
input: QuoteSheetUpdateInput,
|
||
options?: { client?: import('pg').PoolClient }
|
||
) {
|
||
const existing = await assertQuoteSheetAccessible(
|
||
input.quoteSheetCode,
|
||
input.ctx,
|
||
input.operatingBranchCode
|
||
);
|
||
assertQuoteSheetEditableForUpdate(existing as { status: unknown; approval_status: unknown; expires_at?: Date | null });
|
||
|
||
const { customerCodes, items } = normalizeQuoteSheetUpdatePayload(input);
|
||
const { quoteCycle, effectiveAt, expiresAt } = resolveQuoteSheetUpdateDates(existing, input);
|
||
|
||
const client = options?.client ?? (await pool.connect());
|
||
const ownsClient = !options?.client;
|
||
try {
|
||
if (ownsClient) await client.query('BEGIN');
|
||
|
||
await client.query(
|
||
`UPDATE customer_quote_sheets
|
||
SET title = COALESCE($2, title),
|
||
quote_cycle = $3,
|
||
effective_at = $4,
|
||
expires_at = $5,
|
||
auto_sale_price_by_cost = COALESCE($6, auto_sale_price_by_cost),
|
||
reminder_sent_at = NULL,
|
||
updated_at = NOW()
|
||
WHERE quote_sheet_code = $1`,
|
||
[
|
||
input.quoteSheetCode,
|
||
input.title !== undefined ? input.title?.trim() || null : null,
|
||
quoteCycle,
|
||
effectiveAt.toISOString(),
|
||
expiresAt ? expiresAt.toISOString() : null,
|
||
input.autoSalePriceByCost === undefined ? null : Boolean(input.autoSalePriceByCost),
|
||
]
|
||
);
|
||
|
||
if (customerCodes) {
|
||
const branchCode = existing.branch_code as string;
|
||
await assertCustomersInBranch(customerCodes, branchCode);
|
||
await client.query(`DELETE FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1`, [
|
||
input.quoteSheetCode,
|
||
]);
|
||
for (const customerCode of customerCodes) {
|
||
await client.query(
|
||
`INSERT INTO customer_quote_sheet_customers (quote_sheet_code, customer_code) VALUES ($1, $2)`,
|
||
[input.quoteSheetCode, customerCode]
|
||
);
|
||
}
|
||
}
|
||
|
||
if (items) {
|
||
await client.query(`DELETE FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [
|
||
input.quoteSheetCode,
|
||
]);
|
||
for (let i = 0; i < items.length; i += 1) {
|
||
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)`,
|
||
[
|
||
input.quoteSheetCode,
|
||
item.sku_code.trim(),
|
||
item.sku_name?.trim() || null,
|
||
item.unit?.trim() || null,
|
||
readSalePrice(item),
|
||
readCostPrice(item),
|
||
readSalePrice(item),
|
||
readMarkupRatio(item),
|
||
i,
|
||
]
|
||
);
|
||
}
|
||
}
|
||
|
||
const sheetResult = await client.query(`SELECT * FROM customer_quote_sheets WHERE quote_sheet_code = $1`, [
|
||
input.quoteSheetCode,
|
||
]);
|
||
const sheet = sheetResult.rows[0];
|
||
await materializeQuoteVersions(client, sheet, { expireSheetVersionsFirst: true });
|
||
|
||
if (ownsClient) await client.query('COMMIT');
|
||
} catch (error) {
|
||
if (ownsClient) await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
if (ownsClient) client.release();
|
||
}
|
||
|
||
return loadSheetDetail(input.quoteSheetCode);
|
||
}
|
||
|
||
/**
|
||
* 修改执行中的报价单(仅影响后续下单取价,历史订单明细不变)。
|
||
*
|
||
* ⚠️ 行为与改造前**逐字一致**:本函数就是 `applyQuoteSheetUpdate` 的薄封装。
|
||
* 「价格相关改动需审核」的分流在路由/变更单服务里,不在这里(回滚开关时仍走本函数)。
|
||
*/
|
||
export async function updateQuoteSheet(input: QuoteSheetUpdateInput) {
|
||
return applyQuoteSheetUpdate(input);
|
||
}
|
||
|
||
export async function setQuoteSheetAutoSalePriceByCost(input: {
|
||
quoteSheetCode: string;
|
||
enabled: boolean;
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
}) {
|
||
const existing = await assertQuoteSheetAccessible(
|
||
input.quoteSheetCode,
|
||
input.ctx,
|
||
input.operatingBranchCode
|
||
);
|
||
if (Number(existing.status) !== 1 || Number(existing.approval_status) !== 30) {
|
||
throw new Error('仅执行中的报价单可修改');
|
||
}
|
||
if (existing.expires_at && new Date(existing.expires_at) <= new Date()) {
|
||
throw new Error('报价单已过期,无法修改');
|
||
}
|
||
await pool.query(
|
||
`UPDATE customer_quote_sheets
|
||
SET auto_sale_price_by_cost = $2, updated_at = NOW()
|
||
WHERE quote_sheet_code = $1`,
|
||
[input.quoteSheetCode, input.enabled]
|
||
);
|
||
return loadSheetDetail(input.quoteSheetCode);
|
||
}
|
||
|
||
/** 向执行中的报价单追加/更新 SKU 价格(合并已有明细,不覆盖其他商品) */
|
||
export async function appendSkuPricesToQuoteSheet(input: {
|
||
quoteSheetCode: string;
|
||
items: QuoteSheetItemInput[];
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
}) {
|
||
const newItems = input.items.filter((i) => i.sku_code?.trim() && readSalePrice(i) > 0);
|
||
if (!newItems.length) throw new Error('请提供有效的商品与价格');
|
||
|
||
const detail = await getQuoteSheet(input.quoteSheetCode, input.ctx, input.operatingBranchCode);
|
||
const existing = Array.isArray(detail.items) ? detail.items : [];
|
||
const merged = new Map<string, QuoteSheetItemInput>();
|
||
|
||
for (const row of existing) {
|
||
const skuCode = String(row.sku_code || '').trim();
|
||
if (!skuCode) continue;
|
||
merged.set(skuCode, {
|
||
sku_code: skuCode,
|
||
sku_name: row.sku_name?.trim() || row.catalog_name?.trim() || undefined,
|
||
unit: row.unit?.trim() || undefined,
|
||
price: Number(row.sale_price ?? row.price) || 0,
|
||
sale_price: Number(row.sale_price ?? row.price) || 0,
|
||
cost_price: Number(row.cost_price) || 0,
|
||
markup_ratio: row.markup_ratio == null ? null : Number(row.markup_ratio),
|
||
});
|
||
}
|
||
|
||
for (const item of newItems) {
|
||
const skuCode = item.sku_code.trim();
|
||
merged.set(skuCode, {
|
||
sku_code: skuCode,
|
||
sku_name: item.sku_name?.trim() || merged.get(skuCode)?.sku_name,
|
||
unit: item.unit?.trim() || merged.get(skuCode)?.unit,
|
||
price: readSalePrice(item),
|
||
sale_price: readSalePrice(item),
|
||
cost_price:
|
||
item.cost_price !== undefined
|
||
? readCostPrice(item)
|
||
: merged.get(skuCode)?.cost_price || 0,
|
||
markup_ratio:
|
||
item.markup_ratio !== undefined
|
||
? readMarkupRatio(item)
|
||
: merged.get(skuCode)?.markup_ratio ?? null,
|
||
});
|
||
}
|
||
|
||
return updateQuoteSheet({
|
||
quoteSheetCode: input.quoteSheetCode,
|
||
items: [...merged.values()].filter((i) => readSalePrice(i) > 0),
|
||
ctx: input.ctx,
|
||
operatingBranchCode: input.operatingBranchCode,
|
||
});
|
||
}
|
||
|
||
type QuoteDb = Pick<import('pg').PoolClient, 'query'>;
|
||
|
||
/**
|
||
* 客户生效报价单(与列表读回对齐):
|
||
* 优先同 branch → 再允许 branch 为空的共用单;按 version_no / updated_at 降序。
|
||
*/
|
||
export async function resolveActiveQuoteSheetForCustomer(
|
||
db: QuoteDb,
|
||
customerCode: string,
|
||
branchCode?: string | null
|
||
): Promise<string | null> {
|
||
const code = String(customerCode || '').trim();
|
||
if (!code) return null;
|
||
const branch = String(branchCode || '').trim() || null;
|
||
const sheetResult = await db.query(
|
||
`SELECT qs.quote_sheet_code
|
||
FROM customer_quote_sheets qs
|
||
WHERE qs.approval_status = 30
|
||
AND qs.status = 1
|
||
AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
|
||
AND EXISTS (
|
||
SELECT 1 FROM customer_quote_sheet_customers qsc
|
||
WHERE qsc.quote_sheet_code = qs.quote_sheet_code
|
||
AND qsc.customer_code = $1
|
||
)
|
||
AND (
|
||
$2::text IS NULL
|
||
OR qs.branch_code IS NOT DISTINCT FROM $2
|
||
OR qs.branch_code IS NULL
|
||
)
|
||
ORDER BY
|
||
CASE
|
||
WHEN $2::text IS NOT NULL AND qs.branch_code IS NOT DISTINCT FROM $2 THEN 0
|
||
WHEN qs.branch_code IS NULL THEN 1
|
||
ELSE 2
|
||
END,
|
||
qs.version_no DESC NULLS LAST,
|
||
qs.updated_at DESC NULLS LAST,
|
||
qs.created_at DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[code, branch]
|
||
);
|
||
return sheetResult.rows[0]?.quote_sheet_code
|
||
? String(sheetResult.rows[0].quote_sheet_code)
|
||
: null;
|
||
}
|
||
|
||
/** 客户生效报价单全量价目(小程序录单展示成本价/售价) */
|
||
export async function listActiveQuoteSheetPricesForCustomer(
|
||
db: QuoteDb,
|
||
customerCode: string,
|
||
branchCode?: string | null
|
||
): Promise<{
|
||
quote_sheet_code: string | null;
|
||
items: Array<{
|
||
sku_code: string;
|
||
sku_name: string;
|
||
unit: string;
|
||
cost_price: number;
|
||
sale_price: number;
|
||
category_code: string | null;
|
||
category_name: string | null;
|
||
}>;
|
||
}> {
|
||
const quoteSheetCode = await resolveActiveQuoteSheetForCustomer(db, customerCode, branchCode);
|
||
if (!quoteSheetCode) {
|
||
return { quote_sheet_code: null, items: [] };
|
||
}
|
||
|
||
const result = await db.query(
|
||
`SELECT i.sku_code,
|
||
COALESCE(NULLIF(TRIM(i.sku_name), ''), NULLIF(TRIM(s.sku_name), ''), '') AS sku_name,
|
||
COALESCE(NULLIF(TRIM(i.unit), ''), NULLIF(TRIM(s.unit), ''), '斤') AS unit,
|
||
COALESCE(i.cost_price, 0)::float AS cost_price,
|
||
COALESCE(NULLIF(i.sale_price, 0), NULLIF(i.price, 0), 0)::float AS sale_price,
|
||
s.category_code,
|
||
NULLIF(TRIM(cat.category_name), '') AS category_name
|
||
FROM customer_quote_sheet_items i
|
||
LEFT JOIN skus s ON s.sku_code = i.sku_code
|
||
LEFT JOIN categories cat ON cat.category_code = s.category_code
|
||
WHERE i.quote_sheet_code = $1
|
||
ORDER BY i.sort_order ASC NULLS LAST, i.sku_code ASC`,
|
||
[quoteSheetCode]
|
||
);
|
||
|
||
return {
|
||
quote_sheet_code: quoteSheetCode,
|
||
items: result.rows.map((row: any) => ({
|
||
sku_code: String(row.sku_code || '').trim(),
|
||
sku_name: String(row.sku_name || '').trim(),
|
||
unit: String(row.unit || '斤').trim() || '斤',
|
||
cost_price: Math.max(0, Number(row.cost_price) || 0),
|
||
sale_price: Math.max(0, Number(row.sale_price) || 0),
|
||
category_code: row.category_code ? String(row.category_code) : null,
|
||
category_name: row.category_name ? String(row.category_name) : null,
|
||
})).filter((row) => row.sku_code),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按客户生效报价单写入/更新 SKU 成本价(订单列表改成本落库)。
|
||
* - 更新该客户全部生效报价中该 SKU(避免写 A 读 B)
|
||
* - 无行则 INSERT 到主生效报价单(允许仅成本)
|
||
* - 无生效报价单:跳过(updated=0)
|
||
*/
|
||
export async function upsertCustomerQuoteItemCosts(
|
||
db: QuoteDb,
|
||
input: {
|
||
customerCode: string;
|
||
branchCode?: string | null;
|
||
items: Array<{
|
||
sku_code: string;
|
||
cost_price: number;
|
||
sale_price?: number;
|
||
sku_name?: string | null;
|
||
unit?: string | null;
|
||
}>;
|
||
/** 是否同步非零销售价;完成补空场景可限制为报价单销售价为空。 */
|
||
syncSalePrice?: boolean;
|
||
onlyIfSalePriceZero?: boolean;
|
||
}
|
||
): Promise<{ quote_sheet_code: string | null; updated: number; inserted: number }> {
|
||
const customerCode = String(input.customerCode || '').trim();
|
||
const branch = String(input.branchCode || '').trim() || null;
|
||
const syncSalePrice = input.syncSalePrice !== false;
|
||
const onlyIfSalePriceZero = input.onlyIfSalePriceZero === true;
|
||
const items = (input.items || [])
|
||
.map((row) => ({
|
||
sku_code: String(row.sku_code || '').trim(),
|
||
cost_price: Math.max(0, Number(row.cost_price) || 0),
|
||
sale_price: Math.max(0, Number(row.sale_price) || 0),
|
||
sku_name: row.sku_name ? String(row.sku_name).trim() : null,
|
||
unit: row.unit ? String(row.unit).trim() : null,
|
||
}))
|
||
.filter((row) => row.sku_code && (row.cost_price > 0 || row.sale_price > 0));
|
||
if (!customerCode || !items.length) {
|
||
return { quote_sheet_code: null, updated: 0, inserted: 0 };
|
||
}
|
||
|
||
const quoteSheetCode = await resolveActiveQuoteSheetForCustomer(db, customerCode, branch);
|
||
if (!quoteSheetCode) {
|
||
return { quote_sheet_code: null, updated: 0, inserted: 0 };
|
||
}
|
||
|
||
let updated = 0;
|
||
let inserted = 0;
|
||
for (const item of items) {
|
||
const upd = await db.query(
|
||
`UPDATE customer_quote_sheet_items i
|
||
SET cost_price = CASE
|
||
WHEN $1::numeric > 0 THEN $1::numeric
|
||
ELSE i.cost_price
|
||
END,
|
||
sale_price = CASE
|
||
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 $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
|
||
END
|
||
FROM customer_quote_sheets qs
|
||
INNER JOIN customer_quote_sheet_customers qsc
|
||
ON qsc.quote_sheet_code = qs.quote_sheet_code
|
||
WHERE i.quote_sheet_code = qs.quote_sheet_code
|
||
AND i.sku_code = $3
|
||
AND qsc.customer_code = $4
|
||
AND qs.approval_status = 30
|
||
AND qs.status = 1
|
||
AND (qs.expires_at IS NULL OR qs.expires_at > NOW())
|
||
AND (
|
||
$5::text IS NULL
|
||
OR qs.branch_code IS NOT DISTINCT FROM $5
|
||
OR qs.branch_code IS NULL
|
||
)`,
|
||
[item.cost_price, item.sale_price, item.sku_code, customerCode, branch, syncSalePrice, onlyIfSalePriceZero]
|
||
);
|
||
const n = Number(upd.rowCount) || 0;
|
||
if (n > 0) {
|
||
updated += n;
|
||
continue;
|
||
}
|
||
|
||
const sortResult = await db.query(
|
||
`SELECT COALESCE(MAX(sort_order), -1) + 1 AS next_sort
|
||
FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`,
|
||
[quoteSheetCode]
|
||
);
|
||
const nextSort = Number(sortResult.rows[0]?.next_sort) || 0;
|
||
const sale = item.sale_price > 0 ? item.sale_price : 0;
|
||
await db.query(
|
||
`INSERT INTO customer_quote_sheet_items
|
||
(quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $5, $7)`,
|
||
[
|
||
quoteSheetCode,
|
||
item.sku_code,
|
||
item.sku_name,
|
||
item.unit || '斤',
|
||
sale,
|
||
item.cost_price,
|
||
nextSort,
|
||
]
|
||
);
|
||
inserted += 1;
|
||
}
|
||
|
||
return { quote_sheet_code: quoteSheetCode, updated, inserted };
|
||
}
|
||
|
||
/** 删除报价单(停用取价,不影响已生成订单的价格快照) */
|
||
export async function deleteQuoteSheet(input: {
|
||
quoteSheetCode: string;
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
}) {
|
||
await assertQuoteSheetAccessible(input.quoteSheetCode, input.ctx, input.operatingBranchCode);
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
await client.query(
|
||
`UPDATE customer_quote_versions SET status = 0, expired_at = NOW()
|
||
WHERE quote_sheet_code = $1 AND status = 1`,
|
||
[input.quoteSheetCode]
|
||
);
|
||
await client.query(
|
||
`UPDATE customer_quote_sheets
|
||
SET status = 0,
|
||
expires_at = COALESCE(expires_at, NOW()),
|
||
updated_at = NOW()
|
||
WHERE quote_sheet_code = $1`,
|
||
[input.quoteSheetCode]
|
||
);
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
return { quote_sheet_code: input.quoteSheetCode, deleted: true };
|
||
}
|
||
|
||
/** 审批报价单(兼容旧接口:直接通过并生效,驳回仍保留) */
|
||
export async function approveQuoteSheet(input: {
|
||
quoteSheetCode: string;
|
||
approved: boolean;
|
||
remark?: string;
|
||
approvedBy?: string | null;
|
||
ctx?: TenantContext | null;
|
||
operatingBranchCode?: string | null;
|
||
}) {
|
||
if (input.approved) {
|
||
const params: unknown[] = [input.quoteSheetCode];
|
||
const branchSql = branchFilter(input.ctx, 'customer_quote_sheets', params, input.operatingBranchCode);
|
||
const exists = await pool.query(
|
||
`SELECT quote_sheet_code FROM customer_quote_sheets WHERE quote_sheet_code = $1 ${branchSql}`,
|
||
params
|
||
);
|
||
if (!exists.rows.length) throw new Error('报价单不存在');
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
|
||
await activateQuoteSheet(client, input.quoteSheetCode, input.approvedBy || null);
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
const detail = await loadSheetDetail(input.quoteSheetCode);
|
||
// 审批通过 ⇒ 事务提交之后再发申请给配送商审核(旁路,失败不影响审批结论)
|
||
requestDeliveryReviewInBackground(detail?.branch_code, input.quoteSheetCode);
|
||
return detail;
|
||
}
|
||
|
||
const nextStatus = 40;
|
||
const params: unknown[] = [input.quoteSheetCode, nextStatus, input.remark || null, input.approvedBy || null];
|
||
const branchSql = branchFilter(input.ctx, 'customer_quote_sheets', params, input.operatingBranchCode);
|
||
const result = await pool.query(
|
||
`UPDATE customer_quote_sheets
|
||
SET approval_status = $2,
|
||
approval_remark = $3,
|
||
approved_by = $4,
|
||
status = 0,
|
||
updated_at = NOW()
|
||
WHERE quote_sheet_code = $1 ${branchSql}
|
||
RETURNING quote_sheet_code`,
|
||
params
|
||
);
|
||
if (!result.rows.length) throw new Error('报价单不存在');
|
||
return loadSheetDetail(input.quoteSheetCode);
|
||
}
|
||
|
||
/** 到期前 1 天提醒运营更新报价 */
|
||
export async function scanQuoteSheetReminders(
|
||
ctx?: TenantContext | null,
|
||
operatingBranchCode?: string | null
|
||
) {
|
||
const params: unknown[] = [];
|
||
const branchSql =
|
||
ctx || operatingBranchCode ? branchFilter(ctx, 'qs', params, operatingBranchCode) : '';
|
||
const result = await pool.query(
|
||
`SELECT qs.quote_sheet_code, qs.title, qs.version_no, qs.expires_at, qs.branch_code,
|
||
(SELECT string_agg(cu.company_name, '、')
|
||
FROM customer_quote_sheet_customers qsc
|
||
JOIN customers cu ON cu.customer_code = qsc.customer_code
|
||
WHERE qsc.quote_sheet_code = qs.quote_sheet_code) AS customer_names
|
||
FROM customer_quote_sheets qs
|
||
WHERE qs.status = 1 AND qs.approval_status = 30
|
||
AND qs.expires_at IS NOT NULL
|
||
AND qs.expires_at > NOW()
|
||
AND qs.expires_at <= NOW() + INTERVAL '1 day'
|
||
AND qs.reminder_sent_at IS NULL
|
||
${branchSql}`,
|
||
params
|
||
);
|
||
|
||
let sent = 0;
|
||
for (const row of result.rows) {
|
||
const expireDate = new Date(row.expires_at).toLocaleDateString('zh-CN');
|
||
await notifyRoleUsers({
|
||
roles: ['admin', 'operator', 'super_admin'],
|
||
notifyType: 'quote_expiry_reminder',
|
||
title: '报价单即将到期',
|
||
content: `报价单 ${row.quote_sheet_code}(${row.title || `V${row.version_no}`})将于 ${expireDate} 到期,客户:${row.customer_names || '-'}。如未更新将自动顺延当前报价。`,
|
||
branchCode: row.branch_code,
|
||
});
|
||
await pool.query(
|
||
`UPDATE customer_quote_sheets SET reminder_sent_at = NOW(), updated_at = NOW() WHERE quote_sheet_code = $1`,
|
||
[row.quote_sheet_code]
|
||
);
|
||
sent += 1;
|
||
}
|
||
return { sent };
|
||
}
|
||
|
||
/** 到期未更新则顺延报价周期;顺延前将刚结束周期快照进历史(status=3) */
|
||
export async function scanQuoteSheetRollover(
|
||
ctx?: TenantContext | null,
|
||
operatingBranchCode?: string | null
|
||
) {
|
||
const params: unknown[] = [];
|
||
const branchSql =
|
||
ctx || operatingBranchCode ? branchFilter(ctx, 'qs', params, operatingBranchCode) : '';
|
||
const expired = await pool.query(
|
||
`SELECT * FROM customer_quote_sheets qs
|
||
WHERE qs.status = 1 AND qs.approval_status = 30
|
||
AND qs.expires_at IS NOT NULL AND qs.expires_at <= NOW()
|
||
${branchSql}`,
|
||
params
|
||
);
|
||
|
||
let rolled = 0;
|
||
for (const sheet of expired.rows) {
|
||
const replacement = await pool.query(
|
||
`SELECT qs.quote_sheet_code FROM customer_quote_sheets qs
|
||
WHERE qs.quote_sheet_code <> $1
|
||
AND qs.approval_status = 30
|
||
AND qs.status IN (0, 1)
|
||
AND qs.created_at > $2
|
||
AND EXISTS (
|
||
SELECT 1 FROM customer_quote_sheet_customers a
|
||
JOIN customer_quote_sheet_customers b ON b.customer_code = a.customer_code
|
||
WHERE a.quote_sheet_code = qs.quote_sheet_code AND b.quote_sheet_code = $1
|
||
)
|
||
LIMIT 1`,
|
||
[sheet.quote_sheet_code, sheet.approved_at || sheet.created_at]
|
||
);
|
||
if (replacement.rows.length) continue;
|
||
|
||
const nextExpires = computeExpiresAt(new Date(), sheet.quote_cycle);
|
||
if (!nextExpires) continue;
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
await archiveQuoteSheetSnapshotForRollover(client, sheet as QuoteSheetRolloverSource);
|
||
await client.query(
|
||
`UPDATE customer_quote_sheets
|
||
SET expires_at = $2, rollover_count = rollover_count + 1,
|
||
reminder_sent_at = NULL, updated_at = NOW()
|
||
WHERE quote_sheet_code = $1`,
|
||
[sheet.quote_sheet_code, nextExpires.toISOString()]
|
||
);
|
||
await client.query(
|
||
`UPDATE customer_quote_versions
|
||
SET expires_at = $2
|
||
WHERE quote_sheet_code = $1 AND status = 1`,
|
||
[sheet.quote_sheet_code, nextExpires.toISOString()]
|
||
);
|
||
await client.query('COMMIT');
|
||
rolled += 1;
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
return { rolled };
|
||
}
|
||
|
||
export type QuoteSheetRolloverSource = {
|
||
quote_sheet_code: string;
|
||
title?: string | null;
|
||
quote_cycle?: string | null;
|
||
effective_at?: Date | string | null;
|
||
expires_at?: Date | string | null;
|
||
approved_by?: string | null;
|
||
approved_at?: Date | string | null;
|
||
branch_code?: string | null;
|
||
created_by?: string | null;
|
||
rollover_count?: number | null;
|
||
auto_sale_price_by_cost?: boolean | null;
|
||
};
|
||
|
||
/** 构造顺延归档头字段(可单测);不写库 */
|
||
export function buildQuoteRolloverArchiveHeader(
|
||
live: QuoteSheetRolloverSource,
|
||
archiveCode: string,
|
||
versionNo: number
|
||
) {
|
||
const titleBase = String(live.title || '').trim() || `报价单 V${versionNo}`;
|
||
return {
|
||
quote_sheet_code: archiveCode,
|
||
title: titleBase,
|
||
version_no: versionNo,
|
||
quote_cycle: live.quote_cycle || null,
|
||
effective_at: live.effective_at || null,
|
||
expires_at: live.expires_at || null,
|
||
status: 3,
|
||
approval_status: 30,
|
||
approved_by: live.approved_by || null,
|
||
approved_at: live.approved_at || null,
|
||
rollover_count: Number(live.rollover_count) || 0,
|
||
auto_sale_price_by_cost: Boolean(live.auto_sale_price_by_cost),
|
||
parent_sheet_code: live.quote_sheet_code,
|
||
branch_code: live.branch_code || null,
|
||
created_by: live.created_by || null,
|
||
};
|
||
}
|
||
|
||
async function archiveQuoteSheetSnapshotForRollover(
|
||
client: import('pg').PoolClient,
|
||
live: QuoteSheetRolloverSource
|
||
) {
|
||
const branchCode = live.branch_code || null;
|
||
const versionResult = await client.query(
|
||
`SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version
|
||
FROM customer_quote_sheets
|
||
WHERE branch_code IS NOT DISTINCT FROM $1`,
|
||
[branchCode]
|
||
);
|
||
const versionNo = Number(versionResult.rows[0]?.next_version) || 1;
|
||
const archiveCode = newSheetCode();
|
||
const header = buildQuoteRolloverArchiveHeader(live, archiveCode, versionNo);
|
||
|
||
const toIso = (v: Date | string | null | undefined) => {
|
||
if (v == null) return null;
|
||
if (v instanceof Date) return v.toISOString();
|
||
const d = new Date(v);
|
||
return Number.isNaN(d.getTime()) ? null : d.toISOString();
|
||
};
|
||
|
||
await client.query(
|
||
`INSERT INTO customer_quote_sheets
|
||
(quote_sheet_code, title, version_no, quote_cycle, effective_at, expires_at,
|
||
status, approval_status, approved_by, approved_at, rollover_count, auto_sale_price_by_cost,
|
||
parent_sheet_code, branch_code, created_by, created_at, updated_at)
|
||
VALUES ($1,$2,$3,$4,$5,$6,3,30,$7,$8,$9,$10,$11,$12,$13,NOW(),NOW())`,
|
||
[
|
||
header.quote_sheet_code,
|
||
header.title,
|
||
header.version_no,
|
||
header.quote_cycle,
|
||
toIso(header.effective_at as Date | string | null),
|
||
toIso(header.expires_at as Date | string | null),
|
||
header.approved_by,
|
||
toIso(header.approved_at as Date | string | null),
|
||
header.rollover_count,
|
||
header.auto_sale_price_by_cost,
|
||
header.parent_sheet_code,
|
||
header.branch_code,
|
||
header.created_by,
|
||
]
|
||
);
|
||
|
||
await client.query(
|
||
`INSERT INTO customer_quote_sheet_customers (quote_sheet_code, customer_code)
|
||
SELECT $1, customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $2`,
|
||
[archiveCode, live.quote_sheet_code]
|
||
);
|
||
|
||
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)
|
||
SELECT $1, sku_code, sku_name, unit, price, cost_price, sale_price, markup_ratio, sort_order
|
||
FROM customer_quote_sheet_items
|
||
WHERE quote_sheet_code = $2`,
|
||
[archiveCode, live.quote_sheet_code]
|
||
);
|
||
|
||
return archiveCode;
|
||
}
|
||
|
||
/**
|
||
* 报价单生效/提交/审批后:**请配送商审核销售价**(A 方向提议),不再直接推对方成本价。
|
||
* 旁路异步 + 吞异常:传递失败不影响本系统自己的生效动作(对方审核通过后才写他自己的成本价)。
|
||
*/
|
||
function requestDeliveryReviewInBackground(branchCode: string | null | undefined, quoteSheetCode: string) {
|
||
void import('./quoteSheetEditService')
|
||
.then(({ requestDeliveryReviewForSheet }) =>
|
||
requestDeliveryReviewForSheet({ quoteSheetCode, branchCode: branchCode || null })
|
||
)
|
||
.catch(() => {
|
||
// 开关关闭 / 主系统不可用 / 无 MAIN_ 客户:都不影响本系统的报价单状态
|
||
});
|
||
}
|