合并 feat/quote-price-sync 的报价单与竞价台账改动,补齐类型(includeDeleted/deletedAt)与缺失文件 (mainSystem/api/quotePriceProposals.ts、迁移 20261058)。
978 lines
39 KiB
TypeScript
978 lines
39 KiB
TypeScript
/**
|
||
* 主系统竞价「待报价」**接收端 + 我方镜像台账**(我方只报价、不定标)。
|
||
*
|
||
* 事实源在主系统:竞价轮次 / 邀约 / 我方报价 / 中标。本模块只做两件事:
|
||
* ① 把 `bid.opened` 推送(以及兜底拉取)落成**我方镜像**,让页面能显示「本轮要我报什么」;
|
||
* ② 提供一个**唯一**的派生口径 `deriveLocalStatus()`,把「对方事实」翻成页面上的 6 种状态。
|
||
*
|
||
* 幂等键 = 契约里的 `(round_id, supplier_code)`;我方再加 `branch_code`
|
||
* (一个分公司可能绑多个 supplier_code,各自独立受邀、独立报价)。
|
||
*
|
||
* 纪律:
|
||
* · **不回写主系统任何数据**(本文件零 `fetch`);
|
||
* · 镜像更新一律「以对方返回为准」:`applyBidDetail()` 会把本轮的明细/报价/中标**整轮重置后重写**,
|
||
* 避免对方撤回报价或改判后我方还留着旧值;
|
||
* · webhook 只带轮次头 + 商品名(没有价格),因此它**只 upsert 头与商品名**,
|
||
* 绝不覆盖我方已报的价格(`unit_price` 只由拉取详情 / 提交成功后的返回写)。
|
||
*
|
||
* 设计文档:docs/design/20261017-主系统竞价待报价与报价提交.md
|
||
*/
|
||
import { pool } from '../db';
|
||
import { listSupplierCodesForBranch } from './mainSystemBranchApi';
|
||
|
||
export type BidLocalStatus = 'pending' | 'quoted' | 'expired' | 'won' | 'lost' | 'cancelled';
|
||
export type BidRoundStatus = 'draft' | 'open' | 'closed' | 'awarded' | 'cancelled';
|
||
export type BidInvitationMainStatus = 'pending' | 'quoted' | 'expired';
|
||
|
||
export const BID_OPENED_EVENT = 'bid.opened' as const;
|
||
|
||
/** 列表页/详情页共用的邀约头 DTO(camelCase:前端直接用,不做二次映射) */
|
||
export type BidInvitationDto = {
|
||
roundId: string;
|
||
roundCode: string | null;
|
||
roundTitle: string | null;
|
||
orderCode: string | null;
|
||
supplierCode: string;
|
||
respondDeadline: string | null;
|
||
itemCount: number;
|
||
roundStatus: BidRoundStatus;
|
||
localStatus: BidLocalStatus;
|
||
quotedAt: string | null;
|
||
lastSyncedAt: string | null;
|
||
/** 本地软删除时间(NULL = 正常显示;2026-10-18 台账软删除) */
|
||
deletedAt: string | null;
|
||
};
|
||
|
||
export type BidInvitationItemDto = {
|
||
skuCode: string;
|
||
skuName: string | null;
|
||
unit: string | null;
|
||
unitPrice: number | null;
|
||
remark: string | null;
|
||
quotedAt: string | null;
|
||
awardPrice: number | null;
|
||
/** 对方 `bid_awards` 无数量列 ⇒ 恒 null(保留字段,对方将来加量时直接落库) */
|
||
awardQty: number | null;
|
||
/** `won` = 我方中标该行;`lost` = 本轮已定标但没有我方这行;`null` = 尚未定标 */
|
||
awardStatus: 'won' | 'lost' | null;
|
||
};
|
||
|
||
/** 我方中标行(只读;`bid_awards` 无数量列 ⇒ 无 qty) */
|
||
export type BidInvitationAwardDto = {
|
||
skuCode: string;
|
||
unitPrice: number | null;
|
||
};
|
||
|
||
export type BidInvitationDetailDto = {
|
||
invitation: BidInvitationDto;
|
||
items: BidInvitationItemDto[];
|
||
/** 本轮我方**中标**的行(对方轮次 awarded 才有值;空数组 = 未中标) */
|
||
myAwards: BidInvitationAwardDto[];
|
||
/** 页面是否允许提交(未过截止 + 轮次在报价中 + 未定标/取消) */
|
||
canQuote: boolean;
|
||
deadlinePassed: boolean;
|
||
syncError: string | null;
|
||
};
|
||
|
||
export type BidInvitationRow = {
|
||
id: string;
|
||
branch_code: string;
|
||
supplier_code: string;
|
||
round_id: string;
|
||
round_code: string | null;
|
||
round_title: string | null;
|
||
order_code: string | null;
|
||
respond_deadline: Date | string | null;
|
||
item_count: number;
|
||
round_status: BidRoundStatus;
|
||
main_invitation_status: BidInvitationMainStatus | null;
|
||
local_status: BidLocalStatus;
|
||
quoted_at: Date | string | null;
|
||
webhook_received_at: Date | string | null;
|
||
last_synced_at: Date | string | null;
|
||
sync_error: string | null;
|
||
/** 软删除:非空 = 本系统列表里隐藏(不通知主系统,可恢复) */
|
||
deleted_at?: Date | string | null;
|
||
deleted_by?: string | null;
|
||
payload: unknown;
|
||
created_at: Date | string;
|
||
updated_at: Date | string;
|
||
};
|
||
|
||
export type BidInvitationItemRow = {
|
||
id: string;
|
||
invitation_id: string;
|
||
branch_code: string;
|
||
round_id: string;
|
||
sku_code: string;
|
||
sku_name: string | null;
|
||
unit: string | null;
|
||
unit_price: string | number | null;
|
||
remark: string | null;
|
||
quoted_at: Date | string | null;
|
||
award_price: string | number | null;
|
||
award_qty: string | number | null;
|
||
award_status: 'won' | 'lost' | null;
|
||
};
|
||
|
||
/** webhook 载荷(对方 `notifySupplierBidOpened` 产出的业务体;信封另有 event/supplier_code 等) */
|
||
export type BidOpenedPayload = {
|
||
round_id?: unknown;
|
||
round_code?: unknown;
|
||
respond_deadline?: unknown;
|
||
order_code?: unknown;
|
||
item_count?: unknown;
|
||
items?: unknown;
|
||
};
|
||
|
||
function toIso(value: Date | string | null | undefined): string | null {
|
||
if (value === null || value === undefined || value === '') return null;
|
||
const date = value instanceof Date ? value : new Date(String(value));
|
||
if (Number.isNaN(date.getTime())) return null;
|
||
return date.toISOString();
|
||
}
|
||
|
||
function toNumber(value: unknown): number | null {
|
||
if (value === null || value === undefined || value === '') return null;
|
||
const num = Number(value);
|
||
return Number.isFinite(num) ? num : null;
|
||
}
|
||
|
||
function toText(value: unknown, max = 0): string | null {
|
||
if (value === null || value === undefined) return null;
|
||
const text = String(value).trim();
|
||
if (!text) return null;
|
||
return max > 0 ? text.slice(0, max) : text;
|
||
}
|
||
|
||
/** 只认主系统那一条推送事件(别的 `bid.*` 一律不接,避免误建台账) */
|
||
export function isBidOpenedEvent(event: unknown): boolean {
|
||
return String(event || '').trim() === BID_OPENED_EVENT;
|
||
}
|
||
|
||
/**
|
||
* **唯一**的「对方事实 → 我方视图状态」口径(页面 6 种状态全由它决定):
|
||
*
|
||
* 1. 轮次取消 ⇒ `cancelled`
|
||
* 2. 轮次已定标 ⇒ 我方有中标行 `won`;有明确落标事实 `lost`;两者都没有 ⇒ **不臆造未中标**,
|
||
* 报过价就回落 `quoted`,否则 `pending`(分不清"真没中标"与"结果还没拉到")
|
||
* 3. 已报(对方说 quoted,或本地每一行都有价)⇒ `quoted`
|
||
* 报价事实**优先于截止时间**:报过价、过了截止仍显示「已报价」,不被「已截止」吃掉
|
||
* 4. 邀约过期(对方说 expired,或截止时间已过)⇒ `expired`
|
||
* 5. 其余 ⇒ `pending`
|
||
*
|
||
* 注意顺序:**先看轮次**(已定标/取消比"过期"更权威),再看报价事实,最后看截止。
|
||
* 截止时间比较用**我方服务器时钟**(与主系统同机部署,偏差可忽略);最终裁决仍在对方。
|
||
*/
|
||
export function deriveLocalStatus(input: {
|
||
roundStatus: string;
|
||
mainInvitationStatus?: string | null;
|
||
respondDeadline?: Date | string | null;
|
||
itemCount: number;
|
||
quotedCount: number;
|
||
hasAward: boolean;
|
||
/** 我方**明确落标**事实(明细 `award_status='lost'`)。缺省视为未知,不得据此判「未中标」 */
|
||
hasLost?: boolean;
|
||
now?: Date;
|
||
}): BidLocalStatus {
|
||
const roundStatus = String(input.roundStatus || 'open');
|
||
if (roundStatus === 'cancelled') return 'cancelled';
|
||
|
||
const mainStatus = input.mainInvitationStatus ? String(input.mainInvitationStatus) : '';
|
||
const itemCount = Number(input.itemCount) || 0;
|
||
const quotedCount = Number(input.quotedCount) || 0;
|
||
/** 报过价:对方说 quoted,或本地每一行都有价(部分报价不算已报) */
|
||
const quoted = mainStatus === 'quoted' || (itemCount > 0 && quotedCount >= itemCount);
|
||
|
||
if (roundStatus === 'awarded') {
|
||
if (input.hasAward) return 'won';
|
||
if (input.hasLost) return 'lost';
|
||
/**
|
||
* 已定标:
|
||
* · 明细已拉到(itemCount>0)⇒ 我方没有中标行就是**对方的定标事实**,判未中标;
|
||
* · 明细还没拉到(itemCount=0)⇒ 分不清"真没中标"与"还没拉到",不臆造,回落已报价/待报价。
|
||
*/
|
||
if (itemCount > 0) return 'lost';
|
||
return quoted ? 'quoted' : 'pending';
|
||
}
|
||
|
||
if (quoted) return 'quoted';
|
||
|
||
const deadlineMs = input.respondDeadline ? new Date(input.respondDeadline).getTime() : NaN;
|
||
const nowMs = (input.now || new Date()).getTime();
|
||
const deadlinePassed = Number.isFinite(deadlineMs) && deadlineMs < nowMs;
|
||
if (mainStatus === 'expired' || deadlinePassed) return 'expired';
|
||
return 'pending';
|
||
}
|
||
|
||
export function toBidInvitationDto(row: BidInvitationRow): BidInvitationDto {
|
||
return {
|
||
roundId: String(row.round_id || ''),
|
||
roundCode: row.round_code ?? null,
|
||
roundTitle: row.round_title ?? null,
|
||
orderCode: row.order_code ?? null,
|
||
supplierCode: String(row.supplier_code || ''),
|
||
respondDeadline: toIso(row.respond_deadline),
|
||
itemCount: Number(row.item_count) || 0,
|
||
roundStatus: (row.round_status || 'open') as BidRoundStatus,
|
||
localStatus: (row.local_status || 'pending') as BidLocalStatus,
|
||
quotedAt: toIso(row.quoted_at),
|
||
lastSyncedAt: toIso(row.last_synced_at),
|
||
deletedAt: toIso(row.deleted_at),
|
||
};
|
||
}
|
||
|
||
export function toBidInvitationItemDto(
|
||
row: BidInvitationItemRow,
|
||
roundStatus: string
|
||
): BidInvitationItemDto {
|
||
const awardPrice = toNumber(row.award_price);
|
||
/**
|
||
* 中标判定**只认** `award_status`(won/lost)。`award_price` 非空不代表中标
|
||
* (对方字段可能回显我方报价),不得据此判 won。
|
||
*/
|
||
/**
|
||
* `won` **只认** `award_status`:`award_price` 非空可能只是对方回显我方报价,
|
||
* 不能据此判「已中标」(2026-10-18 开发者裁决)。
|
||
* `lost` = 明确落标,或整轮已定标(明细已拉到 ⇒ 我方没有中标行就是定标事实)。
|
||
*/
|
||
const awardStatus: 'won' | 'lost' | null =
|
||
row.award_status === 'won'
|
||
? 'won'
|
||
: row.award_status === 'lost'
|
||
? 'lost'
|
||
: String(roundStatus) === 'awarded'
|
||
? 'lost'
|
||
: null;
|
||
return {
|
||
skuCode: String(row.sku_code || ''),
|
||
skuName: row.sku_name ?? null,
|
||
unit: row.unit ?? null,
|
||
unitPrice: toNumber(row.unit_price),
|
||
remark: row.remark ?? null,
|
||
quotedAt: toIso(row.quoted_at),
|
||
awardPrice,
|
||
awardQty: toNumber(row.award_qty),
|
||
awardStatus,
|
||
};
|
||
}
|
||
|
||
/** 事务包装(与既有台账服务同写法:显式 BEGIN/COMMIT,异常 ROLLBACK,finally 释放连接) */
|
||
async function withTransaction<T>(fn: (client: any) => Promise<T>): Promise<T> {
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
const result = await fn(client);
|
||
await client.query('COMMIT');
|
||
return result;
|
||
} catch (error) {
|
||
try {
|
||
await client.query('ROLLBACK');
|
||
} catch {
|
||
/* 回滚失败不掩盖原始异常 */
|
||
}
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 重算 `local_status`(唯一写入口:所有会改变事实的路径写完都调它一次)。
|
||
*
|
||
* 为什么不写在 SQL 里:派生口径要与页面/测试**同一份实现**,写进 SQL 就等于藏了第二份口径。
|
||
*/
|
||
async function recomputeLocalStatus(client: any, invitationId: string): Promise<BidLocalStatus> {
|
||
const { rows } = await client.query(
|
||
`SELECT i.round_status,
|
||
i.main_invitation_status,
|
||
i.respond_deadline,
|
||
i.item_count,
|
||
(SELECT COUNT(*)::int FROM public.main_system_bid_invitation_items it
|
||
WHERE it.invitation_id = i.id AND it.unit_price IS NOT NULL) AS quoted_count,
|
||
EXISTS (SELECT 1 FROM public.main_system_bid_invitation_items it
|
||
WHERE it.invitation_id = i.id AND it.award_status = 'won') AS has_award,
|
||
EXISTS (SELECT 1 FROM public.main_system_bid_invitation_items it
|
||
WHERE it.invitation_id = i.id AND it.award_status = 'lost') AS has_lost,
|
||
(SELECT MAX(it.quoted_at) FROM public.main_system_bid_invitation_items it
|
||
WHERE it.invitation_id = i.id) AS quoted_at
|
||
FROM public.main_system_bid_invitations i
|
||
WHERE i.id = $1`,
|
||
[invitationId]
|
||
);
|
||
const row = rows[0];
|
||
if (!row) return 'pending';
|
||
const localStatus = deriveLocalStatus({
|
||
roundStatus: String(row.round_status || 'open'),
|
||
mainInvitationStatus: row.main_invitation_status,
|
||
respondDeadline: row.respond_deadline,
|
||
itemCount: Number(row.item_count) || 0,
|
||
quotedCount: Number(row.quoted_count) || 0,
|
||
hasAward: row.has_award === true,
|
||
hasLost: row.has_lost === true,
|
||
});
|
||
await client.query(
|
||
`UPDATE public.main_system_bid_invitations
|
||
SET local_status = $2, quoted_at = $3, updated_at = NOW()
|
||
WHERE id = $1`,
|
||
[invitationId, localStatus, row.quoted_at || null]
|
||
);
|
||
return localStatus;
|
||
}
|
||
|
||
/** upsert 邀约头(webhook 与拉取共用;字段语义见函数体注释) */
|
||
async function upsertInvitationHeader(
|
||
client: any,
|
||
input: {
|
||
branchCode: string;
|
||
supplierCode: string;
|
||
roundId: string;
|
||
roundCode?: string | null;
|
||
roundTitle?: string | null;
|
||
orderCode?: string | null;
|
||
respondDeadline?: string | null;
|
||
itemCount?: number | null;
|
||
roundStatus?: string | null;
|
||
mainInvitationStatus?: string | null;
|
||
fromWebhook?: boolean;
|
||
fromSync?: boolean;
|
||
/** 本次的 `itemCount` 是否权威(带明细的推送 / 拉详情):是则直接覆盖,退化的只增不减 */
|
||
fromDetailItems?: boolean;
|
||
payload?: unknown;
|
||
}
|
||
): Promise<string> {
|
||
const { rows } = await client.query(
|
||
`INSERT INTO public.main_system_bid_invitations AS i
|
||
(branch_code, supplier_code, round_id, round_code, round_title, order_code,
|
||
respond_deadline, item_count, round_status, main_invitation_status,
|
||
webhook_received_at, last_synced_at, sync_error, payload)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, 0), COALESCE($9, 'open'), $10,
|
||
CASE WHEN $11::boolean THEN NOW() ELSE NULL END,
|
||
CASE WHEN $12::boolean THEN NOW() ELSE NULL END,
|
||
NULL, $14::jsonb)
|
||
ON CONFLICT (branch_code, round_id, supplier_code) DO UPDATE SET
|
||
round_code = COALESCE(EXCLUDED.round_code, i.round_code),
|
||
round_title = COALESCE(EXCLUDED.round_title, i.round_title),
|
||
order_code = COALESCE(EXCLUDED.order_code, i.order_code),
|
||
respond_deadline = COALESCE(EXCLUDED.respond_deadline, i.respond_deadline),
|
||
-- 权威来源(拉详情 / 带明细的推送)按实际行数覆盖;退化载荷(无明细)只增不减
|
||
item_count = CASE
|
||
WHEN $12::boolean OR $13::boolean THEN EXCLUDED.item_count
|
||
ELSE GREATEST(i.item_count, EXCLUDED.item_count)
|
||
END,
|
||
-- 已截标/已定标/已取消是**终态事实**:迟到的补投(含 webhook 硬编码的 open)
|
||
-- 不得把它们改回 open —— 否则 canQuote 会误判为"还能报"
|
||
round_status = CASE
|
||
WHEN i.round_status IN ('closed', 'awarded', 'cancelled') THEN i.round_status
|
||
ELSE COALESCE(EXCLUDED.round_status, i.round_status)
|
||
END,
|
||
main_invitation_status = COALESCE(EXCLUDED.main_invitation_status, i.main_invitation_status),
|
||
webhook_received_at = CASE WHEN $11::boolean THEN NOW() ELSE i.webhook_received_at END,
|
||
last_synced_at = CASE WHEN $12::boolean THEN NOW() ELSE i.last_synced_at END,
|
||
-- 同步/刷新成功 ⇒ 清掉历史失败原因(失败原因不清就等于"没同步成功过"永远留着)
|
||
sync_error = CASE WHEN $12::boolean THEN NULL ELSE i.sync_error END,
|
||
payload = COALESCE(EXCLUDED.payload, i.payload),
|
||
updated_at = NOW()
|
||
RETURNING i.id`,
|
||
[
|
||
input.branchCode,
|
||
input.supplierCode,
|
||
input.roundId,
|
||
input.roundCode ?? null,
|
||
input.roundTitle ?? null,
|
||
input.orderCode ?? null,
|
||
input.respondDeadline ?? null,
|
||
input.itemCount ?? 0,
|
||
input.roundStatus ?? 'open',
|
||
input.mainInvitationStatus ?? null,
|
||
input.fromWebhook === true,
|
||
input.fromSync === true,
|
||
input.fromDetailItems === true,
|
||
input.payload === undefined || input.payload === null ? null : JSON.stringify(input.payload),
|
||
]
|
||
);
|
||
return String(rows[0]?.id || '');
|
||
}
|
||
|
||
async function upsertItemIdentity(
|
||
client: any,
|
||
input: {
|
||
invitationId: string;
|
||
branchCode: string;
|
||
roundId: string;
|
||
skuCode: string;
|
||
skuName?: string | null;
|
||
unit?: string | null;
|
||
}
|
||
): Promise<void> {
|
||
await client.query(
|
||
`INSERT INTO public.main_system_bid_invitation_items AS it
|
||
(invitation_id, branch_code, round_id, sku_code, sku_name, unit)
|
||
VALUES ($1, $2, $3, $4, $5, $6)
|
||
ON CONFLICT (invitation_id, sku_code) DO UPDATE SET
|
||
sku_name = COALESCE(EXCLUDED.sku_name, it.sku_name),
|
||
unit = COALESCE(EXCLUDED.unit, it.unit),
|
||
updated_at = NOW()`,
|
||
[input.invitationId, input.branchCode, input.roundId, input.skuCode, input.skuName ?? null, input.unit ?? null]
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 收 `bid.opened`:落邀约头 + 商品名(**不写价格**)。
|
||
*
|
||
* 幂等:同一 `(branch, round, supplier)` 重复推送只更新一行;商品行按 `(invitation_id, sku_code)` upsert。
|
||
* 退化载荷(`items: []`,对方读明细失败时只推轮次头)也照常落头 —— 页面点开时会再拉详情补齐。
|
||
*/
|
||
export async function recordBidOpened(input: {
|
||
branchCode: string;
|
||
supplierCode: string;
|
||
payload: BidOpenedPayload;
|
||
}): Promise<{
|
||
status: 'recorded' | 'ignored';
|
||
roundId?: string;
|
||
roundCode?: string | null;
|
||
itemCount?: number;
|
||
localStatus?: BidLocalStatus;
|
||
reason?: string;
|
||
}> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const declaredSupplier = String(input.supplierCode || '').trim();
|
||
const roundId = toText(input.payload?.round_id, 128);
|
||
if (!branchCode || !declaredSupplier) return { status: 'ignored', reason: 'missing_branch_or_supplier' };
|
||
if (!roundId) return { status: 'ignored', reason: 'missing_round_id' };
|
||
// 形态与查询/提交侧同一口径(`[0-9A-Za-z_-]{1,64}`):不合约的 round_id 落进来只会变成
|
||
// 一行"点不开、提交不了"的僵尸台账,因此入口就忽略(tester F3)。
|
||
if (!/^[0-9A-Za-z_-]{1,64}$/.test(roundId)) return { status: 'ignored', reason: 'invalid_round_id' };
|
||
|
||
/**
|
||
* **编码校验 + 规范化**(2026-10-17 红队 #10):
|
||
* 推送只认该分公司**生效绑定**里的 supplier_code(大小写不敏感匹配,存绑定里的写法)。
|
||
* 为什么:`bid_invitations` 是按 `(轮次 × supplier_code)` 的,若把 `sup123` 与 `SUP123` 当成两个键,
|
||
* 同一轮会裂成两行、页面出现重复待办;而完全不校验则任何签名齐全的载荷都能落一行陌生编码。
|
||
* ⚠️ 读不到绑定(空列表 = 未绑定/查询失败)时**不拦**:那是环境的已知状态,不是本事件的错。
|
||
*/
|
||
let supplierCode = declaredSupplier;
|
||
try {
|
||
const bound = await listSupplierCodesForBranch(branchCode);
|
||
if (bound.length) {
|
||
const canonical = bound.find(
|
||
(code) => String(code).trim().toUpperCase() === declaredSupplier.toUpperCase()
|
||
);
|
||
if (!canonical) {
|
||
return { status: 'ignored', reason: 'supplier_not_bound' };
|
||
}
|
||
supplierCode = String(canonical).trim();
|
||
}
|
||
} catch (error) {
|
||
console.warn('[bid] 校验 supplier_code 绑定失败(不阻断落库):', (error as Error)?.message || error);
|
||
}
|
||
|
||
const rawItems = Array.isArray(input.payload?.items) ? (input.payload?.items as any[]) : [];
|
||
const items: Array<{ skuCode: string; skuName: string | null; unit: string | null }> = [];
|
||
const seenSkus = new Set<string>();
|
||
for (const row of rawItems) {
|
||
const skuCode = toText(row?.sku_code, 120) || '';
|
||
if (!skuCode || seenSkus.has(skuCode)) continue; // 去重:同一 SKU 重复出现只算一行(红队 #7)
|
||
seenSkus.add(skuCode);
|
||
items.push({
|
||
skuCode,
|
||
skuName: toText(row?.sku_name, 255),
|
||
unit: toText(row?.unit, 32),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 数量口径(红队 #7):**只认去重后的实际明细行数**。
|
||
*
|
||
* 为什么不采信载荷里的 `item_count`:① 它可能含重复 SKU/对方已删的行,
|
||
* 会让"列表显示 3 件、点开只有 2 件";② 对方读明细失败时退化推送的 `items` 是空数组,
|
||
* 此时按声明值写就把一个不可信的数字记成了事实。退化推送一律按 0 写(`GREATEST` 保住旧值)。
|
||
*/
|
||
const itemCount = items.length;
|
||
|
||
return withTransaction(async (client) => {
|
||
const invitationId = await upsertInvitationHeader(client, {
|
||
branchCode,
|
||
supplierCode,
|
||
roundId,
|
||
roundCode: toText(input.payload?.round_code, 128),
|
||
// 载荷里没有标题(对方只给 round_code);标题留空,等拉详情补
|
||
orderCode: toText(input.payload?.order_code, 128),
|
||
respondDeadline: toIso(input.payload?.respond_deadline as any),
|
||
itemCount,
|
||
roundStatus: 'open',
|
||
fromWebhook: true,
|
||
fromDetailItems: items.length > 0,
|
||
payload: input.payload,
|
||
});
|
||
for (const item of items) {
|
||
await upsertItemIdentity(client, {
|
||
invitationId,
|
||
branchCode,
|
||
roundId,
|
||
skuCode: item.skuCode,
|
||
skuName: item.skuName,
|
||
unit: item.unit,
|
||
});
|
||
}
|
||
const localStatus = await recomputeLocalStatus(client, invitationId);
|
||
return {
|
||
status: 'recorded' as const,
|
||
roundId,
|
||
roundCode: toText(input.payload?.round_code, 128),
|
||
itemCount,
|
||
localStatus,
|
||
};
|
||
});
|
||
}
|
||
|
||
/** 拉列表兜底能提供的字段(对方 `bid_invitations` ⋈ `bid_rounds` 的行) */
|
||
export type BidListHeaderInput = {
|
||
roundId: string;
|
||
roundCode?: string | null;
|
||
roundTitle?: string | null;
|
||
orderCode?: string | null;
|
||
respondDeadline?: string | null;
|
||
itemCount?: number | null;
|
||
roundStatus?: string | null;
|
||
invitationStatus?: string | null;
|
||
};
|
||
|
||
/**
|
||
* 拉取兜底:只 upsert **邀约头**(对方列表接口不发明细)。
|
||
* 明细/报价/中标由 `applyBidDetail()` 在"打开某一轮"时整轮对齐。
|
||
*/
|
||
export async function upsertInvitationHeaders(input: {
|
||
branchCode: string;
|
||
supplierCode: string;
|
||
rows: BidListHeaderInput[];
|
||
payload?: unknown;
|
||
}): Promise<{ upserted: number }> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const supplierCode = String(input.supplierCode || '').trim();
|
||
if (!branchCode || !supplierCode) return { upserted: 0 };
|
||
const rows = (input.rows || []).filter((row) => String(row?.roundId || '').trim());
|
||
if (!rows.length) return { upserted: 0 };
|
||
|
||
return withTransaction(async (client) => {
|
||
let upserted = 0;
|
||
for (const row of rows) {
|
||
const invitationId = await upsertInvitationHeader(client, {
|
||
branchCode,
|
||
supplierCode,
|
||
roundId: String(row.roundId).trim(),
|
||
roundCode: row.roundCode ?? null,
|
||
roundTitle: row.roundTitle ?? null,
|
||
orderCode: row.orderCode ?? null,
|
||
respondDeadline: row.respondDeadline ?? null,
|
||
itemCount: row.itemCount ?? 0,
|
||
roundStatus: row.roundStatus ?? 'open',
|
||
mainInvitationStatus: row.invitationStatus ?? null,
|
||
fromSync: true,
|
||
});
|
||
if (invitationId) {
|
||
await recomputeLocalStatus(client, invitationId);
|
||
upserted += 1;
|
||
}
|
||
}
|
||
return { upserted };
|
||
});
|
||
}
|
||
|
||
/** 对方详情视图(`GET /api/supplier/bids/:id` 的 `data`)—— 本文件只做落库,不做 HTTP */
|
||
export type BidDetailInput = {
|
||
round: {
|
||
id?: unknown;
|
||
round_code?: unknown;
|
||
title?: unknown;
|
||
order_code?: unknown;
|
||
status?: unknown;
|
||
respond_deadline?: unknown;
|
||
} | null;
|
||
invitation: { status?: unknown; respond_deadline?: unknown; quoted_at?: unknown } | null;
|
||
items: Array<{ sku_code?: unknown; sku_name?: unknown; unit?: unknown }>;
|
||
myQuotes: Array<{ sku_code?: unknown; unit_price?: unknown; remark?: unknown; updated_at?: unknown; created_at?: unknown }>;
|
||
myAwards: Array<{ sku_code?: unknown; unit_price?: unknown }>;
|
||
};
|
||
|
||
/**
|
||
* **整轮对齐**(打开某一轮 / 提交成功后的返回都用它):
|
||
* 明细、我方报价、我方中标一律「先清空再按对方返回重写」——
|
||
* 否则对方撤回一条报价、或改判中标后,我方镜像会留着旧值(假事实)。
|
||
*/
|
||
export async function applyBidDetail(input: {
|
||
branchCode: string;
|
||
supplierCode: string;
|
||
roundId: string;
|
||
detail: BidDetailInput;
|
||
payload?: unknown;
|
||
}): Promise<{ invitationId: string; localStatus: BidLocalStatus }> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const supplierCode = String(input.supplierCode || '').trim();
|
||
const roundId = String(input.roundId || '').trim();
|
||
if (!branchCode || !supplierCode || !roundId) {
|
||
throw new Error('applyBidDetail 缺少 branchCode/supplierCode/roundId');
|
||
}
|
||
const round = input.detail?.round || {};
|
||
const invitation = input.detail?.invitation || {};
|
||
const items = (Array.isArray(input.detail?.items) ? input.detail.items : [])
|
||
.map((row) => ({
|
||
skuCode: toText(row?.sku_code, 120) || '',
|
||
skuName: toText(row?.sku_name, 255),
|
||
unit: toText(row?.unit, 32),
|
||
}))
|
||
.filter((row) => Boolean(row.skuCode));
|
||
const quotes = (Array.isArray(input.detail?.myQuotes) ? input.detail.myQuotes : [])
|
||
.map((row) => ({
|
||
skuCode: toText(row?.sku_code, 120) || '',
|
||
unitPrice: toNumber(row?.unit_price),
|
||
remark: toText(row?.remark),
|
||
quotedAt: toIso((row?.updated_at as any) || (row?.created_at as any)),
|
||
}))
|
||
.filter((row) => Boolean(row.skuCode) && row.unitPrice !== null);
|
||
const awards = (Array.isArray(input.detail?.myAwards) ? input.detail.myAwards : [])
|
||
.map((row) => ({
|
||
skuCode: toText(row?.sku_code, 120) || '',
|
||
unitPrice: toNumber(row?.unit_price),
|
||
}))
|
||
.filter((row) => Boolean(row.skuCode));
|
||
|
||
return withTransaction(async (client) => {
|
||
const invitationId = await upsertInvitationHeader(client, {
|
||
branchCode,
|
||
supplierCode,
|
||
roundId,
|
||
roundCode: toText(round.round_code, 128),
|
||
roundTitle: toText(round.title, 255),
|
||
orderCode: toText(round.order_code, 128),
|
||
respondDeadline: toIso((round.respond_deadline as any) || (invitation.respond_deadline as any)),
|
||
itemCount: items.length,
|
||
roundStatus: toText(round.status, 20) || 'open',
|
||
mainInvitationStatus: toText(invitation.status, 20),
|
||
fromSync: true,
|
||
fromDetailItems: true,
|
||
payload: input.payload ?? input.detail,
|
||
});
|
||
|
||
/**
|
||
* 对方视图里已不存在的商品行 ⇒ 删掉(避免页面出现"对方已经没有的行")。
|
||
* ⚠️ **即使 `items` 是空数组也要删**:能走到这里说明响应是**可识别**的
|
||
* (`isDegenerateDetail` 已在 api 层挡掉"既无轮次又无明细"的那种),
|
||
* 此时"0 行明细"本身就是事实;若跳过删除,头会写 0 行而明细还留着旧行/旧价,
|
||
* 页面又按明细行数展示 ⇒ 显示的是对方已经删掉的东西(tester F2)。
|
||
*/
|
||
await client.query(
|
||
`DELETE FROM public.main_system_bid_invitation_items
|
||
WHERE invitation_id = $1 AND NOT (sku_code = ANY($2::text[]))`,
|
||
[invitationId, items.map((row) => row.skuCode)]
|
||
);
|
||
|
||
for (const item of items) {
|
||
await upsertItemIdentity(client, {
|
||
invitationId,
|
||
branchCode,
|
||
roundId,
|
||
skuCode: item.skuCode,
|
||
skuName: item.skuName,
|
||
unit: item.unit,
|
||
});
|
||
}
|
||
|
||
// 报价与中标:先清空再写(对方撤回/改判要能体现)
|
||
await client.query(
|
||
`UPDATE public.main_system_bid_invitation_items
|
||
SET unit_price = NULL, remark = NULL, quoted_at = NULL, updated_at = NOW()
|
||
WHERE invitation_id = $1 AND unit_price IS NOT NULL`,
|
||
[invitationId]
|
||
);
|
||
for (const quote of quotes) {
|
||
await client.query(
|
||
`UPDATE public.main_system_bid_invitation_items AS it
|
||
SET unit_price = $3, remark = $4, quoted_at = COALESCE($5, it.quoted_at), updated_at = NOW()
|
||
WHERE it.invitation_id = $1 AND it.sku_code = $2`,
|
||
[invitationId, quote.skuCode, quote.unitPrice, quote.remark, quote.quotedAt]
|
||
);
|
||
}
|
||
|
||
await client.query(
|
||
`UPDATE public.main_system_bid_invitation_items
|
||
SET award_price = NULL, award_qty = NULL, award_status = NULL, updated_at = NOW()
|
||
WHERE invitation_id = $1 AND (award_price IS NOT NULL OR award_status IS NOT NULL)`,
|
||
[invitationId]
|
||
);
|
||
for (const award of awards) {
|
||
await client.query(
|
||
`UPDATE public.main_system_bid_invitation_items AS it
|
||
SET award_price = $3, award_status = 'won', updated_at = NOW()
|
||
WHERE it.invitation_id = $1 AND it.sku_code = $2`,
|
||
[invitationId, award.skuCode, award.unitPrice]
|
||
);
|
||
}
|
||
|
||
const localStatus = await recomputeLocalStatus(client, invitationId);
|
||
return { invitationId, localStatus };
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 按轮次定位台账行。
|
||
*
|
||
* ⚠️ 一个分公司可能绑**多个 supplier_code**,同一轮可能同时邀请两个编码 ⇒ `(branch, round)` 可能命中多行。
|
||
* 因此:
|
||
* · 调用方带了 `supplierCode` ⇒ 精确匹配该行(前端列表里每行都带它,正常路径都走这条);
|
||
* · 没带且只有一行 ⇒ 就用它(单绑定的常见情况);
|
||
* · 没带且多行 ⇒ 返回 `ambiguous`,由调用方提示"请从清单里点具体那条",**绝不猜**(猜错会以另一家身份报价)。
|
||
*/
|
||
export async function findInvitationByRound(input: {
|
||
branchCode: string;
|
||
roundId: string;
|
||
supplierCode?: string | null;
|
||
}): Promise<
|
||
| { kind: 'found'; row: BidInvitationRow }
|
||
| { kind: 'missing' }
|
||
| { kind: 'ambiguous'; supplierCodes: string[] }
|
||
> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const roundId = String(input.roundId || '').trim();
|
||
const supplierCode = String(input.supplierCode || '').trim();
|
||
if (!branchCode || !roundId) return { kind: 'missing' };
|
||
if (supplierCode) {
|
||
const { rows } = await pool.query<BidInvitationRow>(
|
||
`SELECT * FROM public.main_system_bid_invitations
|
||
WHERE branch_code = $1 AND round_id = $2 AND upper(supplier_code) = upper($3)
|
||
AND deleted_at IS NULL
|
||
LIMIT 1`,
|
||
[branchCode, roundId, supplierCode]
|
||
);
|
||
return rows[0] ? { kind: 'found', row: rows[0] } : { kind: 'missing' };
|
||
}
|
||
const { rows } = await pool.query<BidInvitationRow>(
|
||
`SELECT * FROM public.main_system_bid_invitations
|
||
WHERE branch_code = $1 AND round_id = $2
|
||
ORDER BY created_at DESC`,
|
||
[branchCode, roundId]
|
||
);
|
||
if (!rows.length) return { kind: 'missing' };
|
||
if (rows.length > 1) {
|
||
return { kind: 'ambiguous', supplierCodes: rows.map((row) => String(row.supplier_code || '')) };
|
||
}
|
||
return { kind: 'found', row: rows[0] };
|
||
}
|
||
|
||
export async function listInvitationRows(input: {
|
||
branchCode: string;
|
||
status?: 'all' | 'pending' | 'history' | null;
|
||
/** true = 连已软删的行一起返回(页面「显示已删除」开关) */
|
||
includeDeleted?: boolean;
|
||
limit?: number;
|
||
}): Promise<{ rows: BidInvitationRow[]; counts: Record<string, number> }> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
if (!branchCode) return { rows: [], counts: {} };
|
||
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
|
||
const status = input.status === 'pending' || input.status === 'history' ? input.status : null;
|
||
const deletedSql = input.includeDeleted ? '' : 'AND deleted_at IS NULL';
|
||
const statusSql =
|
||
status === 'pending'
|
||
? `AND local_status = 'pending'`
|
||
: status === 'history'
|
||
? `AND local_status IN ('quoted', 'expired', 'won', 'lost', 'cancelled')`
|
||
: '';
|
||
|
||
const [rows, counts] = await Promise.all([
|
||
pool.query<BidInvitationRow>(
|
||
`SELECT * FROM public.main_system_bid_invitations
|
||
WHERE branch_code = $1 ${deletedSql} ${statusSql}
|
||
ORDER BY (local_status = 'pending') DESC,
|
||
CASE WHEN local_status = 'pending' THEN respond_deadline END ASC NULLS LAST,
|
||
updated_at DESC
|
||
LIMIT $2`,
|
||
[branchCode, limit]
|
||
),
|
||
pool.query<{ local_status: string; n: number }>(
|
||
`SELECT local_status, COUNT(*)::int AS n
|
||
FROM public.main_system_bid_invitations
|
||
WHERE branch_code = $1 ${deletedSql}
|
||
GROUP BY local_status`,
|
||
[branchCode]
|
||
),
|
||
]);
|
||
|
||
const countsMap: Record<string, number> = {};
|
||
for (const row of counts.rows) countsMap[String(row.local_status)] = Number(row.n) || 0;
|
||
return { rows: rows.rows, counts: countsMap };
|
||
}
|
||
|
||
/**
|
||
* 软删除一条竞价邀约(本系统台账里隐藏)。
|
||
*
|
||
* 口径(`.team/bid-delete-status/decisions.md`):**不通知主系统、不硬删**;
|
||
* 只允许 `pending` / `expired`;上游再次推送时 `upsertInvitationHeader` 不写 `deleted_at` ⇒ 保持隐藏。
|
||
*/
|
||
export async function softDeleteBidInvitation(input: {
|
||
branchCode: string;
|
||
roundId: string;
|
||
supplierCode?: string | null;
|
||
userId?: string | null;
|
||
}): Promise<
|
||
{ ok: true; roundCode: string | null } | { ok: false; status: number; code: string; message: string }
|
||
> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const roundId = String(input.roundId || '').trim();
|
||
if (!branchCode || !roundId) {
|
||
return { ok: false, status: 400, code: 'branch_required', message: '缺少分公司或竞价轮次' };
|
||
}
|
||
const supplierCode = String(input.supplierCode || '').trim();
|
||
const scope = supplierCode ? 'AND upper(supplier_code) = upper($4)' : '';
|
||
const params: unknown[] = [branchCode, roundId, input.userId || null];
|
||
if (supplierCode) params.push(supplierCode);
|
||
const { rows } = await pool.query(
|
||
`UPDATE public.main_system_bid_invitations
|
||
SET deleted_at = NOW(), deleted_by = $3, updated_at = NOW()
|
||
WHERE branch_code = $1 AND round_id = $2 ${scope}
|
||
AND deleted_at IS NULL
|
||
AND local_status IN ('pending', 'expired')
|
||
RETURNING round_code`,
|
||
params
|
||
);
|
||
if (!rows.length) {
|
||
const exists = await pool.query<{ local_status: string; deleted_at: Date | null }>(
|
||
`SELECT local_status, deleted_at FROM public.main_system_bid_invitations
|
||
WHERE branch_code = $1 AND round_id = $2 ${scope}
|
||
LIMIT 1`,
|
||
params.slice(0, supplierCode ? 4 : 2)
|
||
);
|
||
if (!exists.rows.length) return { ok: false, status: 404, code: 'not_found', message: '竞价邀约不存在' };
|
||
if (exists.rows[0].deleted_at) {
|
||
return { ok: false, status: 409, code: 'already_deleted', message: '该邀约已删除' };
|
||
}
|
||
return {
|
||
ok: false,
|
||
status: 409,
|
||
code: 'not_deletable',
|
||
message: '只有「待报价 / 已截止」的邀约可以删除',
|
||
};
|
||
}
|
||
return { ok: true, roundCode: rows[0]?.round_code ?? null };
|
||
}
|
||
|
||
/** 恢复一条被软删的邀约(仅管理员;直接把 `deleted_at` 复位) */
|
||
export async function restoreBidInvitation(input: {
|
||
branchCode: string;
|
||
roundId: string;
|
||
supplierCode?: string | null;
|
||
}): Promise<{ ok: true; roundCode: string | null } | { ok: false; status: number; code: string; message: string }> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const roundId = String(input.roundId || '').trim();
|
||
if (!branchCode || !roundId) {
|
||
return { ok: false, status: 400, code: 'branch_required', message: '缺少分公司或竞价轮次' };
|
||
}
|
||
const supplierCode = String(input.supplierCode || '').trim();
|
||
const scope = supplierCode ? 'AND upper(supplier_code) = upper($3)' : '';
|
||
const params: unknown[] = [branchCode, roundId];
|
||
if (supplierCode) params.push(supplierCode);
|
||
const { rows } = await pool.query(
|
||
`UPDATE public.main_system_bid_invitations
|
||
SET deleted_at = NULL, deleted_by = NULL, updated_at = NOW()
|
||
WHERE branch_code = $1 AND round_id = $2 ${scope} AND deleted_at IS NOT NULL
|
||
RETURNING round_code`,
|
||
params
|
||
);
|
||
if (!rows.length) return { ok: false, status: 404, code: 'not_found', message: '没有可恢复的已删邀约' };
|
||
return { ok: true, roundCode: rows[0]?.round_code ?? null };
|
||
}
|
||
|
||
export async function listInvitationItems(invitationId: string): Promise<BidInvitationItemRow[]> {
|
||
const { rows } = await pool.query<BidInvitationItemRow>(
|
||
`SELECT * FROM public.main_system_bid_invitation_items
|
||
WHERE invitation_id = $1
|
||
ORDER BY sku_name NULLS LAST, sku_code`,
|
||
[invitationId]
|
||
);
|
||
return rows;
|
||
}
|
||
|
||
/** 详情 DTO(含 `canQuote` / `deadlinePassed`,页面只读判断全用它) */
|
||
export async function getBidInvitationDetail(input: {
|
||
branchCode: string;
|
||
roundId: string;
|
||
supplierCode?: string | null;
|
||
}): Promise<BidInvitationDetailDto | null> {
|
||
const found = await findInvitationByRound(input);
|
||
if (found.kind !== 'found') return null;
|
||
const row = found.row;
|
||
const itemRows = await listInvitationItems(row.id);
|
||
const itemCount = itemRows.length || Number(row.item_count) || 0;
|
||
const deadlineMs = row.respond_deadline ? new Date(row.respond_deadline).getTime() : NaN;
|
||
const deadlinePassed = Number.isFinite(deadlineMs) && deadlineMs < Date.now();
|
||
// 「轮次还在报价中」是对方的事实(`open`);`closed`/`awarded`/`cancelled` 一律不可提交。
|
||
// 另外派生状态已是终态(expired/won/lost/cancelled)也不可提交:对方说邀约过期时,
|
||
// 即便本地时钟还没到截止,也不该再发出一次注定被拒的请求。
|
||
const canQuote =
|
||
!deadlinePassed &&
|
||
row.round_status === 'open' &&
|
||
row.local_status !== 'expired' &&
|
||
row.local_status !== 'won' &&
|
||
row.local_status !== 'lost' &&
|
||
row.local_status !== 'cancelled';
|
||
const items = itemRows.map((item) => toBidInvitationItemDto(item, row.round_status));
|
||
return {
|
||
invitation: { ...toBidInvitationDto(row), itemCount },
|
||
items,
|
||
myAwards: items
|
||
.filter((item) => item.awardStatus === 'won')
|
||
.map((item) => ({ skuCode: item.skuCode, unitPrice: item.awardPrice })),
|
||
canQuote,
|
||
deadlinePassed,
|
||
syncError: row.sync_error ?? null,
|
||
};
|
||
}
|
||
|
||
/** 记一次同步/提交失败(页面标题上要能看到"为什么这轮没刷新成功") */
|
||
/** 按 `(branch, round[, supplier])` 更新;给了 supplier 就只动那一行(多绑定时不误伤) */
|
||
function invitationScopeSql(input: { supplierCode?: string | null }): { sql: string; params: unknown[] } {
|
||
const supplierCode = String(input.supplierCode || '').trim();
|
||
return supplierCode
|
||
? { sql: `AND upper(supplier_code) = upper($4)`, params: [supplierCode] }
|
||
: { sql: '', params: [] };
|
||
}
|
||
|
||
export async function markInvitationSyncError(input: {
|
||
branchCode: string;
|
||
roundId: string;
|
||
supplierCode?: string | null;
|
||
reason: string;
|
||
}): Promise<void> {
|
||
const reason = String(input.reason || '').slice(0, 500);
|
||
const scope = invitationScopeSql(input);
|
||
await pool.query(
|
||
`UPDATE public.main_system_bid_invitations
|
||
SET sync_error = $3, updated_at = NOW()
|
||
WHERE branch_code = $1 AND round_id = $2 ${scope.sql}`,
|
||
[String(input.branchCode || '').trim(), String(input.roundId || '').trim(), reason || null, ...scope.params]
|
||
);
|
||
}
|
||
|
||
/** 对方明确说这一轮不存在/无权查看 ⇒ 我方停用该行(不删,留痕) */
|
||
export async function markInvitationCancelled(input: {
|
||
branchCode: string;
|
||
roundId: string;
|
||
supplierCode?: string | null;
|
||
reason: string;
|
||
}): Promise<void> {
|
||
const scope = invitationScopeSql(input);
|
||
await pool.query(
|
||
`UPDATE public.main_system_bid_invitations
|
||
SET round_status = 'cancelled',
|
||
local_status = 'cancelled',
|
||
sync_error = $3,
|
||
updated_at = NOW()
|
||
WHERE branch_code = $1 AND round_id = $2 ${scope.sql}`,
|
||
[
|
||
String(input.branchCode || '').trim(),
|
||
String(input.roundId || '').trim(),
|
||
String(input.reason || '').slice(0, 500) || null,
|
||
...scope.params,
|
||
]
|
||
);
|
||
}
|