开发者 2026-10-12:「不能只看现在脚本修复的只是暂时的,后续不能出问题才是对的」。
⇒ 对两类问题做**写入点全表审计**,把还没覆盖的口子补齐,并加"新写入点漏了也能自愈"的兜底。
一、抵扣后"需求归零的待采单"没人取消 ⇒ 订单卡 30 待备货
① 写入侧补口:`bidRoundService`(发标前的补偿抵扣,分配路线之外唯一还会新落抵扣的点)
改为调统一入口 `syncZeroDemandPurchasesAfterCover(orderCode, branch)`(自建租户上下文/事务);
② 判据侧收口:新增 `countPurchasesWithOpenDemand` —— 只有"证据确凿(有挂链/source_id,
且这些明细全都没有缺口)"的待采单才排除。**推进器与回退器同改**(只改一处会状态来回抖);
`countPendingPurchases` 全局口径不动(采购面/列表照旧看全部待采单);
③ 兜底自愈:`reconcileOrderWorkflowStatus` 每轮先归零再判推进 ⇒ 将来任何新写入点漏了同步,
最迟 15 分钟自动纠正,不需要人工改数据。
二、退货/删行残留拣货行
写入点全表审计(退货红冲 / 改明细标退货 / 取消履约删行 / 主系统删单跟随 / 任何未来新路径)
⇒ 实时清 + 读取与完成校验同口径 + 对账兜底删;另外确认**建拣货行的取数本就过滤 is_returned**
(`pickingSortRouteService` / 修复扫描),所以不会"清完又被建回来"。
真库故障注入(FIXTEST_DEMAND_A/B,用后即删、残留 0):
· A 需求被抵扣吃光、待采单还在(模拟"某路径漏了同步")⇒ 对账 steps
["需求归零的待采自采单已自动取消 1","全部备货完成,订单进入待验收","验收/加工完成→待分拣(PK…)"]
采购单 40/0.00/需求归零,自动取消;订单 30→45 ✅ 自愈
· B 仍有缺口(cover 2 < qty 5)⇒「尚有 1 个采购单未完成」、状态保持 30、采购单仍 10 且缩量到 3 ✅ 没放宽坏
· 夹具:已退货未拣的行被删、有效行与"已退货已拣"的行保留 ✅
顺带核对(AGENTS.md 2026-10-12 更新 FIFO 为"入库时间优先"):实际扣库 / 抵扣批次计划 /
分拣批次卡三处 ORDER BY 已一致(created_at ASC, expiry_date ASC NULLS FIRST),无口径漂移。
测试:inventoryFullCoverFulfillment 追加 6 例(写入点三处 + 统一入口 + 判据保守性 + 推进/回退同改 +
全局口径未动);bidInventoryCover 适配新调用(并断言"抵扣后确实同步")。
全量 25 个失败文件与基线一致(0 新增失败);门禁 8/1/1(check-ai-cost 既定红、verify-facts 无 psql)。
3208 lines
112 KiB
TypeScript
3208 lines
112 KiB
TypeScript
import { pool } from '../db';
|
||
import { getTenantDbStore } from './tenantDbContext';
|
||
import {
|
||
fetchCategoryRows,
|
||
getSupplierBindingLookupCodes,
|
||
type CategoryRow,
|
||
} from './categoryCatalogService';
|
||
import {
|
||
assertBidEnabled,
|
||
getBidSettings,
|
||
resolveBidPeriodWindow,
|
||
computeNextBidPeriodWindow,
|
||
resolveQuoteRespondDeadline,
|
||
resolveScheduledOpenAt,
|
||
isQueuedDraftWaiting,
|
||
type BidSettings,
|
||
} from './bidConfigService';
|
||
import { notifySuppliersBidOpened } from './bidAwardService';
|
||
import { suggestAwardsForSettings, suggestLowestQuotesPure } from './bidAwardScoringService';
|
||
import { applyStockCoverForOrder } from './inventoryStockCoverService';
|
||
import {
|
||
ensureBranchCategoryCode,
|
||
stripBranchCategoryPrefix,
|
||
} from './categoryCodePolicy';
|
||
import { formatChinaDate, formatChinaHm } from '../utils/chinaDate';
|
||
import type { PoolClient } from 'pg';
|
||
|
||
export type BidCycleMode = 'per_order' | 'period';
|
||
export type BidScopeType = 'sku' | 'category';
|
||
|
||
/**
|
||
* `tryAutoAwardAndAllocate` 在外层事务内运行时的保存点名。
|
||
* 与 tenantSchemaService 的 'sp_tenant_schema' 刻意区分,避免同名嵌套。
|
||
*
|
||
* 【P0 修复背景】本函数会被「订单分配事务内」调用
|
||
* (`orderAllocationService` → `resolvePerOrderAutoBidGate` → 此处)。
|
||
* 请求级共享连接下 `pool.connect()` 返回的是【同一条连接】的 facade
|
||
* (`db.ts:283-289`,`release()` 为空操作),裸 `BEGIN/COMMIT` 会把外层事务提前提交:
|
||
*
|
||
* · 外层 `SELECT … FOR UPDATE` 的行锁提前释放 → 并发重复分配窗口被打开(重复建采购/备货单)
|
||
* · 外层 `COMMIT` / `ROLLBACK` 双双退化为空操作
|
||
* · 外层仍写「订单分配失败,已回滚」→ **假回滚**,半成品数据静默残留
|
||
*
|
||
* 因此照搬项目既有范式 `tenantSchemaService.ts:112-145`
|
||
* (其注释原文:「若复用请求级连接且外层已在事务中:用 SAVEPOINT,禁止裸 ROLLBACK 冲掉外层写入」):
|
||
* 外层有事务时用 SAVEPOINT / RELEASE / ROLLBACK TO,否则维持原 BEGIN/COMMIT/ROLLBACK。
|
||
* 判定条件与 `tenantSchemaService` 完全一致,避免两套判据。
|
||
* 见 docs/design/20260918-nested-txn-and-slot-deadlock.md
|
||
*/
|
||
const AUTO_AWARD_SAVEPOINT = 'sp_bid_auto_award';
|
||
|
||
function httpError(message: string, status = 400, code = 'invalid_request') {
|
||
return Object.assign(new Error(message), { status, code });
|
||
}
|
||
|
||
/** 轮次是否仍处于中标后手调 hold(未放行且未到点) */
|
||
export function isAllocationHoldActive(round: {
|
||
allocation_hold_until?: string | Date | null;
|
||
allocation_hold_released_at?: string | Date | null;
|
||
}): boolean {
|
||
if (round.allocation_hold_released_at) return false;
|
||
const until = round.allocation_hold_until;
|
||
if (!until) return false;
|
||
const t = until instanceof Date ? until.getTime() : new Date(until).getTime();
|
||
return Number.isFinite(t) && t > Date.now();
|
||
}
|
||
|
||
/** 轮次编号:东八区时间戳 + 当日序号,如 20260811175345-003 */
|
||
async function genRoundCode(client?: PoolClient): Promise<string> {
|
||
const db = client || pool;
|
||
const now = new Date();
|
||
const ymd = formatChinaDate(now).replace(/-/g, '');
|
||
const parts = new Intl.DateTimeFormat('en-GB', {
|
||
timeZone: 'Asia/Shanghai',
|
||
hour: '2-digit',
|
||
minute: '2-digit',
|
||
second: '2-digit',
|
||
hour12: false,
|
||
}).formatToParts(now);
|
||
const get = (type: Intl.DateTimeFormatPartTypes) =>
|
||
parts.find((p) => p.type === type)?.value?.padStart(2, '0') || '00';
|
||
const stamp = `${ymd}${get('hour')}${get('minute')}${get('second')}`;
|
||
|
||
const cnt = await db.query(
|
||
`SELECT COUNT(*)::int AS c
|
||
FROM bid_rounds
|
||
WHERE round_code LIKE $1`,
|
||
[`${ymd}%`]
|
||
);
|
||
const seq = (Number(cnt.rows[0]?.c) || 0) + 1;
|
||
return `${stamp}-${String(seq).padStart(3, '0')}`;
|
||
}
|
||
|
||
async function expireOverdueInvitations(roundId: string) {
|
||
await pool.query(
|
||
`UPDATE bid_invitations
|
||
SET status = 'expired'
|
||
WHERE round_id = $1
|
||
AND status = 'pending'
|
||
AND respond_deadline < NOW()`,
|
||
[roundId]
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 自动中标闸门。
|
||
* - 截止前:仅 auto_award_lowest 开且全员已报价 → 可提前中标
|
||
* - 截止后:有报价则一律中标(忽略开关);0 报价不中标
|
||
* - 已过截止且尚有 pending:先出局再按已有报价中标
|
||
*/
|
||
export function evaluateAutoAwardGate(input: {
|
||
autoAwardLowest: boolean;
|
||
status: string;
|
||
pending: number;
|
||
quoted: number;
|
||
deadlinePassed: boolean;
|
||
}): { proceed: boolean; reason: string } {
|
||
if (input.status === 'awarded') return { proceed: false, reason: 'already_awarded' };
|
||
if (input.status !== 'open' && input.status !== 'closed') {
|
||
return { proceed: false, reason: `status_${input.status}` };
|
||
}
|
||
if (input.quoted <= 0) return { proceed: false, reason: 'no_quotes' };
|
||
// 截止后:有报价必中标(开关无效)
|
||
if (input.deadlinePassed) {
|
||
return { proceed: true, reason: 'ok' };
|
||
}
|
||
// 截止前:仅开关开且无人待报
|
||
if (!input.autoAwardLowest) return { proceed: false, reason: 'disabled' };
|
||
if (input.pending > 0) {
|
||
return { proceed: false, reason: 'waiting_quotes' };
|
||
}
|
||
return { proceed: true, reason: 'ok' };
|
||
}
|
||
|
||
/** 截止且整轮 0 报价:不中标,放行智能分配(找供应商 / 自采) */
|
||
export function shouldReleaseEmptyQuoteRound(input: {
|
||
deadlinePassed: boolean;
|
||
quoted: number;
|
||
}): boolean {
|
||
return Boolean(input.deadlinePassed) && Number(input.quoted) <= 0;
|
||
}
|
||
|
||
/**
|
||
* 截止后自动中标语义失败:应取消轮次并降级智能分配(勿每分钟空转)。
|
||
* 闸门未放行 / 未知瞬时错误返回 false,留给下轮重试。
|
||
*/
|
||
export function isUnrecoverableAutoAwardFailure(reason: string): boolean {
|
||
const r = String(reason || '').trim();
|
||
if (!r || r === 'ok') return false;
|
||
if (
|
||
[
|
||
'no_round',
|
||
'not_found',
|
||
'already_awarded',
|
||
'disabled',
|
||
'waiting_quotes',
|
||
'no_quotes',
|
||
'fallback_smart_alloc',
|
||
].includes(r)
|
||
) {
|
||
return false;
|
||
}
|
||
if (r.startsWith('status_')) return false;
|
||
if (r.includes('没有可确认的中标报价')) return true;
|
||
if (r.includes('缺少有效中标价')) return true;
|
||
if (r.includes('不能中标')) return true;
|
||
if (r.includes('竞价功能未开启')) return true;
|
||
if (r.includes('当前状态不可确认中标')) return true;
|
||
return false;
|
||
}
|
||
|
||
export const EMPTY_QUOTE_RELEASE_MESSAGE = '竞价截止无人报价,已改走智能分配';
|
||
|
||
async function roundHasAnyQuotes(roundId: string): Promise<boolean> {
|
||
const result = await pool.query(
|
||
`SELECT
|
||
EXISTS (SELECT 1 FROM bid_invitations WHERE round_id = $1 AND status = 'quoted') AS has_inv,
|
||
EXISTS (SELECT 1 FROM bid_quotes WHERE round_id = $1) AS has_q`,
|
||
[roundId]
|
||
);
|
||
return Boolean(result.rows[0]?.has_inv) || Boolean(result.rows[0]?.has_q);
|
||
}
|
||
|
||
/** 截止无人报价则截标(open→closed),未报价邀约出局。已 closed 且仍无人报价也视为可放行。 */
|
||
export async function closeRoundIfEmptyQuotesPastDeadline(roundId: string): Promise<{
|
||
released: boolean;
|
||
status: string;
|
||
}> {
|
||
const id = String(roundId || '').trim();
|
||
if (!id) return { released: false, status: '' };
|
||
await expireOverdueInvitations(id);
|
||
const roundRes = await pool.query(
|
||
`SELECT status, respond_deadline FROM bid_rounds WHERE id = $1 LIMIT 1`,
|
||
[id]
|
||
);
|
||
if (!roundRes.rowCount) return { released: false, status: '' };
|
||
const status = String(roundRes.rows[0].status || '');
|
||
if (status !== 'open' && status !== 'closed') return { released: false, status };
|
||
const deadlineRaw = roundRes.rows[0].respond_deadline;
|
||
const deadlinePassed =
|
||
deadlineRaw != null && new Date(String(deadlineRaw)).getTime() < Date.now();
|
||
const quoted = (await roundHasAnyQuotes(id)) ? 1 : 0;
|
||
if (!shouldReleaseEmptyQuoteRound({ deadlinePassed, quoted })) {
|
||
return { released: false, status };
|
||
}
|
||
if (status === 'open') {
|
||
await pool.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'closed', closed_at = COALESCE(closed_at, NOW()), updated_at = NOW()
|
||
WHERE id = $1 AND status = 'open'`,
|
||
[id]
|
||
);
|
||
}
|
||
await pool.query(
|
||
`UPDATE bid_invitations SET status = 'expired' WHERE round_id = $1 AND status = 'pending'`,
|
||
[id]
|
||
);
|
||
return { released: true, status: 'closed' };
|
||
}
|
||
|
||
async function resolveSettingsBranchForRound(
|
||
round: { order_code?: unknown },
|
||
fallback?: string | null
|
||
): Promise<string | null> {
|
||
const orderCode = String(round.order_code || '').trim();
|
||
if (orderCode) {
|
||
const row = await pool.query(
|
||
`SELECT NULLIF(TRIM(branch_code), '') AS branch_code
|
||
FROM orders WHERE order_code = $1 LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
const fromOrder = String(row.rows[0]?.branch_code || '').trim();
|
||
if (fromOrder) return fromOrder;
|
||
}
|
||
const fb = String(fallback || '').trim();
|
||
return fb || null;
|
||
}
|
||
|
||
export async function tryAutoAwardAndAllocate(
|
||
roundId: string,
|
||
branchCode?: string | null
|
||
): Promise<{ awarded: boolean; reason: string; detail?: unknown }> {
|
||
const id = String(roundId || '').trim();
|
||
if (!id) return { awarded: false, reason: 'no_round' };
|
||
|
||
const client = await pool.connect();
|
||
let round: Record<string, unknown> | null = null;
|
||
let deadlinePassed = false;
|
||
let settingsBranch: string | null = branchCode ?? null;
|
||
// 【P0 修复】外层若有事务,改用 SAVEPOINT 而非裸 BEGIN/COMMIT。
|
||
// 缘由与项目既有范式见 AUTO_AWARD_SAVEPOINT 的说明。
|
||
const sharedRequestClient = Boolean(getTenantDbStore()?.client);
|
||
let inOuterTxn = false;
|
||
if (sharedRequestClient) {
|
||
const tx = await client.query(`SELECT txid_current_if_assigned() AS txid`);
|
||
inOuterTxn = Boolean(tx.rows[0]?.txid);
|
||
}
|
||
/** 结束本函数开启的那一层:SAVEPOINT 只释放保存点,绝不提交外层事务 */
|
||
const closeTxnLayer = async () => {
|
||
if (inOuterTxn) await client.query(`RELEASE SAVEPOINT ${AUTO_AWARD_SAVEPOINT}`);
|
||
else await client.query('COMMIT');
|
||
};
|
||
/** 回滚本函数开启的那一层,不影响外层事务的其它写入 */
|
||
const abortTxnLayer = async () => {
|
||
if (inOuterTxn) {
|
||
await client.query(`ROLLBACK TO SAVEPOINT ${AUTO_AWARD_SAVEPOINT}`).catch(() => undefined);
|
||
} else {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
}
|
||
};
|
||
try {
|
||
if (inOuterTxn) await client.query(`SAVEPOINT ${AUTO_AWARD_SAVEPOINT}`);
|
||
else await client.query('BEGIN');
|
||
const locked = await client.query(
|
||
`SELECT * FROM bid_rounds WHERE id = $1 FOR UPDATE`,
|
||
[id]
|
||
);
|
||
if (!locked.rowCount) {
|
||
await abortTxnLayer();
|
||
return { awarded: false, reason: 'not_found' };
|
||
}
|
||
const lockedRound = locked.rows[0] as Record<string, unknown>;
|
||
round = lockedRound;
|
||
settingsBranch = await resolveSettingsBranchForRound(lockedRound, branchCode);
|
||
const settings = await getBidSettings(settingsBranch);
|
||
|
||
await client.query(
|
||
`UPDATE bid_invitations
|
||
SET status = 'expired'
|
||
WHERE round_id = $1
|
||
AND status = 'pending'
|
||
AND respond_deadline < NOW()`,
|
||
[id]
|
||
);
|
||
|
||
const counts = await client.query(
|
||
`SELECT
|
||
COUNT(*) FILTER (WHERE status = 'pending')::int AS pending,
|
||
COUNT(*) FILTER (WHERE status = 'quoted')::int AS quoted,
|
||
EXISTS (SELECT 1 FROM bid_quotes q WHERE q.round_id = $1) AS has_q
|
||
FROM bid_invitations
|
||
WHERE round_id = $1`,
|
||
[id]
|
||
);
|
||
const pending = Number(counts.rows[0]?.pending || 0);
|
||
const quotedInv = Number(counts.rows[0]?.quoted || 0);
|
||
const hasQuoteRows = Boolean(counts.rows[0]?.has_q);
|
||
// 与 cron 选轮一致:邀约 quoted 或存在 bid_quotes 均视为有报价
|
||
const quoted = quotedInv > 0 || hasQuoteRows ? Math.max(quotedInv, 1) : 0;
|
||
const deadlineRaw = lockedRound.respond_deadline;
|
||
deadlinePassed =
|
||
deadlineRaw != null && new Date(String(deadlineRaw)).getTime() < Date.now();
|
||
|
||
const gate = evaluateAutoAwardGate({
|
||
autoAwardLowest: Boolean(settings.auto_award_lowest),
|
||
status: String(lockedRound.status || ''),
|
||
pending,
|
||
quoted,
|
||
deadlinePassed,
|
||
});
|
||
await closeTxnLayer();
|
||
|
||
if (!gate.proceed) {
|
||
return { awarded: false, reason: gate.reason };
|
||
}
|
||
} catch (error) {
|
||
await abortTxnLayer();
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
try {
|
||
const detail = await confirmBidAwards({
|
||
roundId: id,
|
||
useSuggestedLowest: true,
|
||
acknowledgePendingInvites: true,
|
||
branchCode: settingsBranch,
|
||
awardedBy: null,
|
||
});
|
||
console.info(
|
||
`[bid] 自动中标成功 round=${id} order=${String(round?.order_code || '')}`
|
||
);
|
||
return { awarded: true, reason: 'ok', detail };
|
||
} catch (error) {
|
||
const reason = error instanceof Error ? error.message : 'award_failed';
|
||
console.warn('[bid] 自动中标失败:', reason);
|
||
if (deadlinePassed && isUnrecoverableAutoAwardFailure(reason)) {
|
||
try {
|
||
const fallback = await fallbackFailedAwardRoundToSmartAlloc(id, branchCode);
|
||
console.warn(
|
||
`[bid] 截止后评标失败已降级智能分配 round=${id} order=${String(round?.order_code || '')}` +
|
||
(fallback.allocated ? '(已触发分配)' : '')
|
||
);
|
||
return { awarded: false, reason: 'fallback_smart_alloc', detail: fallback };
|
||
} catch (fallbackError) {
|
||
console.warn(
|
||
'[bid] 评标失败降级智能分配异常:',
|
||
fallbackError instanceof Error ? fallbackError.message : fallbackError
|
||
);
|
||
}
|
||
}
|
||
return { awarded: false, reason };
|
||
}
|
||
}
|
||
|
||
/** 截止后无法中标:取消轮次,按每单则跳过竞价闸门走智能分配 */
|
||
export async function fallbackFailedAwardRoundToSmartAlloc(
|
||
roundId: string,
|
||
branchCode?: string | null
|
||
): Promise<{ cancelled: boolean; allocated: boolean }> {
|
||
const id = String(roundId || '').trim();
|
||
if (!id) return { cancelled: false, allocated: false };
|
||
|
||
const roundRes = await pool.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'cancelled', updated_at = NOW()
|
||
WHERE id = $1 AND status IN ('open', 'closed')
|
||
RETURNING id, order_code, cycle_mode`,
|
||
[id]
|
||
);
|
||
if (!roundRes.rowCount) return { cancelled: false, allocated: false };
|
||
|
||
await pool.query(
|
||
`UPDATE bid_invitations SET status = 'expired' WHERE round_id = $1 AND status = 'pending'`,
|
||
[id]
|
||
);
|
||
|
||
const row = roundRes.rows[0];
|
||
let allocated = false;
|
||
if (String(row.cycle_mode || '') === 'per_order') {
|
||
const orderCode = String(row.order_code || '').trim();
|
||
if (orderCode) {
|
||
const order = await pool.query(
|
||
`SELECT order_status FROM orders
|
||
WHERE order_code = $1 AND deleted_at IS NULL
|
||
LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (order.rowCount && Number(order.rows[0].order_status) === 20) {
|
||
const { reprocessOrderAllocation } = await import('./orderAllocationService');
|
||
await reprocessOrderAllocation(orderCode, null, branchCode ?? null, undefined, {
|
||
skipPerOrderAutoBidGate: true,
|
||
});
|
||
allocated = true;
|
||
}
|
||
}
|
||
}
|
||
return { cancelled: true, allocated };
|
||
}
|
||
|
||
/** 懒触发:开启自动中标时尝试完结(全员已报或已过截止) */
|
||
export async function maybeLazyAutoAwardRound(
|
||
roundId: string,
|
||
branchCode?: string | null
|
||
): Promise<void> {
|
||
const id = String(roundId || '').trim();
|
||
if (!id) return;
|
||
try {
|
||
await tryAutoAwardAndAllocate(id, branchCode);
|
||
} catch (error) {
|
||
console.warn(
|
||
'[bid] 懒触发自动中标失败:',
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
}
|
||
|
||
async function resolveSkusForScope(input: {
|
||
scopeType: BidScopeType;
|
||
skuCodes?: string[];
|
||
categoryCodes?: string[];
|
||
branchCode?: string | null;
|
||
}): Promise<
|
||
Array<{
|
||
sku_code: string;
|
||
sku_name: string | null;
|
||
category_code: string | null;
|
||
category_name: string | null;
|
||
unit: string | null;
|
||
}>
|
||
> {
|
||
if (input.scopeType === 'sku') {
|
||
const codes = [...new Set((input.skuCodes || []).map((c) => String(c || '').trim()).filter(Boolean))];
|
||
if (!codes.length) throw httpError('请至少选择一个商品');
|
||
const result = await pool.query(
|
||
`SELECT sku_code, sku_name, category_code, unit
|
||
FROM skus
|
||
WHERE sku_code = ANY($1::text[])
|
||
AND COALESCE(status, 1) IN (1, 10, 20)`,
|
||
[codes]
|
||
);
|
||
if (!result.rowCount) throw httpError('未找到可用商品');
|
||
const categories = await fetchCategoryRows(input.branchCode);
|
||
const catMap = new Map(categories.map((c) => [c.category_code, c.category_name]));
|
||
return result.rows.map((row) => ({
|
||
sku_code: String(row.sku_code),
|
||
sku_name: row.sku_name != null ? String(row.sku_name) : null,
|
||
category_code: row.category_code != null ? String(row.category_code) : null,
|
||
category_name: row.category_code ? catMap.get(String(row.category_code)) || null : null,
|
||
unit: row.unit != null ? String(row.unit) : null,
|
||
}));
|
||
}
|
||
|
||
const categoryCodes = [
|
||
...new Set((input.categoryCodes || []).map((c) => String(c || '').trim()).filter(Boolean)),
|
||
];
|
||
if (!categoryCodes.length) throw httpError('请至少选择一个分类');
|
||
|
||
const categories = await fetchCategoryRows(input.branchCode);
|
||
const byParent = new Map<string, string[]>();
|
||
for (const cat of categories) {
|
||
const parent = String(cat.parent_code || '').trim();
|
||
if (!parent) continue;
|
||
const list = byParent.get(parent) || [];
|
||
list.push(cat.category_code);
|
||
byParent.set(parent, list);
|
||
}
|
||
|
||
const expanded = new Set<string>();
|
||
const queue = [...categoryCodes];
|
||
while (queue.length) {
|
||
const code = queue.shift()!;
|
||
if (expanded.has(code)) continue;
|
||
expanded.add(code);
|
||
for (const child of byParent.get(code) || []) queue.push(child);
|
||
}
|
||
|
||
const catNameMap = new Map(categories.map((c) => [c.category_code, c.category_name]));
|
||
const result = await pool.query(
|
||
`SELECT sku_code, sku_name, category_code, unit
|
||
FROM skus
|
||
WHERE category_code = ANY($1::text[])
|
||
AND COALESCE(status, 1) IN (1, 10, 20)
|
||
ORDER BY sku_code`,
|
||
[[...expanded]]
|
||
);
|
||
if (!result.rowCount) throw httpError('所选分类下没有可用商品');
|
||
|
||
let rows = result.rows.map((row) => ({
|
||
sku_code: String(row.sku_code),
|
||
sku_name: row.sku_name != null ? String(row.sku_name) : null,
|
||
category_code: row.category_code != null ? String(row.category_code) : null,
|
||
category_name: row.category_code ? catNameMap.get(String(row.category_code)) || null : null,
|
||
unit: row.unit != null ? String(row.unit) : null,
|
||
}));
|
||
|
||
// 按每单自动发标:可传入订单命中 SKU,避免整类全量进轮
|
||
const skuFilter = [
|
||
...new Set((input.skuCodes || []).map((c) => String(c || '').trim()).filter(Boolean)),
|
||
];
|
||
if (skuFilter.length) {
|
||
const allow = new Set(skuFilter);
|
||
rows = rows.filter((r) => allow.has(r.sku_code));
|
||
if (!rows.length) throw httpError('所选分类下没有与订单匹配的商品');
|
||
}
|
||
|
||
return rows;
|
||
}
|
||
|
||
/** 将所选分类展开为含全部子孙的 category_code 集合 */
|
||
async function expandCategoryCodes(
|
||
categoryCodes: string[],
|
||
branchCode?: string | null
|
||
): Promise<Set<string>> {
|
||
const codes = [...new Set(categoryCodes.map((c) => String(c || '').trim()).filter(Boolean))];
|
||
const expanded = new Set<string>();
|
||
if (!codes.length) return expanded;
|
||
|
||
const categories = await fetchCategoryRows(branchCode);
|
||
const byParent = new Map<string, string[]>();
|
||
for (const cat of categories) {
|
||
const parent = String(cat.parent_code || '').trim();
|
||
if (!parent) continue;
|
||
const list = byParent.get(parent) || [];
|
||
list.push(cat.category_code);
|
||
byParent.set(parent, list);
|
||
}
|
||
|
||
const queue = [...codes];
|
||
while (queue.length) {
|
||
const code = queue.shift()!;
|
||
if (expanded.has(code)) continue;
|
||
expanded.add(code);
|
||
for (const child of byParent.get(code) || []) queue.push(child);
|
||
}
|
||
return expanded;
|
||
}
|
||
|
||
/** 分类码候选:原码 + 裸码 + 分公司前缀(与采购/分配互通) */
|
||
function categoryLookupVariants(categoryCode: string, branchCode?: string | null): string[] {
|
||
const trimmed = String(categoryCode || '').trim();
|
||
if (!trimmed) return [];
|
||
const bare = stripBranchCategoryPrefix(trimmed);
|
||
const branch = String(branchCode || '').trim();
|
||
const prefixed = branch ? ensureBranchCategoryCode(branch, trimmed) : '';
|
||
return [...new Set([trimmed, bare, prefixed].filter(Boolean))];
|
||
}
|
||
|
||
/** 判断明细分类是否落在已展开的设置分类集合内(含前缀归一) */
|
||
export function categoryInExpandedSet(
|
||
categoryCode: string,
|
||
expanded: Set<string>,
|
||
branchCode?: string | null
|
||
): boolean {
|
||
const variants = categoryLookupVariants(categoryCode, branchCode);
|
||
if (variants.some((c) => expanded.has(c))) return true;
|
||
const bareSet = new Set([...expanded].map((c) => stripBranchCategoryPrefix(c)));
|
||
return variants.some((c) => bareSet.has(stripBranchCategoryPrefix(c)));
|
||
}
|
||
|
||
/** 空码 / 自采 / 未分配 不算「指定供应商」 */
|
||
export function isRealBidSupplier(code?: string | null): boolean {
|
||
const c = String(code || '').trim();
|
||
return Boolean(c) && c !== 'INTERNAL' && c !== 'UNASSIGNED';
|
||
}
|
||
|
||
export function resolveDesignatedSupplierForSku(input: {
|
||
skuCode: string;
|
||
categoryCode?: string | null;
|
||
orderLineSupplier?: string | null;
|
||
skuItems: Array<{ sku_code: string; supplier_code?: string | null }>;
|
||
categoryItems: Array<{ category_code: string; supplier_code?: string | null }>;
|
||
categoryMatches: (itemCategory: string, settingCategory: string) => boolean;
|
||
}): string | null {
|
||
if (isRealBidSupplier(input.orderLineSupplier)) {
|
||
return String(input.orderLineSupplier).trim();
|
||
}
|
||
const sku = String(input.skuCode || '').trim();
|
||
const skuItem = input.skuItems.find((i) => String(i.sku_code || '').trim() === sku);
|
||
if (skuItem && isRealBidSupplier(skuItem.supplier_code)) {
|
||
return String(skuItem.supplier_code).trim();
|
||
}
|
||
const itemCat = String(input.categoryCode || '').trim();
|
||
if (itemCat) {
|
||
for (const ci of input.categoryItems) {
|
||
const settingCat = String(ci.category_code || '').trim();
|
||
if (!settingCat || !isRealBidSupplier(ci.supplier_code)) continue;
|
||
if (input.categoryMatches(itemCat, settingCat)) {
|
||
return String(ci.supplier_code).trim();
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** sku_code → 指定真实供应商 */
|
||
export async function resolveDesignatedSuppliersBySku(input: {
|
||
skuRows: Array<{
|
||
sku_code: string;
|
||
category_code?: string | null;
|
||
supplier_code?: string | null;
|
||
}>;
|
||
settings: Pick<BidSettings, 'sku_items' | 'category_items'>;
|
||
branchCode?: string | null;
|
||
}): Promise<Map<string, string>> {
|
||
const skuItems = input.settings.sku_items || [];
|
||
const categoryItems = input.settings.category_items || [];
|
||
const expandedByCat = new Map<string, Set<string>>();
|
||
for (const ci of categoryItems) {
|
||
const cat = String(ci.category_code || '').trim();
|
||
if (!cat || expandedByCat.has(cat)) continue;
|
||
expandedByCat.set(cat, await expandCategoryCodes([cat], input.branchCode));
|
||
}
|
||
|
||
const orderLineBySku = new Map<string, string>();
|
||
const bySku = new Map<string, { sku_code: string; category_code: string }>();
|
||
for (const row of input.skuRows) {
|
||
const sku = String(row.sku_code || '').trim();
|
||
if (!sku) continue;
|
||
if (!orderLineBySku.has(sku) && isRealBidSupplier(row.supplier_code)) {
|
||
orderLineBySku.set(sku, String(row.supplier_code).trim());
|
||
}
|
||
if (!bySku.has(sku)) {
|
||
bySku.set(sku, {
|
||
sku_code: sku,
|
||
category_code: String(row.category_code || '').trim(),
|
||
});
|
||
}
|
||
}
|
||
|
||
const result = new Map<string, string>();
|
||
for (const meta of bySku.values()) {
|
||
const designated = resolveDesignatedSupplierForSku({
|
||
skuCode: meta.sku_code,
|
||
categoryCode: meta.category_code,
|
||
orderLineSupplier: orderLineBySku.get(meta.sku_code) || null,
|
||
skuItems,
|
||
categoryItems,
|
||
categoryMatches: (itemCategory, settingCategory) => {
|
||
const expanded = expandedByCat.get(settingCategory);
|
||
if (!expanded) return false;
|
||
return categoryInExpandedSet(itemCategory, expanded, input.branchCode);
|
||
},
|
||
});
|
||
if (designated) result.set(meta.sku_code, designated);
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/** 未填供应商的兄弟行回写指定商;不覆盖 INTERNAL / 已有真实供应商 */
|
||
export async function stampDesignatedSuppliersOnOrderItems(input: {
|
||
orderCode: string;
|
||
branchCode?: string | null;
|
||
items: Array<{
|
||
id: string;
|
||
sku_code?: string | null;
|
||
supplier_code?: string | null;
|
||
category_code?: string | null;
|
||
}>;
|
||
client: Pick<PoolClient, 'query'>;
|
||
}): Promise<Map<string, string>> {
|
||
const orderCode = String(input.orderCode || '').trim();
|
||
if (!orderCode || !input.items.length) return new Map();
|
||
|
||
let settings: BidSettings;
|
||
try {
|
||
settings = await getBidSettings(input.branchCode);
|
||
} catch {
|
||
return new Map();
|
||
}
|
||
if (!settings.enabled) return new Map();
|
||
|
||
const designated = await resolveDesignatedSuppliersBySku({
|
||
skuRows: input.items.map((row) => ({
|
||
sku_code: String(row.sku_code || '').trim(),
|
||
category_code: row.category_code,
|
||
supplier_code: row.supplier_code,
|
||
})),
|
||
settings,
|
||
branchCode: input.branchCode,
|
||
});
|
||
if (!designated.size) return designated;
|
||
|
||
for (const item of input.items) {
|
||
const sku = String(item.sku_code || '').trim();
|
||
const supplier = sku ? designated.get(sku) : undefined;
|
||
if (!supplier) continue;
|
||
if (String(item.supplier_code || '').trim() === 'INTERNAL') continue;
|
||
if (isRealBidSupplier(item.supplier_code)) continue;
|
||
await input.client.query(
|
||
`UPDATE order_items SET supplier_code = $1 WHERE id = $2 AND order_code = $3`,
|
||
[supplier, item.id, orderCode]
|
||
);
|
||
item.supplier_code = supplier;
|
||
}
|
||
return designated;
|
||
}
|
||
|
||
/**
|
||
* 按分配同口径:父类绑定 / 一级 / 别名 / 前缀互通,从经营分类绑定中解析可邀供应商。
|
||
* 纯函数便于单测。
|
||
*/
|
||
export function resolveCategoryInviteSuppliers(
|
||
categoryCodes: string[],
|
||
categoryRows: CategoryRow[],
|
||
bindings: Array<{ supplier_code: string; category_code: string }>,
|
||
branchCode?: string | null
|
||
): string[] {
|
||
const suppliers = new Set<string>();
|
||
const codes = [...new Set(categoryCodes.map((c) => String(c || '').trim()).filter(Boolean))];
|
||
if (!codes.length || !bindings.length) return [];
|
||
|
||
const bindingCats = bindings.map((b) => ({ category_code: String(b.category_code || '').trim() }));
|
||
|
||
for (const cat of codes) {
|
||
const matchedBoundCodes = new Set<string>();
|
||
if (categoryRows.length) {
|
||
for (const code of getSupplierBindingLookupCodes(cat, categoryRows, bindingCats)) {
|
||
matchedBoundCodes.add(code);
|
||
}
|
||
// 明细分类的前缀变体再查一遍(SKU 存裸码、绑定存 BR_ 前缀等)
|
||
for (const variant of categoryLookupVariants(cat, branchCode)) {
|
||
if (variant === cat) continue;
|
||
for (const code of getSupplierBindingLookupCodes(variant, categoryRows, bindingCats)) {
|
||
matchedBoundCodes.add(code);
|
||
}
|
||
}
|
||
} else {
|
||
for (const variant of categoryLookupVariants(cat, branchCode)) {
|
||
matchedBoundCodes.add(variant);
|
||
}
|
||
}
|
||
|
||
if (!matchedBoundCodes.size) {
|
||
for (const variant of categoryLookupVariants(cat, branchCode)) {
|
||
matchedBoundCodes.add(variant);
|
||
}
|
||
}
|
||
|
||
const bareMatched = new Set([...matchedBoundCodes].map((c) => stripBranchCategoryPrefix(c)));
|
||
for (const b of bindings) {
|
||
const bc = String(b.category_code || '').trim();
|
||
const sc = String(b.supplier_code || '').trim();
|
||
if (!bc || !sc) continue;
|
||
if (matchedBoundCodes.has(bc) || bareMatched.has(stripBranchCategoryPrefix(bc))) {
|
||
suppliers.add(sc);
|
||
}
|
||
}
|
||
}
|
||
return [...suppliers];
|
||
}
|
||
|
||
async function resolveInviteSuppliers(
|
||
skuCodes: string[],
|
||
categoryCodes: string[],
|
||
branchCode?: string | null,
|
||
options?: { skipSkuSuppliers?: boolean }
|
||
): Promise<string[]> {
|
||
const suppliers = new Set<string>();
|
||
if (skuCodes.length && !options?.skipSkuSuppliers) {
|
||
const bySku = await pool.query(
|
||
`SELECT DISTINCT supplier_code
|
||
FROM sku_suppliers
|
||
WHERE sku_code = ANY($1::text[])
|
||
AND COALESCE(status, 1) = 1
|
||
AND NULLIF(TRIM(supplier_code), '') IS NOT NULL`,
|
||
[skuCodes]
|
||
);
|
||
for (const row of bySku.rows) suppliers.add(String(row.supplier_code).trim());
|
||
}
|
||
if (categoryCodes.length) {
|
||
let categoryRows: CategoryRow[] = [];
|
||
try {
|
||
if (String(branchCode || '').trim()) {
|
||
categoryRows = await fetchCategoryRows(branchCode);
|
||
}
|
||
} catch (error) {
|
||
console.warn(
|
||
'[bid] 加载分类树失败,邀请匹配降级为编码归一/精确匹配:',
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
const byCat = await pool.query(
|
||
`SELECT sc.supplier_code, sc.category_code
|
||
FROM supplier_categories sc
|
||
JOIN suppliers s ON s.supplier_code = sc.supplier_code
|
||
WHERE COALESCE(s.status, 10) IN (10, 20)
|
||
AND NULLIF(TRIM(sc.supplier_code), '') IS NOT NULL
|
||
AND NULLIF(TRIM(sc.category_code), '') IS NOT NULL`
|
||
);
|
||
const bindings = byCat.rows.map((row) => ({
|
||
supplier_code: String(row.supplier_code).trim(),
|
||
category_code: String(row.category_code).trim(),
|
||
}));
|
||
for (const code of resolveCategoryInviteSuppliers(
|
||
categoryCodes,
|
||
categoryRows,
|
||
bindings,
|
||
branchCode
|
||
)) {
|
||
suppliers.add(code);
|
||
}
|
||
}
|
||
return [...suppliers];
|
||
}
|
||
|
||
/**
|
||
* 按分类码变体集合直接查经营分类绑定(宽松匹配),避免树解析失败时只剩首选一家。
|
||
*/
|
||
async function resolveSuppliersByCategoryVariants(
|
||
categoryCodes: string[],
|
||
branchCode?: string | null
|
||
): Promise<string[]> {
|
||
const codes = [...new Set(categoryCodes.map((c) => String(c || '').trim()).filter(Boolean))];
|
||
if (!codes.length) return [];
|
||
const variants = new Set<string>();
|
||
for (const code of codes) {
|
||
for (const v of categoryLookupVariants(code, branchCode)) variants.add(v);
|
||
}
|
||
const variantList = [...variants];
|
||
const bareList = [...new Set(variantList.map((c) => stripBranchCategoryPrefix(c)).filter(Boolean))];
|
||
const result = await pool.query(
|
||
`SELECT DISTINCT sc.supplier_code
|
||
FROM supplier_categories sc
|
||
JOIN suppliers s ON s.supplier_code = sc.supplier_code
|
||
WHERE COALESCE(s.status, 10) IN (10, 20)
|
||
AND NULLIF(TRIM(sc.supplier_code), '') IS NOT NULL
|
||
AND NULLIF(TRIM(sc.category_code), '') IS NOT NULL
|
||
AND (
|
||
TRIM(sc.category_code) = ANY($1::text[])
|
||
OR regexp_replace(TRIM(sc.category_code), '^[^_]+_', '') = ANY($2::text[])
|
||
)`,
|
||
[variantList, bareList]
|
||
);
|
||
return result.rows.map((row) => String(row.supplier_code).trim()).filter(Boolean);
|
||
}
|
||
|
||
/**
|
||
* 竞价设置中的分类范围(含子类)对应的全部经营分类供应商。
|
||
* 与「行内首选供应商」不同:此处按经营分类并集邀请,避免只邀首选一家。
|
||
*/
|
||
async function resolveSettingsCategoryInviteSuppliers(
|
||
branchCode?: string | null
|
||
): Promise<string[]> {
|
||
const settings = await getBidSettings(branchCode);
|
||
const selectedCats = [...new Set((settings.category_codes || []).map((c) => String(c || '').trim()).filter(Boolean))];
|
||
if (!selectedCats.length) return [];
|
||
const expanded = await expandCategoryCodes(selectedCats, branchCode);
|
||
const poolCodes = expanded.size ? [...expanded] : selectedCats;
|
||
const [smart, loose] = await Promise.all([
|
||
resolveInviteSuppliers([], poolCodes, branchCode),
|
||
resolveSuppliersByCategoryVariants(poolCodes, branchCode),
|
||
]);
|
||
return [...new Set([...smart, ...loose])];
|
||
}
|
||
|
||
/**
|
||
* 轮次明细 SKU:除 sku_suppliers 外,再按其商品分类邀请全部经营供应商。
|
||
* 避免「同品类多家供应商」仅因未维护 sku_suppliers / 只配了首选而只邀一家。
|
||
*/
|
||
async function resolveCategoryInviteSuppliersForSkus(
|
||
skuCodes: string[],
|
||
branchCode?: string | null
|
||
): Promise<string[]> {
|
||
const codes = [...new Set(skuCodes.map((c) => String(c || '').trim()).filter(Boolean))];
|
||
if (!codes.length) return [];
|
||
const skuCats = await pool.query(
|
||
`SELECT DISTINCT NULLIF(TRIM(category_code), '') AS category_code
|
||
FROM skus
|
||
WHERE sku_code = ANY($1::text[])
|
||
AND NULLIF(TRIM(category_code), '') IS NOT NULL`,
|
||
[codes]
|
||
);
|
||
const categoryCodes = skuCats.rows
|
||
.map((row) => String(row.category_code || '').trim())
|
||
.filter(Boolean);
|
||
if (!categoryCodes.length) return [];
|
||
const [smart, loose] = await Promise.all([
|
||
resolveInviteSuppliers([], categoryCodes, branchCode),
|
||
resolveSuppliersByCategoryVariants(categoryCodes, branchCode),
|
||
]);
|
||
return [...new Set([...smart, ...loose])];
|
||
}
|
||
|
||
/** 竞价设置中与本轮明细相关的首选供应商(须仍绑定对应经营分类/供货关系) */
|
||
async function resolvePreferredInviteSuppliers(
|
||
skuCodes: string[],
|
||
itemCategoryCodes: string[],
|
||
branchCode?: string | null,
|
||
options?: { skipSkuSuppliers?: boolean }
|
||
): Promise<string[]> {
|
||
const settings = await getBidSettings(branchCode);
|
||
const out = new Set<string>();
|
||
const skuSet = new Set(skuCodes.map((c) => String(c || '').trim()).filter(Boolean));
|
||
|
||
for (const item of settings.sku_items || []) {
|
||
const sku = String(item.sku_code || '').trim();
|
||
const supplier = String(item.supplier_code || '').trim();
|
||
if (sku && supplier && skuSet.has(sku)) out.add(supplier);
|
||
}
|
||
|
||
const catItems = (settings.category_items || []).filter(
|
||
(i) => String(i.category_code || '').trim() && String(i.supplier_code || '').trim()
|
||
);
|
||
for (const item of catItems) {
|
||
const settingCat = String(item.category_code).trim();
|
||
const supplier = String(item.supplier_code).trim();
|
||
if (!itemCategoryCodes.length) continue;
|
||
const expanded = await expandCategoryCodes([settingCat], branchCode);
|
||
const coversItem = itemCategoryCodes.some((ic) =>
|
||
categoryInExpandedSet(ic, expanded, branchCode)
|
||
);
|
||
if (coversItem) {
|
||
out.add(supplier);
|
||
continue;
|
||
}
|
||
const settingVariants = new Set(categoryLookupVariants(settingCat, branchCode));
|
||
const itemHitsParent = itemCategoryCodes.some((ic) =>
|
||
categoryLookupVariants(ic, branchCode).some((v) => settingVariants.has(v))
|
||
);
|
||
if (itemHitsParent) out.add(supplier);
|
||
}
|
||
|
||
// 分类级主供:经营分类 is_primary,作为邀约首选补充
|
||
if (itemCategoryCodes.length) {
|
||
const primaryRes = await pool.query(
|
||
`SELECT sc.supplier_code, sc.category_code
|
||
FROM supplier_categories sc
|
||
JOIN suppliers s ON s.supplier_code = sc.supplier_code
|
||
WHERE sc.is_primary = true
|
||
AND COALESCE(s.status, 10) IN (10, 20)
|
||
AND NULLIF(TRIM(sc.supplier_code), '') IS NOT NULL`
|
||
);
|
||
for (const row of primaryRes.rows) {
|
||
const settingCat = String(row.category_code || '').trim();
|
||
const supplier = String(row.supplier_code || '').trim();
|
||
if (!settingCat || !supplier) continue;
|
||
const expanded = await expandCategoryCodes([settingCat], branchCode);
|
||
const coversItem = itemCategoryCodes.some((ic) =>
|
||
categoryInExpandedSet(ic, expanded, branchCode)
|
||
);
|
||
if (coversItem) {
|
||
out.add(supplier);
|
||
continue;
|
||
}
|
||
const settingVariants = new Set(categoryLookupVariants(settingCat, branchCode));
|
||
const itemHitsParent = itemCategoryCodes.some((ic) =>
|
||
categoryLookupVariants(ic, branchCode).some((v) => settingVariants.has(v))
|
||
);
|
||
if (itemHitsParent) out.add(supplier);
|
||
}
|
||
}
|
||
|
||
return filterPreferredStillEligible([...out], skuCodes, itemCategoryCodes, branchCode, options);
|
||
}
|
||
|
||
/** 首选供应商须仍挂在本轮相关分类(或 SKU 供货关系)上,避免改绑后仍被邀 */
|
||
async function filterPreferredStillEligible(
|
||
supplierCodes: string[],
|
||
skuCodes: string[],
|
||
itemCategoryCodes: string[],
|
||
branchCode?: string | null,
|
||
options?: { skipSkuSuppliers?: boolean }
|
||
): Promise<string[]> {
|
||
const codes = [...new Set(supplierCodes.map((c) => String(c || '').trim()).filter(Boolean))];
|
||
if (!codes.length) return [];
|
||
|
||
const eligible = new Set<string>();
|
||
if (itemCategoryCodes.length) {
|
||
const byCat = await resolveSuppliersByCategoryVariants(itemCategoryCodes, branchCode);
|
||
for (const c of byCat) eligible.add(c);
|
||
}
|
||
if (skuCodes.length && !options?.skipSkuSuppliers) {
|
||
const bySku = await pool.query(
|
||
`SELECT DISTINCT supplier_code
|
||
FROM sku_suppliers
|
||
WHERE sku_code = ANY($1::text[])
|
||
AND COALESCE(status, 1) = 1
|
||
AND supplier_code = ANY($2::text[])`,
|
||
[skuCodes, codes]
|
||
);
|
||
for (const row of bySku.rows) eligible.add(String(row.supplier_code).trim());
|
||
}
|
||
|
||
const kept = codes.filter((c) => eligible.has(c));
|
||
const dropped = codes.filter((c) => !eligible.has(c));
|
||
if (dropped.length) {
|
||
console.info(`[bid] 首选供应商因现绑不符已丢弃: ${dropped.join(',')}`);
|
||
}
|
||
return kept;
|
||
}
|
||
|
||
export async function listBidRounds(input?: { status?: string; limit?: number }) {
|
||
const limit = Math.min(Math.max(Number(input?.limit) || 50, 1), 200);
|
||
const status = String(input?.status || '').trim();
|
||
const params: unknown[] = [limit];
|
||
let where = '';
|
||
if (status) {
|
||
params.unshift(status);
|
||
where = 'WHERE status = $1';
|
||
}
|
||
const result = await pool.query(
|
||
`SELECT r.*,
|
||
(SELECT COUNT(*)::int FROM bid_round_items i WHERE i.round_id = r.id) AS item_count,
|
||
(SELECT COUNT(*)::int FROM bid_invitations v WHERE v.round_id = r.id) AS invite_count,
|
||
(SELECT COUNT(*)::int FROM bid_invitations v WHERE v.round_id = r.id AND v.status = 'quoted') AS quoted_count,
|
||
(SELECT COUNT(*)::int FROM bid_awards a WHERE a.round_id = r.id) AS award_count
|
||
FROM bid_rounds r
|
||
${where}
|
||
ORDER BY r.created_at DESC
|
||
LIMIT $${params.length}`,
|
||
params
|
||
);
|
||
return result.rows;
|
||
}
|
||
|
||
export async function getBidRoundDetail(roundId: string, branchCode?: string | null) {
|
||
const id = String(roundId || '').trim();
|
||
if (!id) throw httpError('缺少轮次 ID');
|
||
|
||
await expireOverdueInvitations(id);
|
||
await maybeLazyAutoAwardRound(id, branchCode);
|
||
await maybeLazyReleaseAllocationHold(id, branchCode);
|
||
|
||
const round = await pool.query(`SELECT * FROM bid_rounds WHERE id = $1 LIMIT 1`, [id]);
|
||
if (!round.rowCount) throw httpError('竞价轮次不存在', 404, 'not_found');
|
||
|
||
const [items, invitations, quotes, awards] = await Promise.all([
|
||
pool.query(`SELECT * FROM bid_round_items WHERE round_id = $1 ORDER BY sku_code`, [id]),
|
||
pool.query(
|
||
`SELECT v.*, s.company_name AS supplier_name
|
||
FROM bid_invitations v
|
||
LEFT JOIN suppliers s ON s.supplier_code = v.supplier_code
|
||
WHERE v.round_id = $1
|
||
ORDER BY v.invited_at`,
|
||
[id]
|
||
),
|
||
pool.query(
|
||
`SELECT q.*, s.company_name AS supplier_name
|
||
FROM bid_quotes q
|
||
LEFT JOIN suppliers s ON s.supplier_code = q.supplier_code
|
||
WHERE q.round_id = $1
|
||
ORDER BY q.sku_code, q.unit_price ASC, q.created_at ASC`,
|
||
[id]
|
||
),
|
||
pool.query(
|
||
`SELECT a.*, s.company_name AS supplier_name
|
||
FROM bid_awards a
|
||
LEFT JOIN suppliers s ON s.supplier_code = a.supplier_code
|
||
WHERE a.round_id = $1
|
||
ORDER BY a.sku_code`,
|
||
[id]
|
||
),
|
||
]);
|
||
|
||
const settingsForSuggest = await getBidSettings(branchCode).catch(() => null);
|
||
const suggestedAwards = settingsForSuggest
|
||
? await suggestAwardsForSettings({
|
||
quotes: quotes.rows,
|
||
settings: settingsForSuggest,
|
||
branchCode,
|
||
})
|
||
: suggestLowestQuotesPure(quotes.rows);
|
||
const roundRow = round.rows[0];
|
||
const holdActive = isAllocationHoldActive(roundRow);
|
||
|
||
return {
|
||
round: roundRow,
|
||
items: items.rows,
|
||
invitations: invitations.rows,
|
||
quotes: quotes.rows,
|
||
awards: awards.rows,
|
||
suggested_awards: suggestedAwards,
|
||
award_mode: settingsForSuggest?.award_mode || 'lowest',
|
||
allocation_hold_active: holdActive,
|
||
};
|
||
}
|
||
|
||
export async function createBidRound(input: {
|
||
title?: string;
|
||
cycleMode: BidCycleMode;
|
||
scopeType: BidScopeType;
|
||
orderCode?: string | null;
|
||
periodStart?: string | null;
|
||
periodEnd?: string | null;
|
||
respondMinutes?: number | null;
|
||
skuCodes?: string[];
|
||
categoryCodes?: string[];
|
||
supplierCodes?: string[];
|
||
openImmediately?: boolean;
|
||
/** 报价窗开始前排队:同一 INSERT 写入,避免半成品被当成无时刻 draft 立刻补开 */
|
||
scheduledOpenAt?: Date | null;
|
||
branchCode?: string | null;
|
||
createdBy?: string | null;
|
||
}) {
|
||
const settings = await assertBidEnabled(input.branchCode);
|
||
const cycleMode = input.cycleMode === 'per_order' ? 'per_order' : 'period';
|
||
const scopeType = input.scopeType === 'category' ? 'category' : 'sku';
|
||
const respondMinutes =
|
||
Number(input.respondMinutes) > 0
|
||
? Math.min(10080, Math.round(Number(input.respondMinutes)))
|
||
: settings.respond_minutes;
|
||
|
||
if (cycleMode === 'per_order') {
|
||
const orderCode = String(input.orderCode || '').trim();
|
||
if (!orderCode) throw httpError('按每单竞价须指定订单号');
|
||
const order = await pool.query(`SELECT order_code FROM orders WHERE order_code = $1 LIMIT 1`, [
|
||
orderCode,
|
||
]);
|
||
if (!order.rowCount) throw httpError('订单不存在', 404, 'not_found');
|
||
}
|
||
|
||
const items = await resolveSkusForScope({
|
||
scopeType,
|
||
skuCodes: input.skuCodes,
|
||
categoryCodes: input.categoryCodes,
|
||
branchCode: input.branchCode,
|
||
});
|
||
|
||
const roundCode = await genRoundCode();
|
||
const client = await pool.connect();
|
||
let committed = false;
|
||
try {
|
||
await client.query('BEGIN');
|
||
const inserted = await client.query(
|
||
`INSERT INTO bid_rounds (
|
||
round_code, title, cycle_mode, scope_type, order_code,
|
||
period_start, period_end, respond_minutes, status, created_by,
|
||
scheduled_open_at
|
||
) VALUES (
|
||
$1, $2, $3, $4, $5,
|
||
$6, $7, $8, 'draft', $9,
|
||
$10
|
||
)
|
||
RETURNING *`,
|
||
[
|
||
roundCode,
|
||
String(input.title || '').trim() || null,
|
||
cycleMode,
|
||
scopeType,
|
||
cycleMode === 'per_order' ? String(input.orderCode || '').trim() : null,
|
||
cycleMode === 'period' && input.periodStart ? input.periodStart : null,
|
||
cycleMode === 'period' && input.periodEnd ? input.periodEnd : null,
|
||
respondMinutes,
|
||
input.createdBy || null,
|
||
input.openImmediately ? null : input.scheduledOpenAt || null,
|
||
]
|
||
);
|
||
const round = inserted.rows[0];
|
||
|
||
for (const item of items) {
|
||
await client.query(
|
||
`INSERT INTO bid_round_items (
|
||
round_id, sku_code, sku_name, category_code, category_name, unit
|
||
) VALUES ($1, $2, $3, $4, $5, $6)`,
|
||
[
|
||
round.id,
|
||
item.sku_code,
|
||
item.sku_name,
|
||
item.category_code,
|
||
item.category_name,
|
||
item.unit,
|
||
]
|
||
);
|
||
}
|
||
|
||
await client.query('COMMIT');
|
||
committed = true;
|
||
|
||
if (input.openImmediately) {
|
||
try {
|
||
return await openBidRound({
|
||
roundId: round.id,
|
||
supplierCodes: input.supplierCodes,
|
||
branchCode: input.branchCode,
|
||
});
|
||
} catch (openError) {
|
||
// 发标失败时取消草稿,避免 per_order 闸门永久 defer / 与回退分配并存脏轮次
|
||
await pool
|
||
.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'cancelled', updated_at = NOW()
|
||
WHERE id = $1 AND status = 'draft'`,
|
||
[round.id]
|
||
)
|
||
.catch(() => undefined);
|
||
throw openError;
|
||
}
|
||
}
|
||
|
||
return getBidRoundDetail(round.id);
|
||
} catch (error) {
|
||
// 仅未提交时回滚;已 COMMIT 后再 ROLLBACK 会干扰连接,且可能吞掉 open 错误
|
||
if (!committed) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
}
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
async function applyPostAwardHold(
|
||
db: Pick<PoolClient, 'query'>,
|
||
roundId: string,
|
||
holdMinutesRaw: number
|
||
) {
|
||
const holdMinutes = Math.max(0, Math.min(10080, Number(holdMinutesRaw || 0)));
|
||
if (holdMinutes > 0) {
|
||
await db.query(
|
||
`UPDATE bid_rounds
|
||
SET allocation_hold_until = NOW() + ($2::int * INTERVAL '1 minute'),
|
||
allocation_hold_released_at = NULL,
|
||
updated_at = NOW()
|
||
WHERE id = $1`,
|
||
[roundId, holdMinutes]
|
||
);
|
||
} else {
|
||
await db.query(
|
||
`UPDATE bid_rounds
|
||
SET allocation_hold_until = NULL,
|
||
allocation_hold_released_at = NOW(),
|
||
updated_at = NOW()
|
||
WHERE id = $1`,
|
||
[roundId]
|
||
);
|
||
}
|
||
}
|
||
|
||
export async function openBidRound(input: {
|
||
roundId: string;
|
||
supplierCodes?: string[];
|
||
branchCode?: string | null;
|
||
}) {
|
||
await assertBidEnabled(input.branchCode);
|
||
const id = String(input.roundId || '').trim();
|
||
const roundRes = await pool.query(`SELECT * FROM bid_rounds WHERE id = $1 LIMIT 1`, [id]);
|
||
if (!roundRes.rowCount) throw httpError('竞价轮次不存在', 404, 'not_found');
|
||
const round = roundRes.rows[0];
|
||
if (round.status !== 'draft' && round.status !== 'open') {
|
||
throw httpError('仅草稿或进行中的轮次可发标/补邀');
|
||
}
|
||
|
||
const items = await pool.query(`SELECT sku_code, category_code FROM bid_round_items WHERE round_id = $1`, [
|
||
id,
|
||
]);
|
||
if (!items.rowCount) throw httpError('轮次没有商品明细');
|
||
|
||
const settings = await getBidSettings(input.branchCode);
|
||
const orderCode = round.order_code != null ? String(round.order_code).trim() : '';
|
||
const orderLineBySku = new Map<string, string>();
|
||
if (orderCode) {
|
||
const orderRows = await pool.query(
|
||
`SELECT sku_code, supplier_code FROM order_items
|
||
WHERE order_code = $1 AND NULLIF(TRIM(sku_code), '') IS NOT NULL`,
|
||
[orderCode]
|
||
);
|
||
for (const row of orderRows.rows) {
|
||
const sku = String(row.sku_code || '').trim();
|
||
if (!sku || orderLineBySku.has(sku) || !isRealBidSupplier(row.supplier_code)) continue;
|
||
orderLineBySku.set(sku, String(row.supplier_code).trim());
|
||
}
|
||
}
|
||
|
||
const designatedMap = await resolveDesignatedSuppliersBySku({
|
||
skuRows: items.rows.map((r) => {
|
||
const sku = String(r.sku_code || '').trim();
|
||
return {
|
||
sku_code: sku,
|
||
category_code: r.category_code != null ? String(r.category_code).trim() : '',
|
||
supplier_code: orderLineBySku.get(sku) || null,
|
||
};
|
||
}),
|
||
settings,
|
||
branchCode: input.branchCode,
|
||
});
|
||
|
||
const quoteRows = items.rows.filter((r) => !designatedMap.has(String(r.sku_code || '').trim()));
|
||
const designatedSkus = [...designatedMap.keys()];
|
||
const allDirect = quoteRows.length === 0 && designatedSkus.length > 0;
|
||
|
||
const inviteRows = allDirect ? [] : quoteRows;
|
||
const skuCodes = inviteRows.map((r) => String(r.sku_code));
|
||
let categoryCodes = [
|
||
...new Set(inviteRows.map((r) => String(r.category_code || '').trim()).filter(Boolean)),
|
||
];
|
||
if (skuCodes.length) {
|
||
const skuCatRows = await pool.query(
|
||
`SELECT DISTINCT NULLIF(TRIM(category_code), '') AS category_code
|
||
FROM skus
|
||
WHERE sku_code = ANY($1::text[])
|
||
AND NULLIF(TRIM(category_code), '') IS NOT NULL`,
|
||
[skuCodes]
|
||
);
|
||
categoryCodes = [
|
||
...new Set([
|
||
...categoryCodes,
|
||
...skuCatRows.rows.map((r) => String(r.category_code || '').trim()).filter(Boolean),
|
||
]),
|
||
];
|
||
}
|
||
|
||
const manualCodes = (input.supplierCodes || [])
|
||
.map((c) => String(c || '').trim())
|
||
.filter(Boolean);
|
||
|
||
const hasCategoryScope = (settings.category_codes || []).length > 0;
|
||
const hasSkuScope = (settings.sku_codes || []).length > 0;
|
||
/** 仅分类竞价:不以 sku_suppliers 扩邀,避免改绑供应商因旧供货关系入场 */
|
||
const categoryOnly = hasCategoryScope && !hasSkuScope;
|
||
|
||
let supplierCodes: string[] = [];
|
||
let resolved: string[] = [];
|
||
let preferred: string[] = [];
|
||
let settingsCats: string[] = [];
|
||
let settingsCatsScoped: string[] = [];
|
||
let skuCategorySuppliers: string[] = [];
|
||
|
||
if (!allDirect) {
|
||
const [resolvedRows, preferredRows, settingsCatsRows, skuCategoryRows, categoryScopedRows] =
|
||
await Promise.all([
|
||
resolveInviteSuppliers(skuCodes, categoryCodes, input.branchCode, {
|
||
skipSkuSuppliers: categoryOnly,
|
||
}),
|
||
resolvePreferredInviteSuppliers(skuCodes, categoryCodes, input.branchCode, {
|
||
skipSkuSuppliers: categoryOnly,
|
||
}),
|
||
resolveSettingsCategoryInviteSuppliers(input.branchCode),
|
||
categoryOnly
|
||
? Promise.resolve([] as string[])
|
||
: resolveCategoryInviteSuppliersForSkus(skuCodes, input.branchCode),
|
||
// 只按「本轮明细的分类」匹配的供应商(不含 sku_suppliers)——用于给设置里的分类范围收口
|
||
categoryCodes.length
|
||
? resolveInviteSuppliers([], categoryCodes, input.branchCode)
|
||
: Promise.resolve([] as string[]),
|
||
]);
|
||
resolved = resolvedRows;
|
||
preferred = preferredRows;
|
||
settingsCats = settingsCatsRows;
|
||
skuCategorySuppliers = skuCategoryRows;
|
||
|
||
/**
|
||
* 竞价设置里的「分类范围」是**分公司级**配置,与具体某一轮的商品无关。
|
||
* 直接并入会把「与本轮商品无关的分类」下的供应商也邀进来(他们会看到该商品并能报价)。
|
||
* 故:只有当这些供应商同样覆盖「本轮明细的分类」时才并入。
|
||
* 仅分类竞价(categoryOnly)时,本轮分类即设置范围的展开结果,交集后结果不变。
|
||
*/
|
||
if (categoryCodes.length) {
|
||
const categoryScoped = new Set(categoryScopedRows.map((c) => String(c || '').trim()));
|
||
settingsCatsScoped = settingsCats.filter((code) => categoryScoped.has(String(code || '').trim()));
|
||
} else {
|
||
// 本轮明细没有分类可比对:保持原行为,不擅自扩大也不擅自收窄
|
||
settingsCatsScoped = settingsCats;
|
||
}
|
||
|
||
supplierCodes = [
|
||
...new Set([
|
||
...manualCodes,
|
||
...resolved,
|
||
...preferred,
|
||
...settingsCatsScoped,
|
||
...skuCategorySuppliers,
|
||
]),
|
||
];
|
||
|
||
console.info(
|
||
`[bid] 邀请来源 categoryOnly=${categoryOnly} resolved=${resolved.length} preferred=${preferred.length} settingsCats=${settingsCats.length} settingsCatsScoped=${settingsCatsScoped.length} skuCat=${skuCategorySuppliers.length} manual=${manualCodes.length} total=${supplierCodes.length}`
|
||
);
|
||
if (!supplierCodes.length) {
|
||
throw httpError('没有可邀请的供应商,请手动指定或先绑定经营品类/供货关系');
|
||
}
|
||
|
||
const valid = await pool.query(
|
||
`SELECT supplier_code FROM suppliers
|
||
WHERE supplier_code = ANY($1::text[])
|
||
AND COALESCE(status, 10) IN (10, 20)`,
|
||
[supplierCodes]
|
||
);
|
||
supplierCodes = valid.rows.map((r) => String(r.supplier_code));
|
||
if (!supplierCodes.length) throw httpError('受邀供应商均不可用');
|
||
}
|
||
|
||
const respondMinutes = Number(round.respond_minutes) || 30;
|
||
const openedAt = new Date();
|
||
const deadline = resolveQuoteRespondDeadline(
|
||
{
|
||
quote_window_start: settings.quote_window_start,
|
||
quote_window_end: settings.quote_window_end,
|
||
respond_minutes: respondMinutes,
|
||
},
|
||
openedAt
|
||
);
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
if (allDirect) {
|
||
await client.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'cancelled',
|
||
scheduled_open_at = NULL,
|
||
updated_at = NOW()
|
||
WHERE id = $1`,
|
||
[id]
|
||
);
|
||
} else {
|
||
await client.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'open',
|
||
opened_at = COALESCE(opened_at, $2),
|
||
respond_deadline = $3,
|
||
scheduled_open_at = NULL,
|
||
updated_at = NOW()
|
||
WHERE id = $1`,
|
||
[id, openedAt.toISOString(), deadline.toISOString()]
|
||
);
|
||
|
||
for (const code of supplierCodes) {
|
||
await client.query(
|
||
`INSERT INTO bid_invitations (round_id, supplier_code, status, invited_at, respond_deadline)
|
||
VALUES ($1, $2, 'pending', $3, $4)
|
||
ON CONFLICT (round_id, supplier_code) DO NOTHING`,
|
||
[id, code, openedAt.toISOString(), deadline.toISOString()]
|
||
);
|
||
}
|
||
|
||
if (designatedSkus.length) {
|
||
await client.query(
|
||
`DELETE FROM bid_round_items WHERE round_id = $1 AND sku_code = ANY($2::text[])`,
|
||
[id, designatedSkus]
|
||
);
|
||
}
|
||
}
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
let notifyResult:
|
||
| {
|
||
invited: number;
|
||
notifiedUsers: number;
|
||
notifiedSuppliers: number;
|
||
missingSupplierCodes: string[];
|
||
}
|
||
| undefined;
|
||
|
||
if (!allDirect) {
|
||
notifyResult = await notifySuppliersBidOpened({
|
||
roundId: id,
|
||
roundCode: String(round.round_code),
|
||
supplierCodes,
|
||
respondDeadline: deadline,
|
||
branchCode: input.branchCode,
|
||
orderCode: round.order_code != null ? String(round.order_code) : null,
|
||
}).catch((error) => {
|
||
console.warn('[bid] 发标通知失败:', error instanceof Error ? error.message : error);
|
||
return {
|
||
invited: supplierCodes.length,
|
||
notifiedUsers: 0,
|
||
notifiedSuppliers: 0,
|
||
missingSupplierCodes: supplierCodes,
|
||
};
|
||
});
|
||
|
||
if (notifyResult && notifyResult.missingSupplierCodes.length) {
|
||
console.warn(
|
||
`[bid] 发标 ${round.round_code}:邀请 ${notifyResult.invited} 家,通知账号 ${notifyResult.notifiedUsers};未绑定登录账号的供应商: ${notifyResult.missingSupplierCodes.join(',')}`
|
||
);
|
||
} else {
|
||
console.info(
|
||
`[bid] 发标 ${round.round_code}:邀请 ${supplierCodes.length} 家,通知账号 ${notifyResult?.notifiedUsers ?? 0}`
|
||
);
|
||
}
|
||
} else {
|
||
console.info(`[bid] 发标 ${round.round_code}:全部指定直供,跳过请报价通知`);
|
||
}
|
||
|
||
let allocationWarning: string | null = null;
|
||
if (allDirect && orderCode) {
|
||
try {
|
||
const { reprocessOrderAllocation } = await import('./orderAllocationService');
|
||
const orderRow = await pool.query(
|
||
`SELECT customer_code, branch_code FROM orders WHERE order_code = $1 LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (orderRow.rowCount) {
|
||
const allocation = await reprocessOrderAllocation(
|
||
orderCode,
|
||
orderRow.rows[0].customer_code ? String(orderRow.rows[0].customer_code) : null,
|
||
orderRow.rows[0].branch_code ? String(orderRow.rows[0].branch_code) : input.branchCode
|
||
);
|
||
if (allocation.errors.length) {
|
||
allocationWarning = allocation.errors.join(';');
|
||
}
|
||
}
|
||
} catch (error: unknown) {
|
||
allocationWarning =
|
||
error instanceof Error ? error.message : '指定直供后自动分配失败,请手动分配';
|
||
}
|
||
}
|
||
|
||
const detail = await getBidRoundDetail(id);
|
||
return {
|
||
...detail,
|
||
...(allocationWarning ? { allocation_warning: allocationWarning } : {}),
|
||
notify: notifyResult
|
||
? {
|
||
invited: notifyResult.invited,
|
||
notified_users: notifyResult.notifiedUsers,
|
||
notified_suppliers: notifyResult.notifiedSuppliers,
|
||
missing_supplier_codes: notifyResult.missingSupplierCodes,
|
||
}
|
||
: undefined,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 该供应商在这批商品里「可报价」的 SKU 集合。
|
||
*
|
||
* 判定依据(任一成立即可):
|
||
* - 商品分类落在该供应商的 `supplier_categories` 经营品类内(含一级分类祖先、裸码/前缀变体,
|
||
* 与邀请侧 `resolveCategoryInviteSuppliers` 同一套匹配,避免两边口径分叉);
|
||
* - 该商品与该供应商存在 `sku_suppliers` 供货关系(`status=1`)。
|
||
*
|
||
* 返回 `null` = 该供应商未配置经营品类 → **不做限制**(保持既有行为,避免误伤)。
|
||
* 商品本身没有分类时也不据此拦截。
|
||
*/
|
||
async function resolveSupplierQuotableSkus(
|
||
supplierCode: string,
|
||
skuCodes: string[],
|
||
branchCode?: string | null
|
||
): Promise<Set<string> | null> {
|
||
const code = String(supplierCode || '').trim();
|
||
const skus = [...new Set(skuCodes.map((s) => String(s || '').trim()).filter(Boolean))];
|
||
if (!code || !skus.length) return null;
|
||
|
||
const bindings = (
|
||
await pool.query(
|
||
`SELECT supplier_code, category_code FROM supplier_categories WHERE supplier_code = $1`,
|
||
[code]
|
||
)
|
||
).rows
|
||
.map((row) => ({
|
||
supplier_code: String(row.supplier_code || '').trim(),
|
||
category_code: String(row.category_code || '').trim(),
|
||
}))
|
||
.filter((row) => row.supplier_code && row.category_code);
|
||
if (!bindings.length) return null;
|
||
|
||
const [categoryRows, skuCatRows, relationRows] = await Promise.all([
|
||
fetchCategoryRows(branchCode).catch(() => [] as CategoryRow[]),
|
||
pool.query(
|
||
`SELECT sku_code, NULLIF(TRIM(category_code), '') AS category_code
|
||
FROM skus WHERE sku_code = ANY($1::text[])`,
|
||
[skus]
|
||
),
|
||
pool.query(
|
||
`SELECT DISTINCT sku_code FROM sku_suppliers
|
||
WHERE supplier_code = $1 AND COALESCE(status, 1) = 1 AND sku_code = ANY($2::text[])`,
|
||
[code, skus]
|
||
),
|
||
]);
|
||
|
||
const categoryBySku = new Map<string, string>();
|
||
for (const row of skuCatRows.rows) {
|
||
const categoryCode = String(row.category_code || '').trim();
|
||
if (categoryCode) categoryBySku.set(String(row.sku_code), categoryCode);
|
||
}
|
||
const relationSkus = new Set(relationRows.rows.map((row) => String(row.sku_code)));
|
||
|
||
const allowed = new Set<string>();
|
||
for (const sku of skus) {
|
||
const categoryCode = categoryBySku.get(sku);
|
||
if (!categoryCode) {
|
||
// 商品未分类:无法判定归属,不据此拦截(与注释口径一致)
|
||
allowed.add(sku);
|
||
continue;
|
||
}
|
||
if (relationSkus.has(sku)) {
|
||
allowed.add(sku);
|
||
continue;
|
||
}
|
||
if (
|
||
resolveCategoryInviteSuppliers([categoryCode], categoryRows, bindings, branchCode).includes(code)
|
||
) {
|
||
allowed.add(sku);
|
||
}
|
||
}
|
||
return allowed;
|
||
}
|
||
|
||
export async function submitBidQuotes(input: {
|
||
roundId: string;
|
||
supplierCode: string;
|
||
quotes: Array<{ sku_code: string; unit_price: number; remark?: string | null }>;
|
||
createdBy?: string | null;
|
||
branchCode?: string | null;
|
||
}) {
|
||
await assertBidEnabled(input.branchCode);
|
||
const roundId = String(input.roundId || '').trim();
|
||
const supplierCode = String(input.supplierCode || '').trim();
|
||
if (!supplierCode) throw httpError('缺少供应商');
|
||
if (!Array.isArray(input.quotes) || !input.quotes.length) throw httpError('请至少提交一条报价');
|
||
|
||
await expireOverdueInvitations(roundId);
|
||
|
||
const roundRes = await pool.query(`SELECT * FROM bid_rounds WHERE id = $1 LIMIT 1`, [roundId]);
|
||
if (!roundRes.rowCount) throw httpError('竞价轮次不存在', 404, 'not_found');
|
||
const round = roundRes.rows[0];
|
||
if (round.status !== 'open') throw httpError('轮次未在报价中,无法提交');
|
||
|
||
const invite = await pool.query(
|
||
`SELECT * FROM bid_invitations WHERE round_id = $1 AND supplier_code = $2 LIMIT 1`,
|
||
[roundId, supplierCode]
|
||
);
|
||
if (!invite.rowCount) throw httpError('该供应商未被邀请参与本轮');
|
||
const invitation = invite.rows[0];
|
||
if (invitation.status === 'expired') {
|
||
throw httpError('已超过响应时限,本轮已出局,不可再报价');
|
||
}
|
||
if (new Date(invitation.respond_deadline).getTime() < Date.now() && invitation.status === 'pending') {
|
||
await pool.query(`UPDATE bid_invitations SET status = 'expired' WHERE id = $1`, [invitation.id]);
|
||
throw httpError('已超过响应时限,本轮已出局,不可再报价');
|
||
}
|
||
|
||
const itemRows = await pool.query(`SELECT sku_code FROM bid_round_items WHERE round_id = $1`, [roundId]);
|
||
const allowedSkus = new Set(itemRows.rows.map((r) => String(r.sku_code)));
|
||
|
||
/**
|
||
* 经营品类闸门:**被邀请 ≠ 授权供应某商品**。
|
||
* 邀请面会为「避免邀请过少」而按分类扩邀,若设置里的分类范围偏宽,与本轮商品无关的供应商也会收到邀请;
|
||
* 此前报价侧只校验「有邀请 + SKU 在本轮明细」,于是他们能看到并报出不属于自己品类的商品。
|
||
* 口径见 resolveSupplierQuotableSkus。
|
||
*/
|
||
const quotableSkus = await resolveSupplierQuotableSkus(
|
||
supplierCode,
|
||
[...allowedSkus],
|
||
input.branchCode
|
||
);
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
for (const raw of input.quotes) {
|
||
const skuCode = String(raw.sku_code || '').trim();
|
||
const unitPrice = Number(raw.unit_price);
|
||
if (!skuCode || !allowedSkus.has(skuCode)) {
|
||
throw httpError(`商品 ${skuCode || '(空)'} 不在本轮明细中`);
|
||
}
|
||
if (quotableSkus && !quotableSkus.has(skuCode)) {
|
||
throw httpError(`商品 ${skuCode} 不在你的经营品类内,无法报价`, 403, 'supplier_category_mismatch');
|
||
}
|
||
if (!Number.isFinite(unitPrice) || unitPrice <= 0) {
|
||
throw httpError(`商品 ${skuCode} 报价须大于 0`);
|
||
}
|
||
await client.query(
|
||
`INSERT INTO bid_quotes (
|
||
round_id, invitation_id, supplier_code, sku_code, unit_price, remark, created_by
|
||
) VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||
ON CONFLICT (round_id, supplier_code, sku_code)
|
||
DO UPDATE SET
|
||
unit_price = EXCLUDED.unit_price,
|
||
remark = EXCLUDED.remark,
|
||
updated_at = NOW()`,
|
||
[
|
||
roundId,
|
||
invitation.id,
|
||
supplierCode,
|
||
skuCode,
|
||
unitPrice,
|
||
raw.remark != null ? String(raw.remark) : null,
|
||
input.createdBy || null,
|
||
]
|
||
);
|
||
}
|
||
|
||
await client.query(
|
||
`UPDATE bid_invitations
|
||
SET status = 'quoted', quoted_at = COALESCE(quoted_at, NOW())
|
||
WHERE id = $1`,
|
||
[invitation.id]
|
||
);
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
// 全员报价后:若开启自动中标则立即按最低价确认并分配
|
||
try {
|
||
const settings = await getBidSettings(input.branchCode);
|
||
if (settings.auto_award_lowest) {
|
||
const pendingRes = await pool.query(
|
||
`SELECT COUNT(*)::int AS cnt FROM bid_invitations WHERE round_id = $1 AND status = 'pending'`,
|
||
[roundId]
|
||
);
|
||
if (Number(pendingRes.rows[0]?.cnt || 0) === 0) {
|
||
await tryAutoAwardAndAllocate(roundId, input.branchCode);
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.warn(
|
||
'[bid] 报价后自动中标检查失败:',
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
|
||
return getBidRoundDetail(roundId);
|
||
}
|
||
|
||
export async function closeBidRound(roundId: string, branchCode?: string | null) {
|
||
await assertBidEnabled(branchCode);
|
||
const id = String(roundId || '').trim();
|
||
await expireOverdueInvitations(id);
|
||
const result = await pool.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'closed', closed_at = NOW(), updated_at = NOW()
|
||
WHERE id = $1 AND status = 'open'
|
||
RETURNING id`,
|
||
[id]
|
||
);
|
||
if (!result.rowCount) throw httpError('仅进行中的轮次可截标');
|
||
await pool.query(
|
||
`UPDATE bid_invitations
|
||
SET status = 'expired'
|
||
WHERE round_id = $1 AND status = 'pending'`,
|
||
[id]
|
||
);
|
||
return getBidRoundDetail(id);
|
||
}
|
||
|
||
export async function confirmBidAwards(input: {
|
||
roundId: string;
|
||
awards?: Array<{ sku_code: string; supplier_code: string; unit_price?: number; quote_id?: string }>;
|
||
useSuggestedLowest?: boolean;
|
||
awardedBy?: string | null;
|
||
branchCode?: string | null;
|
||
/** open 态仍有未报价邀约时须显式确认,否则 409 pending_invites */
|
||
acknowledgePendingInvites?: boolean;
|
||
}) {
|
||
await assertBidEnabled(input.branchCode);
|
||
const id = String(input.roundId || '').trim();
|
||
await expireOverdueInvitations(id);
|
||
|
||
const roundRes = await pool.query(`SELECT * FROM bid_rounds WHERE id = $1 LIMIT 1`, [id]);
|
||
if (!roundRes.rowCount) throw httpError('竞价轮次不存在', 404, 'not_found');
|
||
const round = roundRes.rows[0];
|
||
if (!['open', 'closed', 'awarded'].includes(String(round.status))) {
|
||
throw httpError('当前状态不可确认中标');
|
||
}
|
||
|
||
const settingsBranch = await resolveSettingsBranchForRound(round, input.branchCode);
|
||
const settings = await getBidSettings(settingsBranch);
|
||
|
||
if (String(round.status) === 'open') {
|
||
const pendingRes = await pool.query(
|
||
`SELECT COUNT(*)::int AS cnt FROM bid_invitations WHERE round_id = $1 AND status = 'pending'`,
|
||
[id]
|
||
);
|
||
const pendingCount = Number(pendingRes.rows[0]?.cnt || 0);
|
||
if (pendingCount > 0 && !input.acknowledgePendingInvites) {
|
||
throw Object.assign(
|
||
new Error(
|
||
`仍有 ${pendingCount} 家供应商未报价。请先截标,或确认后继续(未报价供应商将出局)`
|
||
),
|
||
{ status: 409, code: 'pending_invites', pending_count: pendingCount }
|
||
);
|
||
}
|
||
}
|
||
|
||
const quotes = await pool.query(`SELECT * FROM bid_quotes WHERE round_id = $1`, [id]);
|
||
let awards = input.awards || [];
|
||
if (input.useSuggestedLowest || !awards.length) {
|
||
awards = await suggestAwardsForSettings({
|
||
quotes: quotes.rows,
|
||
settings,
|
||
branchCode: settingsBranch,
|
||
});
|
||
}
|
||
if (!awards.length) throw httpError('没有可确认的中标报价');
|
||
|
||
const quoteByKey = new Map(
|
||
quotes.rows.map((q) => [`${q.supplier_code}::${q.sku_code}`, q] as const)
|
||
);
|
||
|
||
const holdMinutes = Math.max(
|
||
0,
|
||
Math.min(10080, Number(settings.post_award_hold_allocation_minutes || 0))
|
||
);
|
||
|
||
let allocationHoldUntil: string | null = null;
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
for (const award of awards) {
|
||
const skuCode = String(award.sku_code || '').trim();
|
||
const supplierCode = String(award.supplier_code || '').trim();
|
||
if (!skuCode || !supplierCode) throw httpError('中标明细缺少商品或供应商');
|
||
|
||
const quote = quoteByKey.get(`${supplierCode}::${skuCode}`);
|
||
const unitPrice =
|
||
award.unit_price != null && Number(award.unit_price) > 0
|
||
? Number(award.unit_price)
|
||
: quote
|
||
? Number(quote.unit_price)
|
||
: NaN;
|
||
if (!Number.isFinite(unitPrice) || unitPrice <= 0) {
|
||
throw httpError(`商品 ${skuCode} 缺少有效中标价`);
|
||
}
|
||
if (!quote) {
|
||
throw httpError(`供应商 ${supplierCode} 未对商品 ${skuCode} 报价,不能中标`);
|
||
}
|
||
|
||
await client.query(
|
||
`INSERT INTO bid_awards (
|
||
round_id, sku_code, supplier_code, unit_price, quote_id, awarded_by
|
||
) VALUES ($1, $2, $3, $4, $5, $6)
|
||
ON CONFLICT (round_id, sku_code)
|
||
DO UPDATE SET
|
||
supplier_code = EXCLUDED.supplier_code,
|
||
unit_price = EXCLUDED.unit_price,
|
||
quote_id = EXCLUDED.quote_id,
|
||
awarded_by = EXCLUDED.awarded_by,
|
||
awarded_at = NOW()`,
|
||
[id, skuCode, supplierCode, unitPrice, quote.id, input.awardedBy || null]
|
||
);
|
||
}
|
||
|
||
if (holdMinutes > 0) {
|
||
const holdRes = await client.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'awarded',
|
||
closed_at = COALESCE(closed_at, NOW()),
|
||
allocation_hold_until = NOW() + ($2::int * INTERVAL '1 minute'),
|
||
allocation_hold_released_at = NULL,
|
||
updated_at = NOW()
|
||
WHERE id = $1
|
||
RETURNING allocation_hold_until`,
|
||
[id, holdMinutes]
|
||
);
|
||
allocationHoldUntil = holdRes.rows[0]?.allocation_hold_until
|
||
? new Date(holdRes.rows[0].allocation_hold_until).toISOString()
|
||
: null;
|
||
} else {
|
||
await client.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'awarded',
|
||
closed_at = COALESCE(closed_at, NOW()),
|
||
allocation_hold_until = NULL,
|
||
allocation_hold_released_at = NOW(),
|
||
updated_at = NOW()
|
||
WHERE id = $1`,
|
||
[id]
|
||
);
|
||
}
|
||
await client.query(
|
||
`UPDATE bid_invitations
|
||
SET status = 'expired'
|
||
WHERE round_id = $1 AND status = 'pending'`,
|
||
[id]
|
||
);
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
// hold=0:事务外立刻分配(兼容现网);hold>0 等 cron / 手调完成
|
||
let allocationWarning: string | null = null;
|
||
if (
|
||
holdMinutes <= 0 &&
|
||
String(round.cycle_mode) === 'per_order' &&
|
||
String(round.order_code || '').trim()
|
||
) {
|
||
try {
|
||
const { reprocessOrderAllocation } = await import('./orderAllocationService');
|
||
const orderCode = String(round.order_code).trim();
|
||
const orderRow = await pool.query(
|
||
`SELECT customer_code, branch_code FROM orders WHERE order_code = $1 LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (orderRow.rowCount) {
|
||
const allocation = await reprocessOrderAllocation(
|
||
orderCode,
|
||
orderRow.rows[0].customer_code ? String(orderRow.rows[0].customer_code) : null,
|
||
orderRow.rows[0].branch_code ? String(orderRow.rows[0].branch_code) : settingsBranch
|
||
);
|
||
if (allocation.errors.length) {
|
||
allocationWarning = allocation.errors.join(';');
|
||
}
|
||
}
|
||
} catch (error: unknown) {
|
||
allocationWarning =
|
||
error instanceof Error ? error.message : '中标后自动分配失败,请补价或手动分配';
|
||
}
|
||
}
|
||
|
||
const detail = await getBidRoundDetail(id, settingsBranch);
|
||
const extra: Record<string, unknown> = {};
|
||
if (allocationWarning) extra.allocation_warning = allocationWarning;
|
||
if (allocationHoldUntil) {
|
||
extra.allocation_hold_until = allocationHoldUntil;
|
||
extra.allocation_hold_message = `中标已确认,自动分配暂停至 ${allocationHoldUntil};可先手调,或点「手调完成,开始分配」`;
|
||
}
|
||
return Object.keys(extra).length ? { ...detail, ...extra } : detail;
|
||
}
|
||
|
||
/** 到点或管理员提前结束手调窗并(按每单)触发分配 */
|
||
export async function releaseBidAllocationHold(
|
||
roundId: string,
|
||
options?: { branchCode?: string | null; lazy?: boolean }
|
||
) {
|
||
const id = String(roundId || '').trim();
|
||
if (!id) throw httpError('轮次无效');
|
||
|
||
const roundRes = await pool.query(`SELECT * FROM bid_rounds WHERE id = $1 LIMIT 1`, [id]);
|
||
if (!roundRes.rowCount) throw httpError('竞价轮次不存在', 404, 'not_found');
|
||
const round = roundRes.rows[0];
|
||
if (String(round.status) !== 'awarded') {
|
||
throw httpError('仅已中标轮次可结束手调窗');
|
||
}
|
||
|
||
if (round.allocation_hold_released_at) {
|
||
if (options?.lazy) return { released: false, already: true };
|
||
return getBidRoundDetail(id, options?.branchCode);
|
||
}
|
||
|
||
const until = round.allocation_hold_until
|
||
? new Date(round.allocation_hold_until).getTime()
|
||
: null;
|
||
if (options?.lazy) {
|
||
if (until == null || until > Date.now()) {
|
||
return { released: false };
|
||
}
|
||
}
|
||
|
||
const { allocationWarning } = await applyAllocationHoldRelease(round, options?.branchCode);
|
||
|
||
if (options?.lazy) return { released: true };
|
||
|
||
const detail = await getBidRoundDetail(id, options?.branchCode);
|
||
return allocationWarning ? { ...detail, allocation_warning: allocationWarning } : detail;
|
||
}
|
||
|
||
async function applyAllocationHoldRelease(
|
||
round: Record<string, unknown>,
|
||
branchCode?: string | null
|
||
): Promise<{ allocationWarning: string | null }> {
|
||
const id = String(round.id || '');
|
||
await pool.query(
|
||
`UPDATE bid_rounds
|
||
SET allocation_hold_released_at = NOW(),
|
||
updated_at = NOW()
|
||
WHERE id = $1 AND allocation_hold_released_at IS NULL`,
|
||
[id]
|
||
);
|
||
|
||
let allocationWarning: string | null = null;
|
||
if (String(round.cycle_mode) === 'per_order' && String(round.order_code || '').trim()) {
|
||
try {
|
||
const { reprocessOrderAllocation } = await import('./orderAllocationService');
|
||
const orderCode = String(round.order_code).trim();
|
||
const orderRow = await pool.query(
|
||
`SELECT customer_code, branch_code FROM orders WHERE order_code = $1 LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (orderRow.rowCount) {
|
||
const allocation = await reprocessOrderAllocation(
|
||
orderCode,
|
||
orderRow.rows[0].customer_code ? String(orderRow.rows[0].customer_code) : null,
|
||
orderRow.rows[0].branch_code ? String(orderRow.rows[0].branch_code) : branchCode
|
||
);
|
||
if (allocation.errors.length) {
|
||
allocationWarning = allocation.errors.join(';');
|
||
}
|
||
}
|
||
} catch (error: unknown) {
|
||
allocationWarning =
|
||
error instanceof Error ? error.message : '放行后自动分配失败,请手动分配';
|
||
}
|
||
}
|
||
return { allocationWarning };
|
||
}
|
||
|
||
async function maybeLazyReleaseAllocationHold(roundId: string, branchCode?: string | null) {
|
||
try {
|
||
const row = await pool.query(`SELECT * FROM bid_rounds WHERE id = $1 LIMIT 1`, [roundId]);
|
||
if (!row.rowCount) return;
|
||
const r = row.rows[0];
|
||
if (String(r.status) !== 'awarded') return;
|
||
if (r.allocation_hold_released_at) return;
|
||
if (!r.allocation_hold_until) return;
|
||
if (new Date(r.allocation_hold_until).getTime() > Date.now()) return;
|
||
await applyAllocationHoldRelease(r, branchCode);
|
||
} catch (err) {
|
||
console.warn('[bid] lazy release allocation hold failed', err);
|
||
}
|
||
}
|
||
|
||
export async function cancelBidRound(roundId: string, branchCode?: string | null) {
|
||
await assertBidEnabled(branchCode);
|
||
const id = String(roundId || '').trim();
|
||
const result = await pool.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'cancelled', updated_at = NOW()
|
||
WHERE id = $1 AND status IN ('draft', 'open')
|
||
RETURNING id`,
|
||
[id]
|
||
);
|
||
if (!result.rowCount) throw httpError('仅草稿或进行中的轮次可取消');
|
||
return getBidRoundDetail(id);
|
||
}
|
||
|
||
/** 管理员删除历史轮次(级联清理明细/邀约/报价/中标) */
|
||
export async function deleteBidRound(roundId: string) {
|
||
const id = String(roundId || '').trim();
|
||
if (!id) throw httpError('轮次无效');
|
||
const result = await pool.query(`DELETE FROM bid_rounds WHERE id = $1 RETURNING id, round_code`, [
|
||
id,
|
||
]);
|
||
if (!result.rowCount) throw httpError('轮次不存在', 404, 'not_found');
|
||
return { id: String(result.rows[0].id), round_code: String(result.rows[0].round_code || '') };
|
||
}
|
||
|
||
/** 供应商端:我的竞价邀约列表 */
|
||
export async function listSupplierBidInvitations(supplierCode: string) {
|
||
const code = String(supplierCode || '').trim();
|
||
if (!code) return [];
|
||
await expireOverdueInvitationsForSupplier(code);
|
||
|
||
// 懒触发:本供应商涉及的、已过截止的 open 轮次尝试自动中标
|
||
try {
|
||
const overdue = await pool.query(
|
||
`SELECT DISTINCT r.id
|
||
FROM bid_invitations v
|
||
JOIN bid_rounds r ON r.id = v.round_id
|
||
WHERE v.supplier_code = $1
|
||
AND r.status IN ('open', 'closed')
|
||
AND r.respond_deadline IS NOT NULL
|
||
AND r.respond_deadline < NOW()
|
||
LIMIT 20`,
|
||
[code]
|
||
);
|
||
for (const row of overdue.rows) {
|
||
await maybeLazyAutoAwardRound(String(row.id));
|
||
}
|
||
} catch (error) {
|
||
console.warn(
|
||
'[bid] 供应商列表懒触发自动中标失败:',
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
|
||
const result = await pool.query(
|
||
`SELECT v.*,
|
||
r.round_code, r.title, r.status AS round_status, r.cycle_mode, r.scope_type,
|
||
r.order_code, r.respond_minutes, r.respond_deadline AS round_respond_deadline,
|
||
r.opened_at,
|
||
(SELECT COUNT(*)::int FROM bid_round_items i WHERE i.round_id = r.id) AS item_count
|
||
FROM bid_invitations v
|
||
JOIN bid_rounds r ON r.id = v.round_id
|
||
WHERE v.supplier_code = $1
|
||
AND r.status IN ('open', 'closed', 'awarded')
|
||
ORDER BY v.invited_at DESC
|
||
LIMIT 100`,
|
||
[code]
|
||
);
|
||
return result.rows;
|
||
}
|
||
|
||
/**
|
||
* 供应商首页角标:待报价邀约数(pending + 轮次 open + 未过报价截止)。
|
||
* 只 COUNT,不做列表接口里的惰性 expired/自动中标写操作。
|
||
*/
|
||
export async function countSupplierPendingBidInvitations(supplierCode: string): Promise<number> {
|
||
const code = String(supplierCode || '').trim();
|
||
if (!code) return 0;
|
||
const result = await pool.query(
|
||
`SELECT COUNT(*)::int AS c
|
||
FROM bid_invitations v
|
||
JOIN bid_rounds r ON r.id = v.round_id
|
||
WHERE v.supplier_code = $1
|
||
AND v.status = 'pending'
|
||
AND r.status = 'open'
|
||
AND v.respond_deadline > NOW()`,
|
||
[code]
|
||
);
|
||
return Number(result.rows[0]?.c) || 0;
|
||
}
|
||
|
||
async function expireOverdueInvitationsForSupplier(supplierCode: string) {
|
||
await pool.query(
|
||
`UPDATE bid_invitations
|
||
SET status = 'expired'
|
||
WHERE supplier_code = $1
|
||
AND status = 'pending'
|
||
AND respond_deadline < NOW()`,
|
||
[supplierCode]
|
||
);
|
||
}
|
||
|
||
/** 供应商端:轮次详情(仅本供应商视角) */
|
||
export async function getSupplierBidRoundDetail(
|
||
roundId: string,
|
||
supplierCode: string,
|
||
branchCode?: string | null
|
||
) {
|
||
const detail = await getBidRoundDetail(roundId);
|
||
const code = String(supplierCode || '').trim();
|
||
const invitation = (detail.invitations || []).find(
|
||
(row: any) => String(row.supplier_code) === code
|
||
);
|
||
if (!invitation) {
|
||
throw httpError('无权查看本轮竞价', 403, 'forbidden');
|
||
}
|
||
// 只下发该供应商经营品类内(或有供货关系)的明细:邀请偏宽时他们不该看到别人的品
|
||
const quotable = await resolveSupplierQuotableSkus(
|
||
code,
|
||
(detail.items || []).map((row: any) => String(row.sku_code || '')),
|
||
branchCode
|
||
);
|
||
const items = quotable
|
||
? (detail.items || []).filter((row: any) => quotable.has(String(row.sku_code || '')))
|
||
: detail.items;
|
||
return {
|
||
round: detail.round,
|
||
items,
|
||
invitation,
|
||
my_quotes: (detail.quotes || []).filter((q: any) => String(q.supplier_code) === code),
|
||
awards: (detail.awards || []).filter((a: any) => String(a.supplier_code) === code),
|
||
};
|
||
}
|
||
|
||
/** 按每单自动发标闸门:所有分配入口共用,避免仅挂在某一提交函数上 */
|
||
export type PerOrderAutoBidGate = {
|
||
/** 暂缓智能分配 */
|
||
defer: boolean;
|
||
/** 事务提交后需调用 autoStartPerOrderBid */
|
||
needsAutoStart: boolean;
|
||
message?: string;
|
||
roundId?: string;
|
||
existingStatus?: string;
|
||
};
|
||
|
||
/**
|
||
* 判断待分配订单是否应暂缓分配并(必要时)自动发标。
|
||
* - enabled + per_order_mode=auto + 状态 20:无中标轮则 defer
|
||
* - 已 awarded:放行分配(强制中标商)
|
||
* - cancelled:可再自动发标
|
||
* - 截止且无人报价:截标并放行智能分配(不重开一轮)
|
||
*/
|
||
export async function resolvePerOrderAutoBidGate(input: {
|
||
orderCode: string;
|
||
branchCode?: string | null;
|
||
orderStatus?: number | null;
|
||
skip?: boolean;
|
||
}): Promise<PerOrderAutoBidGate> {
|
||
if (input.skip) return { defer: false, needsAutoStart: false };
|
||
if (Number(input.orderStatus ?? 20) !== 20) return { defer: false, needsAutoStart: false };
|
||
|
||
let settings;
|
||
try {
|
||
settings = await getBidSettings(input.branchCode);
|
||
} catch {
|
||
return { defer: false, needsAutoStart: false };
|
||
}
|
||
if (
|
||
!settings.enabled ||
|
||
settings.cycle_type !== 'per_order' ||
|
||
settings.per_order_mode !== 'auto'
|
||
) {
|
||
return { defer: false, needsAutoStart: false };
|
||
}
|
||
|
||
const orderCode = String(input.orderCode || '').trim();
|
||
if (!orderCode) return { defer: false, needsAutoStart: false };
|
||
|
||
const existing = await pool.query(
|
||
`SELECT id, status, allocation_hold_until, allocation_hold_released_at, scheduled_open_at FROM bid_rounds
|
||
WHERE order_code = $1 AND cycle_mode = 'per_order'
|
||
ORDER BY created_at DESC
|
||
LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (existing.rowCount) {
|
||
let status = String(existing.rows[0].status || '');
|
||
const roundId = String(existing.rows[0].id);
|
||
|
||
// 自动中标:截止前看开关;截止后有报价必中标(闸门内判断)
|
||
if (status === 'open' || status === 'closed') {
|
||
const auto = await tryAutoAwardAndAllocate(roundId, input.branchCode);
|
||
if (auto.awarded || auto.reason === 'already_awarded') {
|
||
status = 'awarded';
|
||
} else {
|
||
const refreshed = await pool.query(
|
||
`SELECT status, allocation_hold_until, allocation_hold_released_at FROM bid_rounds WHERE id = $1`,
|
||
[roundId]
|
||
);
|
||
status = String(refreshed.rows[0]?.status || status);
|
||
if (refreshed.rowCount) {
|
||
existing.rows[0] = { ...existing.rows[0], ...refreshed.rows[0] };
|
||
}
|
||
}
|
||
}
|
||
|
||
if (status === 'awarded') {
|
||
await maybeLazyReleaseAllocationHold(roundId, input.branchCode);
|
||
const holdRow = await pool.query(
|
||
`SELECT allocation_hold_until, allocation_hold_released_at FROM bid_rounds WHERE id = $1`,
|
||
[roundId]
|
||
);
|
||
if (holdRow.rowCount && isAllocationHoldActive(holdRow.rows[0])) {
|
||
return {
|
||
defer: true,
|
||
needsAutoStart: false,
|
||
roundId,
|
||
existingStatus: status,
|
||
message: '竞价已中标,处于手调窗口:请改派后点「手调完成,开始分配」,或等待窗口结束',
|
||
};
|
||
}
|
||
return { defer: false, needsAutoStart: false, roundId, existingStatus: status };
|
||
}
|
||
if (status === 'cancelled') {
|
||
return {
|
||
defer: true,
|
||
needsAutoStart: true,
|
||
roundId,
|
||
existingStatus: status,
|
||
message: '已自动发起竞价,确认中标后将强制分配中标供应商',
|
||
};
|
||
}
|
||
if (status === 'open' || status === 'closed') {
|
||
const empty = await closeRoundIfEmptyQuotesPastDeadline(roundId);
|
||
if (empty.released) {
|
||
return {
|
||
defer: false,
|
||
needsAutoStart: false,
|
||
roundId,
|
||
existingStatus: 'closed',
|
||
message: EMPTY_QUOTE_RELEASE_MESSAGE,
|
||
};
|
||
}
|
||
status = empty.status || status;
|
||
}
|
||
// draft:无预约时刻 = 发标中断,立刻补开;未到点排队则禁止补开
|
||
if (status === 'draft') {
|
||
if (isQueuedDraftWaiting(existing.rows[0].scheduled_open_at)) {
|
||
const at = new Date(String(existing.rows[0].scheduled_open_at));
|
||
return {
|
||
defer: true,
|
||
needsAutoStart: false,
|
||
roundId,
|
||
existingStatus: status,
|
||
message: `等待报价时段 ${formatChinaHm(at)} 开始后再发标`,
|
||
};
|
||
}
|
||
return {
|
||
defer: true,
|
||
needsAutoStart: true,
|
||
roundId,
|
||
existingStatus: status,
|
||
message: '已自动发起竞价,确认中标后将强制分配中标供应商',
|
||
};
|
||
}
|
||
return {
|
||
defer: true,
|
||
needsAutoStart: false,
|
||
roundId,
|
||
existingStatus: status,
|
||
message:
|
||
status === 'closed'
|
||
? '竞价已截标,系统将按评标规则自动中标并分配(无人报价则走智能分配)'
|
||
: settings.auto_award_lowest
|
||
? '竞价进行中,全部报价或超时后将按评标规则自动中标并分配'
|
||
: '竞价进行中,截止后将按评标规则自动中标;也可提前确认中标',
|
||
};
|
||
}
|
||
|
||
return {
|
||
defer: true,
|
||
needsAutoStart: true,
|
||
message: '已自动发起竞价,确认中标后将强制分配中标供应商',
|
||
};
|
||
}
|
||
|
||
/** 这些 reason 必须整单 skip 闸门且不带 exclude(无人报价/中标/取消/关闭竞价) */
|
||
export const BID_DEGRADE_FULL_ALLOC_REASONS: ReadonlySet<string> = new Set([
|
||
'already_awarded',
|
||
'empty_quotes_released',
|
||
'cancelled',
|
||
'bid_disabled',
|
||
'period_mode',
|
||
'manual_mode',
|
||
]);
|
||
|
||
export function shouldKeepBidExcludeOnAllocFallback(input: {
|
||
excludeSkuCodes: string[];
|
||
hasActivePerOrderRound: boolean;
|
||
reason?: string | null;
|
||
}): boolean {
|
||
const exclude = [
|
||
...new Set((input.excludeSkuCodes || []).map((c) => String(c || '').trim()).filter(Boolean)),
|
||
];
|
||
if (!exclude.length) return false;
|
||
const reason = String(input.reason || '').trim();
|
||
if (BID_DEGRADE_FULL_ALLOC_REASONS.has(reason)) return false;
|
||
return input.hasActivePerOrderRound === true;
|
||
}
|
||
|
||
export async function hasActivePerOrderBidRound(orderCode: string): Promise<boolean> {
|
||
const code = String(orderCode || '').trim();
|
||
if (!code) return false;
|
||
const result = await pool.query(
|
||
`SELECT 1 FROM bid_rounds
|
||
WHERE order_code = $1
|
||
AND cycle_mode = 'per_order'
|
||
AND status IN ('open', 'closed')
|
||
LIMIT 1`,
|
||
[code]
|
||
);
|
||
return Boolean(result.rowCount);
|
||
}
|
||
|
||
export async function resolvePerOrderBidSkipGateAllocOptions(input: {
|
||
orderCode: string;
|
||
excludeSkuCodes?: string[];
|
||
started?: { ok?: boolean; reason?: string };
|
||
}): Promise<{ skipPerOrderAutoBidGate: true; excludeSkuCodes?: string[] }> {
|
||
const excludeSkuCodes = [
|
||
...new Set((input.excludeSkuCodes || []).map((c) => String(c || '').trim()).filter(Boolean)),
|
||
];
|
||
const hasActivePerOrderRound = await hasActivePerOrderBidRound(input.orderCode);
|
||
const keep = shouldKeepBidExcludeOnAllocFallback({
|
||
excludeSkuCodes,
|
||
hasActivePerOrderRound,
|
||
reason: input.started?.reason,
|
||
});
|
||
if (keep) return { skipPerOrderAutoBidGate: true, excludeSkuCodes };
|
||
return { skipPerOrderAutoBidGate: true };
|
||
}
|
||
|
||
/** 事务外执行自动发标;失败返回 false(调用方应回退普通分配) */
|
||
export async function runPerOrderAutoBidAfterDefer(input: {
|
||
orderCode: string;
|
||
branchCode?: string | null;
|
||
createdBy?: string | null;
|
||
}): Promise<{ ok: boolean; roundId?: string; reason?: string }> {
|
||
try {
|
||
const started = await autoStartPerOrderBid(input);
|
||
if (started.started) return { ok: true, roundId: started.roundId, reason: started.reason };
|
||
// 已有进行中/待确认轮次视为成功暂缓;已中标则应走分配(不算 ok)
|
||
if (started.reason === 'already_exists') {
|
||
const st = String(started.existingStatus || '');
|
||
const roundId = started.roundId;
|
||
if (st === 'awarded') return { ok: false, roundId, reason: 'already_awarded' };
|
||
if (st === 'cancelled') return { ok: false, roundId, reason: 'cancelled' };
|
||
if ((st === 'open' || st === 'closed') && roundId) {
|
||
const empty = await closeRoundIfEmptyQuotesPastDeadline(roundId);
|
||
if (empty.released) {
|
||
return { ok: false, roundId, reason: 'empty_quotes_released' };
|
||
}
|
||
}
|
||
// 草稿:未到预约开标不补开;无时刻或已到点则补发标
|
||
if (st === 'draft' && roundId) {
|
||
const queued = await pool.query(
|
||
`SELECT scheduled_open_at FROM bid_rounds WHERE id = $1 AND status = 'draft' LIMIT 1`,
|
||
[roundId]
|
||
);
|
||
if (queued.rowCount && isQueuedDraftWaiting(queued.rows[0].scheduled_open_at)) {
|
||
return { ok: true, roundId, reason: 'queued_until_window' };
|
||
}
|
||
try {
|
||
await openBidRound({ roundId, branchCode: input.branchCode });
|
||
return { ok: true, roundId, reason: 'opened_draft' };
|
||
} catch {
|
||
await pool
|
||
.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'cancelled', updated_at = NOW()
|
||
WHERE id = $1 AND status = 'draft'`,
|
||
[roundId]
|
||
)
|
||
.catch(() => undefined);
|
||
return { ok: false, roundId, reason: 'open_draft_failed' };
|
||
}
|
||
}
|
||
return { ok: true, roundId, reason: started.reason };
|
||
}
|
||
return { ok: false, roundId: started.roundId, reason: started.reason };
|
||
} catch {
|
||
return { ok: false, reason: 'start_failed' };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 本单在竞价范围内、且库存抵扣后仍有净需求的 SKU。
|
||
* 须在 applyStockCoverForOrder 之后调用(或 stock_cover_qty 已正确)。
|
||
*/
|
||
export async function listOrderSkusNeedingBidProcure(input: {
|
||
orderCode: string;
|
||
branchCode?: string | null;
|
||
client?: Pick<PoolClient, 'query'>;
|
||
}): Promise<string[]> {
|
||
const db = input.client || pool;
|
||
const orderCode = String(input.orderCode || '').trim();
|
||
if (!orderCode) return [];
|
||
|
||
let settings;
|
||
try {
|
||
settings = await getBidSettings(input.branchCode);
|
||
} catch {
|
||
return [];
|
||
}
|
||
if (!settings.enabled) return [];
|
||
|
||
const allowedSkus = new Set(settings.sku_codes || []);
|
||
const selectedCats = settings.category_codes || [];
|
||
if (!allowedSkus.size && !selectedCats.length) return [];
|
||
|
||
const expandedCats =
|
||
selectedCats.length > 0
|
||
? await expandCategoryCodes(selectedCats, input.branchCode)
|
||
: new Set<string>();
|
||
|
||
const items = await db.query(
|
||
`SELECT oi.sku_code,
|
||
s.category_code AS sku_category_code,
|
||
ARRAY_AGG(DISTINCT NULLIF(TRIM(oi.category_code), '')) FILTER (
|
||
WHERE NULLIF(TRIM(oi.category_code), '') IS NOT NULL
|
||
) AS item_category_codes,
|
||
ARRAY_AGG(DISTINCT NULLIF(TRIM(oi.supplier_code), '')) FILTER (
|
||
WHERE NULLIF(TRIM(oi.supplier_code), '') IS NOT NULL
|
||
) AS suppliers,
|
||
SUM(GREATEST(0, COALESCE(oi.quantity, 0) - COALESCE(oi.stock_cover_qty, 0)))::float AS procure_qty
|
||
FROM order_items oi
|
||
LEFT JOIN skus s ON s.sku_code = oi.sku_code
|
||
WHERE oi.order_code = $1
|
||
AND NULLIF(TRIM(oi.sku_code), '') IS NOT NULL
|
||
AND NOT (
|
||
NULLIF(TRIM(oi.processing_method), '') IS NOT NULL
|
||
AND TRIM(oi.processing_method) <> '原材料'
|
||
AND LOWER(TRIM(COALESCE(oi.processing_owner, ''))) = 'warehouse'
|
||
)
|
||
GROUP BY oi.sku_code, s.category_code
|
||
HAVING SUM(GREATEST(0, COALESCE(oi.quantity, 0) - COALESCE(oi.stock_cover_qty, 0))) > 1e-9`,
|
||
[orderCode]
|
||
);
|
||
|
||
const catInBidScope = (code: string) => {
|
||
if (!code || !expandedCats.size) return false;
|
||
return categoryInExpandedSet(code, expandedCats, input.branchCode);
|
||
};
|
||
|
||
const inScope = items.rows
|
||
.map((r) => {
|
||
const suppliers = Array.isArray(r.suppliers)
|
||
? (r.suppliers as unknown[]).map((s) => String(s || ''))
|
||
: [];
|
||
const itemCats = Array.isArray(r.item_category_codes)
|
||
? (r.item_category_codes as unknown[]).map((c) => String(c || '').trim()).filter(Boolean)
|
||
: [];
|
||
const skuCat = r.sku_category_code != null ? String(r.sku_category_code).trim() : '';
|
||
const orderLineSupplier = suppliers.find((s) => isRealBidSupplier(s)) || null;
|
||
const sku_code = String(r.sku_code || '').trim();
|
||
const inScopeByCat = catInBidScope(skuCat) || itemCats.some((c) => catInBidScope(c));
|
||
return {
|
||
sku_code,
|
||
category_code: itemCats.find((c) => catInBidScope(c)) || skuCat,
|
||
supplier_code: orderLineSupplier,
|
||
inScope: Boolean(sku_code && (allowedSkus.has(sku_code) || inScopeByCat)),
|
||
};
|
||
})
|
||
.filter((r) => r.inScope);
|
||
|
||
const designated = await resolveDesignatedSuppliersBySku({
|
||
skuRows: inScope,
|
||
settings,
|
||
branchCode: input.branchCode,
|
||
});
|
||
|
||
return [...new Set(inScope.map((r) => r.sku_code).filter((sku) => !designated.has(sku)))];
|
||
}
|
||
|
||
/**
|
||
* 订单列表把某行改为自采后:若该 SKU 在本单已无未分配净需求,从进行中的按单轮次去掉该 SKU。
|
||
* 不改 listOrderSkusNeedingBidProcure 的全局口径。
|
||
*/
|
||
export async function dropSkusFromActivePerOrderBidRoundsIfNoUnassignedRemain(input: {
|
||
orderCode: string;
|
||
skuCodes: string[];
|
||
client: Pick<PoolClient, 'query'>;
|
||
}): Promise<string[]> {
|
||
const orderCode = String(input.orderCode || '').trim();
|
||
const skuCodes = [...new Set((input.skuCodes || []).map((c) => String(c || '').trim()).filter(Boolean))];
|
||
if (!orderCode || !skuCodes.length) return [];
|
||
|
||
const remaining = await input.client.query(
|
||
`SELECT sku_code
|
||
FROM order_items
|
||
WHERE order_code = $1
|
||
AND sku_code = ANY($2::text[])
|
||
AND (
|
||
NULLIF(TRIM(supplier_code), '') IS NULL
|
||
OR TRIM(supplier_code) = 'UNASSIGNED'
|
||
)
|
||
AND GREATEST(0, COALESCE(quantity, 0) - COALESCE(stock_cover_qty, 0)) > 1e-9`,
|
||
[orderCode, skuCodes]
|
||
);
|
||
const stillUnassigned = new Set(
|
||
remaining.rows.map((row) => String(row.sku_code || '').trim()).filter(Boolean)
|
||
);
|
||
const toDrop = skuCodes.filter((sku) => !stillUnassigned.has(sku));
|
||
if (!toDrop.length) return [];
|
||
|
||
await input.client.query(
|
||
`DELETE FROM bid_round_items bri
|
||
USING bid_rounds br
|
||
WHERE bri.round_id = br.id
|
||
AND br.order_code = $1
|
||
AND br.cycle_mode = 'per_order'
|
||
AND br.status IN ('open', 'closed')
|
||
AND bri.sku_code = ANY($2::text[])`,
|
||
[orderCode, toDrop]
|
||
);
|
||
return toDrop;
|
||
}
|
||
|
||
/** 按每单自动发标:订单明细 SKU 建轮并立即邀请 */
|
||
export async function autoStartPerOrderBid(input: {
|
||
orderCode: string;
|
||
branchCode?: string | null;
|
||
createdBy?: string | null;
|
||
}): Promise<{ started: boolean; reason?: string; roundId?: string; existingStatus?: string }> {
|
||
const settings = await getBidSettings(input.branchCode);
|
||
if (!settings.enabled) return { started: false, reason: 'bid_disabled' };
|
||
if (settings.cycle_type !== 'per_order') return { started: false, reason: 'period_mode' };
|
||
if (settings.per_order_mode !== 'auto') return { started: false, reason: 'manual_mode' };
|
||
|
||
const orderCode = String(input.orderCode || '').trim();
|
||
if (!orderCode) return { started: false, reason: 'no_order' };
|
||
|
||
const existing = await pool.query(
|
||
`SELECT id, status FROM bid_rounds
|
||
WHERE order_code = $1
|
||
AND cycle_mode = 'per_order'
|
||
AND status IN ('draft', 'open', 'closed', 'awarded')
|
||
ORDER BY created_at DESC
|
||
LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (existing.rowCount) {
|
||
return {
|
||
started: false,
|
||
reason: 'already_exists',
|
||
roundId: String(existing.rows[0].id),
|
||
existingStatus: String(existing.rows[0].status || ''),
|
||
};
|
||
}
|
||
|
||
// ROLLBACK 后的发标路径:必须再落抵扣,再按净需求选品
|
||
await applyStockCoverForOrder(orderCode, input.branchCode);
|
||
/**
|
||
* ⚠️ 抵扣之后必须把「需求归零」的待采自采单一起归零(2026-10-12 真库事故 `ORD_API_20261012_BR003_0002`):
|
||
* 这里是**分配路线之外**唯一还会新落库存抵扣的地方;只抵扣不归零 ⇒ 那张空需求的待采单一直算
|
||
* 「未完成采购」⇒ 订单卡在 30 待备货。走统一入口(自建租户上下文/事务),失败只告警不阻断发标。
|
||
*/
|
||
try {
|
||
const { syncZeroDemandPurchasesAfterCover } = await import('./orderAllocationService');
|
||
await syncZeroDemandPurchasesAfterCover(orderCode, input.branchCode);
|
||
} catch (error: unknown) {
|
||
console.error(
|
||
`[bid] ${orderCode} 抵扣后同步需求归零自采单失败(不影响发标):`,
|
||
(error as Error)?.message || error
|
||
);
|
||
}
|
||
|
||
const skuCodes = await listOrderSkusNeedingBidProcure({
|
||
orderCode,
|
||
branchCode: input.branchCode,
|
||
});
|
||
if (!skuCodes.length) return { started: false, reason: 'no_procure_qty' };
|
||
|
||
const allowedSkus = new Set(settings.sku_codes || []);
|
||
const selectedCats = settings.category_codes || [];
|
||
const scopeType: BidScopeType =
|
||
selectedCats.length && !allowedSkus.size ? 'category' : 'sku';
|
||
|
||
const scheduledOpenAt = resolveScheduledOpenAt(settings);
|
||
const queueUntilWindow = Boolean(scheduledOpenAt);
|
||
|
||
const detail = await createBidRound({
|
||
title: `订单 ${orderCode} 自动竞价`,
|
||
cycleMode: 'per_order',
|
||
scopeType,
|
||
orderCode,
|
||
respondMinutes: settings.respond_minutes,
|
||
skuCodes,
|
||
categoryCodes: scopeType === 'category' ? selectedCats : undefined,
|
||
openImmediately: !queueUntilWindow,
|
||
scheduledOpenAt,
|
||
branchCode: input.branchCode,
|
||
createdBy: input.createdBy,
|
||
});
|
||
const roundId = String((detail as any)?.round?.id || '');
|
||
return {
|
||
started: true,
|
||
roundId,
|
||
reason: queueUntilWindow ? 'queued_until_window' : undefined,
|
||
};
|
||
}
|
||
|
||
/** 到点打开按每单排队草稿;订单已删则取消。不扫描 period draft。 */
|
||
export async function openDueQueuedPerOrderBids(branchCode?: string | null): Promise<{
|
||
opened: number;
|
||
cancelled: number;
|
||
}> {
|
||
const due = await pool.query(
|
||
`SELECT id, order_code
|
||
FROM bid_rounds
|
||
WHERE status = 'draft'
|
||
AND cycle_mode = 'per_order'
|
||
AND scheduled_open_at IS NOT NULL
|
||
AND scheduled_open_at <= NOW()
|
||
ORDER BY scheduled_open_at ASC
|
||
LIMIT 50`
|
||
);
|
||
let opened = 0;
|
||
let cancelled = 0;
|
||
for (const row of due.rows) {
|
||
const roundId = String(row.id);
|
||
const orderCode = String(row.order_code || '').trim();
|
||
const active = orderCode
|
||
? await pool.query(
|
||
`SELECT 1 FROM orders WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`,
|
||
[orderCode]
|
||
)
|
||
: { rowCount: 0 };
|
||
if (!active.rowCount) {
|
||
const gone = await pool.query(
|
||
`UPDATE bid_rounds
|
||
SET status = 'cancelled', scheduled_open_at = NULL, updated_at = NOW()
|
||
WHERE id = $1 AND status = 'draft'
|
||
RETURNING id`,
|
||
[roundId]
|
||
);
|
||
if (gone.rowCount) cancelled += 1;
|
||
continue;
|
||
}
|
||
try {
|
||
const still = await pool.query(
|
||
`SELECT status FROM bid_rounds WHERE id = $1 LIMIT 1`,
|
||
[roundId]
|
||
);
|
||
if (String(still.rows[0]?.status || '') !== 'draft') continue;
|
||
await openBidRound({ roundId, branchCode });
|
||
opened += 1;
|
||
} catch (error) {
|
||
console.warn(
|
||
`[bid] 排队开标失败 ${roundId}:`,
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
}
|
||
return { opened, cancelled };
|
||
}
|
||
|
||
/**
|
||
* 截止且有报价:主动自动中标(不依赖打开页面)。
|
||
* 中标后由 confirmBidAwards 写 hold 或立即分配。
|
||
*/
|
||
export async function awardDueQuotedBidRounds(branchCode?: string | null): Promise<{
|
||
awarded: number;
|
||
skipped: number;
|
||
}> {
|
||
const due = await pool.query(
|
||
`SELECT r.id
|
||
FROM bid_rounds r
|
||
WHERE r.respond_deadline IS NOT NULL
|
||
AND r.respond_deadline < NOW()
|
||
AND r.status IN ('open', 'closed')
|
||
AND (
|
||
EXISTS (
|
||
SELECT 1 FROM bid_invitations v
|
||
WHERE v.round_id = r.id AND v.status = 'quoted'
|
||
)
|
||
OR EXISTS (
|
||
SELECT 1 FROM bid_quotes q WHERE q.round_id = r.id
|
||
)
|
||
)
|
||
ORDER BY r.respond_deadline ASC
|
||
LIMIT 50`
|
||
);
|
||
let awarded = 0;
|
||
let skipped = 0;
|
||
for (const row of due.rows) {
|
||
const roundId = String(row.id);
|
||
try {
|
||
const result = await tryAutoAwardAndAllocate(roundId, branchCode);
|
||
if (result.awarded) awarded += 1;
|
||
else skipped += 1;
|
||
} catch (error) {
|
||
skipped += 1;
|
||
console.warn(
|
||
`[bid] 截止有报价自动中标失败 ${roundId}:`,
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
}
|
||
return { awarded, skipped };
|
||
}
|
||
|
||
/**
|
||
* 手调窗到期:主动放行并按中标商分配(per_order → reprocess,行齐则 20→30)。
|
||
*/
|
||
export async function releaseDueAllocationHolds(branchCode?: string | null): Promise<{
|
||
released: number;
|
||
failed: number;
|
||
}> {
|
||
const due = await pool.query(
|
||
`SELECT r.*
|
||
FROM bid_rounds r
|
||
WHERE r.status = 'awarded'
|
||
AND r.allocation_hold_until IS NOT NULL
|
||
AND r.allocation_hold_until <= NOW()
|
||
AND r.allocation_hold_released_at IS NULL
|
||
ORDER BY r.allocation_hold_until ASC
|
||
LIMIT 50`
|
||
);
|
||
let released = 0;
|
||
let failed = 0;
|
||
for (const row of due.rows) {
|
||
const roundId = String(row.id);
|
||
const orderCode = String(row.order_code || '').trim();
|
||
try {
|
||
const { allocationWarning } = await applyAllocationHoldRelease(row, branchCode);
|
||
released += 1;
|
||
if (allocationWarning) {
|
||
console.warn(
|
||
`[bid] 手调窗到期放行后分配有警告 round=${roundId} order=${orderCode}: ${allocationWarning}`
|
||
);
|
||
}
|
||
if (String(row.cycle_mode || '') === 'per_order' && orderCode) {
|
||
const st = await pool.query(
|
||
`SELECT order_status FROM orders
|
||
WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (st.rowCount && Number(st.rows[0].order_status) === 20) {
|
||
console.warn(
|
||
`[bid] 手调窗到期放行后订单仍为待分配 round=${roundId} order=${orderCode}` +
|
||
(allocationWarning ? `;${allocationWarning}` : '')
|
||
);
|
||
}
|
||
}
|
||
} catch (error) {
|
||
failed += 1;
|
||
console.warn(
|
||
`[bid] 手调窗到期放行失败 ${roundId}:`,
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
}
|
||
return { released, failed };
|
||
}
|
||
|
||
/**
|
||
* 中标且手调窗已放行,订单仍待分配:再次 reprocess(零价等失败时每分钟重试直至可进 30)。
|
||
*/
|
||
export async function retryStuckAwardedAllocations(branchCode?: string | null): Promise<{
|
||
retried: number;
|
||
advanced: number;
|
||
failed: number;
|
||
}> {
|
||
const due = await pool.query(
|
||
`SELECT r.id, r.order_code
|
||
FROM bid_rounds r
|
||
WHERE r.status = 'awarded'
|
||
AND r.cycle_mode = 'per_order'
|
||
AND r.allocation_hold_released_at IS NOT NULL
|
||
AND NULLIF(TRIM(COALESCE(r.order_code, '')), '') IS NOT NULL
|
||
AND EXISTS (
|
||
SELECT 1 FROM orders o
|
||
WHERE o.order_code = r.order_code
|
||
AND o.deleted_at IS NULL
|
||
AND o.order_status = 20
|
||
)
|
||
ORDER BY r.allocation_hold_released_at ASC NULLS LAST
|
||
LIMIT 50`
|
||
);
|
||
let retried = 0;
|
||
let advanced = 0;
|
||
let failed = 0;
|
||
for (const row of due.rows) {
|
||
const roundId = String(row.id);
|
||
const orderCode = String(row.order_code || '').trim();
|
||
if (!orderCode) continue;
|
||
retried += 1;
|
||
try {
|
||
const { reprocessOrderAllocation } = await import('./orderAllocationService');
|
||
const allocation = await reprocessOrderAllocation(
|
||
orderCode,
|
||
null,
|
||
branchCode ?? null,
|
||
undefined,
|
||
{ skipPerOrderAutoBidGate: true }
|
||
);
|
||
if (allocation.errors.length) {
|
||
console.warn(
|
||
`[bid] 中标后分配重试有错误 round=${roundId} order=${orderCode}: ${allocation.errors.join(';')}`
|
||
);
|
||
}
|
||
const st = await pool.query(
|
||
`SELECT order_status FROM orders
|
||
WHERE order_code = $1 AND deleted_at IS NULL LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (st.rowCount && Number(st.rows[0].order_status) === 30) {
|
||
advanced += 1;
|
||
} else if (st.rowCount && Number(st.rows[0].order_status) === 20) {
|
||
console.warn(
|
||
`[bid] 中标后分配重试后订单仍为待分配 round=${roundId} order=${orderCode}`
|
||
);
|
||
}
|
||
} catch (error) {
|
||
failed += 1;
|
||
console.warn(
|
||
`[bid] 中标后分配重试失败 ${roundId} ${orderCode}:`,
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
}
|
||
return { retried, advanced, failed };
|
||
}
|
||
|
||
/** 截止且无人报价:截标;按每单轮次且订单仍待分配则跑智能分配(供应商→自采) */
|
||
export async function releaseDueEmptyBidRounds(branchCode?: string | null): Promise<{
|
||
closed: number;
|
||
allocated: number;
|
||
}> {
|
||
const due = await pool.query(
|
||
`SELECT r.id, r.order_code, r.cycle_mode, r.status
|
||
FROM bid_rounds r
|
||
WHERE r.respond_deadline IS NOT NULL
|
||
AND r.respond_deadline < NOW()
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM bid_invitations v WHERE v.round_id = r.id AND v.status = 'quoted'
|
||
)
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM bid_quotes q WHERE q.round_id = r.id
|
||
)
|
||
AND (
|
||
r.status = 'open'
|
||
OR (
|
||
r.status = 'closed'
|
||
AND r.cycle_mode = 'per_order'
|
||
AND NULLIF(TRIM(COALESCE(r.order_code, '')), '') IS NOT NULL
|
||
AND EXISTS (
|
||
SELECT 1 FROM orders o
|
||
WHERE o.order_code = r.order_code
|
||
AND o.deleted_at IS NULL
|
||
AND o.order_status = 20
|
||
)
|
||
)
|
||
)
|
||
ORDER BY r.respond_deadline ASC
|
||
LIMIT 50`
|
||
);
|
||
let closed = 0;
|
||
let allocated = 0;
|
||
for (const row of due.rows) {
|
||
const roundId = String(row.id);
|
||
const wasOpen = String(row.status || '') === 'open';
|
||
const result = await closeRoundIfEmptyQuotesPastDeadline(roundId);
|
||
if (!result.released) continue;
|
||
if (wasOpen) closed += 1;
|
||
if (String(row.cycle_mode || '') !== 'per_order') continue;
|
||
const orderCode = String(row.order_code || '').trim();
|
||
if (!orderCode) continue;
|
||
const order = await pool.query(
|
||
`SELECT order_status FROM orders
|
||
WHERE order_code = $1 AND deleted_at IS NULL
|
||
LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (!order.rowCount || Number(order.rows[0].order_status) !== 20) continue;
|
||
try {
|
||
const { reprocessOrderAllocation } = await import('./orderAllocationService');
|
||
await reprocessOrderAllocation(orderCode, null, branchCode ?? null, undefined, {
|
||
skipPerOrderAutoBidGate: true,
|
||
});
|
||
allocated += 1;
|
||
} catch (error) {
|
||
console.warn(
|
||
`[bid] 无人报价改走分配失败 ${roundId} ${orderCode}:`,
|
||
error instanceof Error ? error.message : error
|
||
);
|
||
}
|
||
}
|
||
return { closed, allocated };
|
||
}
|
||
|
||
export async function listBidMeta(branchCode?: string | null) {
|
||
const settings = await getBidSettings(branchCode);
|
||
const [suppliers, skus, categories, lastSkuAwards, lastCatAwards, supplierCats] =
|
||
await Promise.all([
|
||
pool.query(
|
||
`SELECT supplier_code, company_name
|
||
FROM suppliers
|
||
WHERE COALESCE(status, 10) IN (10, 20)
|
||
ORDER BY company_name NULLS LAST, supplier_code
|
||
LIMIT 500`
|
||
),
|
||
pool.query(
|
||
`SELECT sku_code, sku_name, category_code, unit
|
||
FROM skus
|
||
WHERE COALESCE(status, 1) IN (1, 10, 20)
|
||
ORDER BY sku_name NULLS LAST, sku_code
|
||
LIMIT 2000`
|
||
),
|
||
fetchCategoryRows(branchCode),
|
||
pool.query(
|
||
`SELECT DISTINCT ON (a.sku_code)
|
||
a.sku_code,
|
||
a.supplier_code,
|
||
COALESCE(NULLIF(TRIM(s.company_name), ''), a.supplier_code) AS supplier_name
|
||
FROM bid_awards a
|
||
JOIN bid_rounds r ON r.id = a.round_id AND r.status = 'awarded'
|
||
LEFT JOIN suppliers s ON s.supplier_code = a.supplier_code
|
||
ORDER BY a.sku_code, a.awarded_at DESC NULLS LAST`
|
||
),
|
||
pool.query(
|
||
`SELECT DISTINCT ON (sk.category_code)
|
||
sk.category_code,
|
||
a.supplier_code,
|
||
COALESCE(NULLIF(TRIM(s.company_name), ''), a.supplier_code) AS supplier_name
|
||
FROM bid_awards a
|
||
JOIN bid_rounds r ON r.id = a.round_id AND r.status = 'awarded'
|
||
JOIN skus sk ON sk.sku_code = a.sku_code
|
||
LEFT JOIN suppliers s ON s.supplier_code = a.supplier_code
|
||
WHERE NULLIF(TRIM(sk.category_code), '') IS NOT NULL
|
||
ORDER BY sk.category_code, a.awarded_at DESC NULLS LAST`
|
||
),
|
||
pool.query(
|
||
`SELECT sc.supplier_code, sc.category_code, sc.is_primary
|
||
FROM supplier_categories sc
|
||
JOIN suppliers s ON s.supplier_code = sc.supplier_code
|
||
WHERE COALESCE(s.status, 10) IN (10, 20)
|
||
AND NULLIF(TRIM(sc.supplier_code), '') IS NOT NULL
|
||
AND NULLIF(TRIM(sc.category_code), '') IS NOT NULL`
|
||
),
|
||
]);
|
||
|
||
const last_awards_by_sku: Record<string, { supplier_code: string; supplier_name: string }> = {};
|
||
for (const row of lastSkuAwards.rows) {
|
||
last_awards_by_sku[String(row.sku_code)] = {
|
||
supplier_code: String(row.supplier_code),
|
||
supplier_name: String(row.supplier_name || row.supplier_code),
|
||
};
|
||
}
|
||
const last_awards_by_category: Record<string, { supplier_code: string; supplier_name: string }> =
|
||
{};
|
||
for (const row of lastCatAwards.rows) {
|
||
last_awards_by_category[String(row.category_code)] = {
|
||
supplier_code: String(row.supplier_code),
|
||
supplier_name: String(row.supplier_name || row.supplier_code),
|
||
};
|
||
}
|
||
|
||
const supplier_codes_by_category: Record<string, string[]> = {};
|
||
const primary_supplier_by_category: Record<string, string> = {};
|
||
for (const row of supplierCats.rows) {
|
||
const cat = String(row.category_code || '').trim();
|
||
const code = String(row.supplier_code || '').trim();
|
||
if (!cat || !code) continue;
|
||
if (!supplier_codes_by_category[cat]) supplier_codes_by_category[cat] = [];
|
||
if (!supplier_codes_by_category[cat].includes(code)) {
|
||
supplier_codes_by_category[cat].push(code);
|
||
}
|
||
if (row.is_primary === true && !primary_supplier_by_category[cat]) {
|
||
primary_supplier_by_category[cat] = code;
|
||
}
|
||
}
|
||
|
||
return {
|
||
settings,
|
||
suppliers: suppliers.rows,
|
||
skus: skus.rows,
|
||
categories: categories.map((c) => ({
|
||
category_code: c.category_code,
|
||
category_name: c.category_name,
|
||
parent_code: c.parent_code,
|
||
level: c.level,
|
||
})),
|
||
last_awards_by_sku,
|
||
last_awards_by_category,
|
||
supplier_codes_by_category,
|
||
primary_supplier_by_category,
|
||
};
|
||
}
|
||
|
||
/** 按设置开「本期」周期竞价并立即发标 */
|
||
export async function openCurrentPeriodBidRound(input: {
|
||
branchCode?: string | null;
|
||
createdBy?: string | null;
|
||
}) {
|
||
const settings = await assertBidEnabled(input.branchCode);
|
||
if (settings.cycle_type === 'per_order') {
|
||
throw httpError('当前为按每单模式,请先在竞价设置中改为天/周/月/时间段');
|
||
}
|
||
const { start, end } = resolveBidPeriodWindow(settings);
|
||
const dup = await pool.query(
|
||
`SELECT id, round_code, status
|
||
FROM bid_rounds
|
||
WHERE cycle_mode = 'period'
|
||
AND period_start = $1::date
|
||
AND period_end = $2::date
|
||
AND status IN ('open', 'awarded')
|
||
ORDER BY created_at DESC
|
||
LIMIT 1`,
|
||
[start, end]
|
||
);
|
||
if (dup.rowCount) {
|
||
throw httpError(
|
||
`本期(${start}~${end})已有${dup.rows[0].status === 'awarded' ? '中标' : '进行中'}轮次 ${dup.rows[0].round_code}`,
|
||
409,
|
||
'conflict'
|
||
);
|
||
}
|
||
|
||
const hasSku = (settings.sku_items || []).length > 0;
|
||
const hasCat = (settings.category_items || []).length > 0;
|
||
if (!hasSku && !hasCat) {
|
||
throw httpError('请先在竞价设置中配置商品或分类范围');
|
||
}
|
||
|
||
return createBidRound({
|
||
title: `周期竞价 ${start}~${end}`,
|
||
cycleMode: 'period',
|
||
scopeType: hasCat && !hasSku ? 'category' : 'sku',
|
||
periodStart: start,
|
||
periodEnd: end,
|
||
respondMinutes: settings.respond_minutes,
|
||
skuCodes: settings.sku_codes,
|
||
categoryCodes: settings.category_codes,
|
||
openImmediately: true,
|
||
branchCode: input.branchCode,
|
||
createdBy: input.createdBy,
|
||
});
|
||
}
|
||
|
||
/** 沿用已中标周期轮:复制中标到下一窗,无需供应商再报价 */
|
||
export async function renewBidRound(input: {
|
||
roundId: string;
|
||
branchCode?: string | null;
|
||
createdBy?: string | null;
|
||
periodStart?: string | null;
|
||
periodEnd?: string | null;
|
||
}) {
|
||
const settings = await assertBidEnabled(input.branchCode);
|
||
const roundId = String(input.roundId || '').trim();
|
||
if (!roundId) throw httpError('缺少轮次');
|
||
|
||
const roundRes = await pool.query(`SELECT * FROM bid_rounds WHERE id = $1 LIMIT 1`, [roundId]);
|
||
const round = roundRes.rows[0];
|
||
if (!round) throw httpError('轮次不存在', 404, 'not_found');
|
||
if (String(round.cycle_mode) !== 'period') {
|
||
throw httpError('仅周期竞价轮次可沿用');
|
||
}
|
||
if (String(round.status) !== 'awarded') {
|
||
throw httpError('仅已中标轮次可沿用');
|
||
}
|
||
|
||
let nextStart: string;
|
||
let nextEnd: string;
|
||
const bodyStart = String(input.periodStart || '').trim().slice(0, 10);
|
||
const bodyEnd = String(input.periodEnd || '').trim().slice(0, 10);
|
||
if (/^\d{4}-\d{2}-\d{2}$/.test(bodyStart) && /^\d{4}-\d{2}-\d{2}$/.test(bodyEnd)) {
|
||
if (bodyStart > bodyEnd) throw httpError('沿用起止日期无效');
|
||
nextStart = bodyStart;
|
||
nextEnd = bodyEnd;
|
||
} else {
|
||
const next = computeNextBidPeriodWindow(
|
||
String(round.period_start || ''),
|
||
String(round.period_end || ''),
|
||
settings.cycle_type === 'per_order' ? 'custom' : settings.cycle_type
|
||
);
|
||
nextStart = next.start;
|
||
nextEnd = next.end;
|
||
}
|
||
|
||
const dup = await pool.query(
|
||
`SELECT id, round_code, status
|
||
FROM bid_rounds
|
||
WHERE cycle_mode = 'period'
|
||
AND period_start = $1::date
|
||
AND period_end = $2::date
|
||
AND status IN ('open', 'awarded')
|
||
LIMIT 1`,
|
||
[nextStart, nextEnd]
|
||
);
|
||
if (dup.rowCount) {
|
||
throw httpError(
|
||
`下一周期(${nextStart}~${nextEnd})已有轮次 ${dup.rows[0].round_code}`,
|
||
409,
|
||
'conflict'
|
||
);
|
||
}
|
||
|
||
const awards = await pool.query(
|
||
`SELECT sku_code, supplier_code, unit_price
|
||
FROM bid_awards WHERE round_id = $1`,
|
||
[roundId]
|
||
);
|
||
if (!awards.rowCount) throw httpError('原轮次无中标记录,无法沿用');
|
||
|
||
const items = await pool.query(
|
||
`SELECT sku_code, sku_name, category_code, category_name, unit
|
||
FROM bid_round_items WHERE round_id = $1`,
|
||
[roundId]
|
||
);
|
||
|
||
const roundCode = await genRoundCode();
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
const inserted = await client.query(
|
||
`INSERT INTO bid_rounds (
|
||
round_code, title, cycle_mode, scope_type, order_code,
|
||
period_start, period_end, respond_minutes, status,
|
||
opened_at, closed_at, respond_deadline, created_by
|
||
) VALUES (
|
||
$1, $2, 'period', $3, NULL,
|
||
$4::date, $5::date, $6, 'awarded',
|
||
NOW(), NOW(), NOW(), $7
|
||
)
|
||
RETURNING id`,
|
||
[
|
||
roundCode,
|
||
`沿用 ${String(round.round_code || '')} → ${nextStart}~${nextEnd}`,
|
||
String(round.scope_type || 'sku'),
|
||
nextStart,
|
||
nextEnd,
|
||
Number(round.respond_minutes) || settings.respond_minutes,
|
||
input.createdBy || null,
|
||
]
|
||
);
|
||
const newId = String(inserted.rows[0].id);
|
||
|
||
for (const item of items.rows) {
|
||
await client.query(
|
||
`INSERT INTO bid_round_items (
|
||
round_id, sku_code, sku_name, category_code, category_name, unit
|
||
) VALUES ($1, $2, $3, $4, $5, $6)`,
|
||
[
|
||
newId,
|
||
item.sku_code,
|
||
item.sku_name,
|
||
item.category_code,
|
||
item.category_name,
|
||
item.unit,
|
||
]
|
||
);
|
||
}
|
||
|
||
for (const award of awards.rows) {
|
||
await client.query(
|
||
`INSERT INTO bid_awards (
|
||
round_id, sku_code, supplier_code, unit_price, quote_id, awarded_by, awarded_at
|
||
) VALUES ($1, $2, $3, $4, NULL, $5, NOW())`,
|
||
[
|
||
newId,
|
||
award.sku_code,
|
||
award.supplier_code,
|
||
award.unit_price,
|
||
input.createdBy || null,
|
||
]
|
||
);
|
||
}
|
||
|
||
await client.query('COMMIT');
|
||
return getBidRoundDetail(newId, input.branchCode);
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|