From fe10859f4d7082f3949659779f93b8e9ec40671d Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Sat, 17 Oct 2026 12:39:39 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E7=AB=9E=E4=BB=B7=E6=8A=A5=E4=BB=B7):=20?= =?UTF-8?q?=E6=8E=A5=E4=B8=BB=E7=B3=BB=E7=BB=9F=E3=80=8C=E5=BE=85=E6=8A=A5?= =?UTF-8?q?=E4=BB=B7=E3=80=8D=E6=8E=A8=E9=80=81=E5=B9=B6=E5=9B=9E=E4=BC=A0?= =?UTF-8?q?=E5=8D=95=E4=BB=B7=EF=BC=88=E6=88=91=E6=96=B9=E5=8F=AA=E6=8A=A5?= =?UTF-8?q?=E4=BB=B7=E3=80=81=E4=B8=8D=E5=AE=9A=E6=A0=87=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 开发者 2026-10-17 裁决:我方不做本地竞价管理(菜单已摘除),只做两件事 —— 收到主系统 bid.opened 后显示本轮要报什么、把单价报回去;中标后沿用既有「分配 → 建单」。 主系统契约(对方 docs/design/20261017-bid-opened-push.md): · `bid.opened` 推送(单对象、无 data[]、同一套 X-Signature) · `GET /api/supplier/bids`:列表兜底(对方 webhook 只重试 2 次) · `GET /api/supplier/bids/:round_id`:单轮详情(明细 + 我的报价 + 我的中标) · `POST /api/supplier/bids/:round_id/quotes`:提交报价(批量 upsert,只有我的视角) 我方实现: · 迁移 20261055:public.main_system_bid_invitations / _invitation_items, 幂等键 (branch_code, round_id, supplier_code)、明细 (invitation_id, sku_code) · webhook 新增 bid.opened 分支(就地 return,绝不落进 preparations.allocated 建单兜底); 验签逻辑一字未改;落库前按该分公司生效绑定校验并规范化 supplier_code · 主系统调用走既有分层:services/mainSystem/{config,endpoints,http,token}.ts + api/bids.ts; 401 强制刷新 token 只重试一次;403 判语义拒绝不重试 · 业务层:mainSystemBidInbox(整轮对齐/唯一派生口径 deriveLocalStatus)、 mainSystemBidQuotes(列表/同步/刷新/提交 + 错误码中文映射) · 页面侧 4 个 REST:GET 清单 / POST sync / GET :roundId / POST :roundId/quotes (挂 workflow 模块,权限沿用 order_manage|order_edit|order_entry) · Web「待报价」页 + 菜单(orders-bid-invitations)+ 三语文案;复用既有 bids 命名空间 口径与边界(设计文 docs/design/20261017-主系统竞价待报价与报价提交.md): · 事实源在主系统,我方两张表是镜像:刷新/提交成功一律「整轮先清空再写」 · 失败绝不改本地报价(不能让用户以为报上了);只写 sync_error 留痕 · 退化响应守卫:对方 2xx 但载荷不可识别 ⇒ 失败且不落库(否则会清空我方已报价与中标) · 终态不可回退:closed / awarded / cancelled 收到迟到 bid.opened 不得改回 open · item_count 只认去重后的实际明细行数(避免"列表 3 件、点开 2 件") · 多绑定同一轮:页面每行带 supplierCode 精确定位;不带且命中多行 ⇒ 409 不猜 · 单价:只收 number 或纯数字字符串,>0、≤4 位小数、≤99999999.9999 验证(真实输出见交付说明): · server/tests/mainSystemBidQuote.test.ts 28 用例、mainSystemBidQuoteBoundary.test.ts 91 用例、 mainSystemBidQuoteDb.integration.test.ts 真库 11 用例(BID_DB_TEST=1 才跑)全过 · Web:BidInvitationsPage.render 7 用例 + 菜单契约/menuLayout 共 86 用例全过; npm run typecheck 0 错;cd server && npx tsc --noEmit 0 错 (注意:根 tsconfig include 只有 src,后端必须单独 typecheck) · 全量后端套件与基线 14d7afe 逐文件比对:失败集合完全一致(30 文件 / 38 用例,均既有失败) · 本地真环境:伪造签名 401;真实签名连推两次只落 1 行 + 去重后 2 条明细; 未绑定编码 ⇒ ignored 不落库;详情对不存在轮次 404 且台账自动 cancelled · 独立复核(verifier)B1–B9/B11/B13 全 pass;红队(adversary)未发现误建单/跨租户/资金精度类高危, 两条中危(多绑定错供应商、2xx 畸形响应清空本地)已修并被用例钉住 · 设计门禁:8 通过 / 1 已知红 check-ai-cost / verify-facts 因本地缺 tenant_br003 红(均基线) --- .../20261017-主系统竞价待报价与报价提交.md | 309 +++ docs/design/README.md | 2 + .../20261055_main_system_bid_invitations.sql | 99 + server/src/modules/businessModules.ts | 4 + .../workflow/routes/mainSystemBidRoutes.ts | 149 ++ server/src/routes/mainSystemIntegration.ts | 27 + server/src/services/mainSystem/api/bids.ts | 355 ++++ server/src/services/mainSystem/config.ts | 8 + server/src/services/mainSystem/endpoints.ts | 14 + server/src/services/mainSystemBidInbox.ts | 857 ++++++++ server/src/services/mainSystemBidQuotes.ts | 496 +++++ server/tests/mainSystemBidQuote.test.ts | 504 +++++ .../tests/mainSystemBidQuoteBoundary.test.ts | 1863 +++++++++++++++++ .../mainSystemBidQuoteDb.integration.test.ts | 414 ++++ .../menuCatalog.bidRetired.contract.test.ts | 23 + src/config/menuCatalog.ts | 9 + src/i18n/locales/en/bids.ts | 25 + src/i18n/locales/en/menu.ts | 1 + src/i18n/locales/id/bids.ts | 25 + src/i18n/locales/id/menu.ts | 1 + src/i18n/locales/zh-CN/bids.ts | 25 + src/i18n/locales/zh-CN/menu.ts | 1 + src/modules/businessModules.ts | 7 +- src/modules/routes.tsx | 4 + .../orders/BidInvitationsPage.render.test.tsx | 351 ++++ src/pages/orders/BidInvitationsPage.tsx | 543 +++++ src/utils/menuLayout.newMenu.test.ts | 1 + src/utils/menuLayout.ts | 5 +- src/utils/workflowApi.ts | 120 ++ 29 files changed, 6240 insertions(+), 2 deletions(-) create mode 100644 docs/design/20261017-主系统竞价待报价与报价提交.md create mode 100644 migrations/20261055_main_system_bid_invitations.sql create mode 100644 server/src/modules/workflow/routes/mainSystemBidRoutes.ts create mode 100644 server/src/services/mainSystem/api/bids.ts create mode 100644 server/src/services/mainSystemBidInbox.ts create mode 100644 server/src/services/mainSystemBidQuotes.ts create mode 100644 server/tests/mainSystemBidQuote.test.ts create mode 100644 server/tests/mainSystemBidQuoteBoundary.test.ts create mode 100644 server/tests/mainSystemBidQuoteDb.integration.test.ts create mode 100644 src/pages/orders/BidInvitationsPage.render.test.tsx create mode 100644 src/pages/orders/BidInvitationsPage.tsx diff --git a/docs/design/20261017-主系统竞价待报价与报价提交.md b/docs/design/20261017-主系统竞价待报价与报价提交.md new file mode 100644 index 0000000..5d439ad --- /dev/null +++ b/docs/design/20261017-主系统竞价待报价与报价提交.md @@ -0,0 +1,309 @@ +# 主系统竞价「待报价」接收与报价提交(我方只报价、不定标) + +- 日期:2026-10-17 +- 触发:开发者裁决「我方**不做**本地竞价管理;只接收主系统的**待报价清单**、把**单价**报回去; + 中标后沿用既有『分配 → 建单』链路」;主系统已交付 `bid.opened` 推送与三个供应商接口。 +- 主系统侧实现(对方仓库):`docs/design/20261017-bid-opened-push.md`、 + `server/src/services/supplierPrepWebhookService.ts#notifySupplierBidOpened`、 + `server/src/routes/supplier/supplierBusinessRoutes.ts`(`/bids`、`/bids/:id`、`/bids/:id/quotes`)。 +- 交接文:`handoff/20261017-致主系统-竞价报价对接需求.md`。 +- 相关我方文档:`20261027-分公司接入编码与主系统供应商绑定.md`(入站路由 / 出站 `supplier_code`)、 + `20261011-跨系统改价改量审核.md`(主系统调用分层:`services/mainSystem/{endpoints,http,token}.ts` + `api/*.ts`)。 + +## 1. 结论(口径固定,后续不得改回) + +| 项 | 决定 | +| --- | --- | +| 本地竞价管理(轮次/定标/评分/比价) | **不做**。菜单已摘除(`menuCatalog.bidRetired.contract.test.ts`),页面代码保留但不再接新链路 | +| 我方做什么 | ① 收 `bid.opened` 推送 → 本地**待报价台账**(镜像,读得到就显示)② 报价单里**逐行填单价**回传 ③ 只读展示中标结果 | +| 我方不做什么 | 不定标、不评分、不比价、不写主系统其它数据、不推送订单 | +| 中标之后 | 主系统照既有「分配」流程推 `preparations.allocated`,我方按现有导入建单链路走(**零改动**) | +| 报价口径 | **一次性采购单价**(元),不含运费/税,**不等于结算价**;无数量/可报量;`> 0` 且最多 4 位小数 | +| 数据所有权 | 竞价/邀约/报价/中标的**唯一事实源在主系统**;我方两张表是**镜像 + 我方操作留痕**,随时可被对方返回覆盖 | +| 多份绑定 | 一个分公司可能绑多个 `supplier_code` ⇒ 待报价按**邀约行**(`branch_code + supplier_code + round_id`)区分,出站优先用该邀约自己的 `supplier_code` | + +## 2. 主系统契约(已实现,照抄不复述理由) + +### 2.1 推送事件 `bid.opened` + +- 通道:既有 `POST /api/integration/main-system/webhook`,`X-Signature: sha256=HMAC-SHA256(webhook_secret, rawBody)` + (**验签逻辑一字不改**,复用 `verifyWebhookSignature`)。 +- 信封(`deliverSingleObjectEvent` 产出):`event`、`request_id`、`occurred_at`、`branch_code`、 + `supplier_code`、`subsystem_code`(有绑定时)。 +- 业务体(**不含 `data[]`**): + +```json +{ + "event": "bid.opened", + "request_id": "", + "occurred_at": "2026-10-17T02:00:00.000Z", + "branch_code": "BR002", + "supplier_code": "SUP37831443", + "subsystem_code": "SC7K3Q9M2XTP", + "order_code": "ORD_WEB_20261017_BR002_0001", + "round_id": "", + "round_code": "BID20261017BR00201", + "respond_deadline": "2026-10-17T02:30:00.000Z", + "item_count": 2, + "items": [{ "sku_code": "SKU78661366595", "sku_name": "草鱼", "unit": "斤" }] +} +``` + +- 幂等键:**`(round_id, supplier_code)`**(同一轮补邀会再推,但只推新增邀约)。 +- 对方**只重试 2 次**,投递失败只记它的日志 ⇒ 我方必须有**拉取兜底**(§2.2 的列表接口)。 + +### 2.2 我方调用的三个接口(对方供应商开放 API,`Authorization: Bearer <集成 token>`) + +| # | 方法与路径 | 用途 | 关键返回 | +| --- | --- | --- | --- | +| ① | `GET /api/supplier/bids` | 列表兜底(webhook 漏推时补台账) | `{ data: [邀约行...], settings }`;`settings.enabled=false` ⇒ `data` 恒空 | +| ② | `GET /api/supplier/bids/:round_id` | 打开某一轮:明细 + 我的报价 + 我的中标 | `{ data: { round, items, invitation, my_quotes, awards } }` | +| ③ | `POST /api/supplier/bids/:round_id/quotes` | 提交报价(**批量 upsert**) | 成功返回 `{ data: <同 ②> }`(**只含我的视角**,无别家报价/中标) | + +- ③ 请求体:`{ quotes: [{ sku_code, unit_price, remark? }] }`;**重复提交幂等**(最后写入为准)。 +- 身份:`supplier_code` **只从 token 取**(请求体不带),我方出站按邀约行的 `supplier_code` 换 token。 + +### 2.3 对方错误码 → 我方界面文案 + +| 对方 `error` | 含义 | 我方提示(中文) | 我方动作 | +| --- | --- | --- | --- | +| `bid_not_open` | 轮次已不在报价中 | 本轮已结束报价,无法提交 | 重新拉详情、置只读 | +| `quote_deadline_passed` | 已过报价截止 | 已超过报价截止时间,本轮已出局 | 同上 | +| `supplier_category_mismatch` | 商品不在我方经营品类 | 该商品不在你的经营品类内,无法报价 | 该行标红、其余行可继续 | +| `bid_disabled` | 对方竞价开关关闭 | 对方未开启竞价功能 | 整页提示 + 置只读 | +| `not_found` / 404 | 轮次不存在 | 竞价单不存在或已被取消 | 从台账移除(软删 `cancelled`) | +| `forbidden` / 403 | 未受邀 / 编码未绑定 | 无权查看本轮竞价 | 台账标 `cancelled` | +| 401 | token 失效 | (不提示用户) | **强制刷新 token 重试一次**,再失败才报错 | +| 5xx / 网络 / 超时 | 对方不可用 | 对方系统暂不可用,请稍后重试 | 不改本地报价(避免"以为报上了") | + +### 2.4 契约没写、但我方必须自己挡的四件事(2026-10-17 复核/红队后补) + +| # | 情况 | 我方处理 | +| --- | --- | --- | +| 1 | 对方 **2xx 但载荷不可识别**(`{}` / 网关 HTML / 字段改名) | 判**失败**(`invalid_main_system_response`,502)且**不落库** —— 否则 `applyBidDetail` 的"先清空再写"会抹掉我方已报价与中标,变成"以为报上了" | +| 2 | 一个分公司绑**多个 supplier_code**,同一轮可能两条邀约 | 页面每行都带 `supplierCode`,单轮接口用 `?supplier=`(提交用 body 的 `supplierCode`)**精确定位**;没带且命中多行 ⇒ 409 `bid_invitation_ambiguous`,**绝不猜**(猜错会以另一家身份报价) | +| 3 | `supplier_code` 大小写/陌生编码 | webhook 落库前按该分公司**生效绑定**做大小写不敏感匹配并规范成绑定写法;不在绑定里 ⇒ `ignored: supplier_not_bound`(读不到绑定时不拦,只记日志) | +| 4 | 单价畸形 | 只接受 `number` 或**纯数字字符串**(`Number(true)=1`、`Number([1.5])=1.5` 会被"洗白");小数位用**字符串**判定;上限 `99999999.9999`(对方 `numeric(12,4)`) | + +另外三条口径: + +- **终态不可回退**:`closed` / `awarded` / `cancelled` 收到迟到的 `bid.opened`(载荷里本来就是 open)不得改回 `open` —— 否则 `canQuote` 会误判成"还能报"; +- **`item_count` 语义**:**只认去重后的实际明细行数**。webhook 带明细时按行数覆盖、退化推送(`items: []`)按 0 写(`GREATEST` 保住旧值、不采信不可信的声明值);拉详情按对方返回覆盖(对方删行后本地不能还留着大数字)——否则会出现"列表显示 3 件、点开只有 2 件"; +- **轮次 ID 形态校验**:入站(webhook 落库前)与出站(刷新/提交)**同一口径** `[0-9A-Za-z_-]{1,64}` —— + 出站非法 ⇒ 400 `invalid_round_id`;入站非法 ⇒ 直接 `ignored: invalid_round_id`(否则会落一行"点不开、提交不了"的僵尸台账); +- **"0 行明细"是事实**:能通过退化载荷守卫(有轮次 id)却返回 0 行 ⇒ 说明对方把这些行删了, + 整轮对齐要**把本地旧行一并删掉**,不能出现"头写 0 行、明细还留着旧行旧价"。 + +> **权限口径的已知边界**:`super_admin` 没有 `order_manage/order_edit/order_entry` ⇒ 这四个接口对它 403 +> (与既有「供需变更审核」页一致,不是本次引入的越权/漏权)。真要跨分公司排障,用该分公司的管理员账号。 + +## 3. 我方架构 + +``` +主系统 --bid.opened--> POST /api/integration/main-system/webhook + └─ isBidOpenedEvent → recordBidOpened() → public.main_system_bid_invitations + public.main_system_bid_invitation_items +Web「待报价」页面 --→ GET /api/workflow/main-system/bid-invitations (读本地镜像) + --→ POST /api/workflow/main-system/bid-invitations/sync (拉 ① 补台账) + --→ GET /api/workflow/main-system/bid-invitations/:roundId (拉 ② 刷新单轮) + --→ POST /api/workflow/main-system/bid-invitations/:roundId/quotes (调 ③ 回传) +``` + +> 为什么页面侧接口挂在 **workflow 模块**(`/api/workflow/main-system/bid-invitations`)而不是 +> `/api/integration/...`:与「供需变更审核」等**页面驱动**的台账接口同一层(同一套 +> `getWorkflowCtx` / `requireWorkflowPermission` / `getEffectiveBranchCode`),前端也复用同一个 +> `workflowFetch`。`/api/integration/...` 只留**机器对机器**的 webhook。 + +分层纪律(照 `20261011` §7): + +- 端点表:`server/src/services/mainSystem/endpoints.ts` 增 `bids`(`/api/supplier/bids`), + 子路径由 `mainSystemBidPath()` 拼;域名/超时/token 一律走既有 `config.ts` / `http.ts` / `token.ts`; +- API 封装:`server/src/services/mainSystem/api/bids.ts`(只有类型、字段映射、结果枚举,无 URL/fetch); +- 业务:`server/src/services/mainSystemBidInbox.ts`(webhook 落台账)、 + `server/src/services/mainSystemBidQuotes.ts`(刷新/同步/提交 + 错误码映射); +- 路由:① webhook 分支追加进 `server/src/routes/mainSystemIntegration.ts`(机器对机器面); + ② 页面侧 4 个 REST 放新文件 `server/src/modules/workflow/routes/mainSystemBidRoutes.ts`, + 在 `businessModules.ts` 的 `order` 模块里 `mountMainSystemBidWorkflowRoutes(router)` 挂载。 + +## 4. 数据模型(迁移 `20261055_main_system_bid_invitations.sql`) + +放在 **`public`**(与 `main_system_actual_qty_requests` / `main_supplier_bindings` 同域:都是"跨系统台账"), +带 `branch_code`,**不进租户 schema**(跨分公司统一排障、且这些表本来就不是租户业务数据)。 + +```sql +public.main_system_bid_invitations ( + id uuid PK, + branch_code varchar(64) NOT NULL, + supplier_code varchar(64) NOT NULL, + round_id varchar(128) NOT NULL, -- 主系统竞价轮次 UUID + round_code varchar(128), + round_title varchar(255), + order_code varchar(128), + respond_deadline timestamptz, -- 对方 ISO-8601,落 timestamptz + item_count int NOT NULL DEFAULT 0, + round_status varchar(20) NOT NULL DEFAULT 'open', -- 对方**轮次**事实:draft|open|closed|awarded|cancelled + main_invitation_status varchar(20), -- 对方**邀约**状态:pending|quoted|expired(拉过才有,NULL=未拉) + local_status varchar(20) NOT NULL DEFAULT 'pending',-- 我方视图:pending|quoted|expired|won|lost|cancelled + quoted_at timestamptz, + webhook_received_at timestamptz, + last_synced_at timestamptz, + sync_error text, -- 最近一次刷新/提交失败原因;同步成功即清空 + payload jsonb, -- 最近一次入站/拉取的原文(排障) + created_at timestamptz NOT NULL DEFAULT NOW(), + updated_at timestamptz NOT NULL DEFAULT NOW(), + UNIQUE (branch_code, round_id, supplier_code) -- ← 契约幂等键 +) + +public.main_system_bid_invitation_items ( + id uuid PK, + invitation_id uuid NOT NULL REFERENCES public.main_system_bid_invitations(id) ON DELETE CASCADE, + branch_code varchar(64) NOT NULL, + round_id varchar(128) NOT NULL, + sku_code varchar(120) NOT NULL, + sku_name varchar(255), + unit varchar(32), + unit_price numeric(14,4), -- 我方报的单价(对方 my_quotes 覆盖) + remark text, + quoted_at timestamptz, + award_price numeric(14,4), -- 对方 awards(只读) + award_qty numeric(14,3), -- 对方 bid_awards **无数量列** ⇒ 恒 NULL(留列备对方将来加量) + award_status varchar(20), -- 只写 'won';'lost' 由轮次 awarded + 无中标价在读取时派生 + created_at/updated_at, + UNIQUE (invitation_id, sku_code) +) +``` + +`local_status` 派生规则(**只此一份**,写在 `mainSystemBidInbox.ts` 导出函数里,前后端都用它): + +1. `round_status = 'cancelled'` ⇒ `cancelled`; +2. `round_status = 'awarded'` ⇒ 有我方中标行 `won`,否则 `lost`; +3. 否则 `respond_deadline < now()`(**服务器时钟**)⇒ `expired`; +4. 否则所有行都有 `unit_price` ⇒ `quoted`;否则 `pending`。 + +## 5. 后端接口(都要求登录 + 分公司上下文) + +鉴权与既有页面一致:`authMiddleware`;分公司用 `loadTenantContext(req.userId)?.branchCode` +(未绑定分公司 ⇒ 400 `branch_required`,与 `/main-system/preparations` 同口径)。 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| GET | `/api/workflow/main-system/bid-invitations` | 本地镜像列表。query:`status=all|pending|history`(默认 `all`)、`limit`(默认 50,上限 200)。返回 `{ data: [...], summary: { pending, quoted, expired, closed, won, lost, cancelled } }` | +| POST | `/api/workflow/main-system/bid-invitations/sync` | 对每个生效绑定 `supplier_code` 调 ①,upsert 邀约头(**不建明细**,明细等打开时拉 ②)。返回 `{ synced, skipped, unavailable }` | +| GET | `/api/workflow/main-system/bid-invitations/:roundId` | 调 ② 刷新单轮:upsert 邀约头 + 明细 + 我的报价 + 我的中标;返回 `{ data: { invitation, items, canQuote, myAwards } }` | +| POST | `/api/workflow/main-system/bid-invitations/:roundId/quotes` | body **`{ quotes: [{ skuCode, unitPrice, remark? }] }`**(我方接口 camelCase;转成对方 snake_case 只发生在 `api/bids.ts` 一处):先本地校验(非空/`>0`/≤4 位小数/未过截止),再调 ③;成功即用返回的 ② 视图 upsert 落库并回同 GET 的 DTO;失败一律 `{ error, error_description, error_kind }`,**HTTP 状态码照对方**:400/403/404 原样,5xx/网络 ⇒ 502 `main_system_unavailable`,对接未配置 ⇒ 503 `main_system_not_configured` | + +校验细则(提交前): + +- `quotes` 为空 ⇒ 400 `quotes_required`;单条 `sku_code` 不在该轮明细 ⇒ 400 `sku_not_in_round`; +- `unit_price` 非数字 / `<= 0` / 小数位 > 4 ⇒ 400 `invalid_unit_price`; +- 已过截止(**本地时钟**)⇒ 409 `quote_deadline_passed`(**不打扰对方**,但对方仍是最终裁决者); +- 台账 `round_status` 非 `open` ⇒ 409 `bid_not_open`。 + +**不做**的:不排队重试、不本地暂存未提交价格(提交失败即回滚界面状态为"未报")、 +不缓存对方 token 之外的任何东西(token 用既有 `getMainSystemToken` 缓存;401 强制刷新一次)。 + +## 6. 前端 + +### 6.1 页面与入口 + +- 新页面 `src/pages/orders/BidInvitationsPage.tsx`(**只做待报价清单 + 填价**,不做竞价设置/历史分析)。 +- 路由:`/orders/bid-invitations`(`src/modules/routes.tsx` + `src/modules/businessModules.ts` 的 + `order` 模块 `routes`,权限沿用 `['order_manage','order_edit']`,与「供需变更审核」同口径)。 +- 菜单:`src/config/menuCatalog.ts` 加 `orders-bid-invitations`(`secondary: true`, + `permission: ['order_manage','order_edit']`、`accessMatch: 'any'`), + `order` 模块 `menuKeys` 追加;三语 `locales/*/menu.ts` 加同名 label。 +- 页面本身用 `bids` 命名空间(`src/i18n/locales/*/bids.ts` 已存在,追加 `invite.*` 键;**不新建命名空间**)。 + +### 6.2 交互 + +1. 进页:读本地清单(`GET .../bid-invitations`)⇒ 表格:竞价单号 / 标题 / 商品数 / 报价截止 / 状态 / 操作(`报价` / `查看`)。 +2. 顶部:**同步**按钮(`POST .../sync`,补 webhook 漏推)+ **刷新**(重读清单)。 +3. 点「报价」打开弹窗:标题=竞价单号 + 截止倒计时; + 表:商品 / 单位 / 我方报价(数字输入,4 位小数)/ 备注(可选);已中标/已截止 ⇒ 只读 + 中标价列。 + 底部:`保存报价`(提交全部已填行)+ `关闭`。 +4. 提交成功:弹窗内回填对方返回的最新视图(报价时间、状态)+ toast「报价已提交」;清单行状态变「已报价」。 +5. 提交失败:按 §2.3 文案 toast;`supplier_category_mismatch` 只标该行、其它行保留。 +6. 已截止/已定标:整页只读,按钮变禁用并给一句原因(不隐藏,避免"凭空消失")。 + +### 6.3 三语文案(开发前需开发者确认;下为推荐值) + +| key | zh-CN | en | id | +| --- | --- | --- | --- | +| menu label | 待报价 | Bid requests | Permintaan penawaran | +| 页面标题 | 待报价(主系统竞价) | Bid requests (main system) | Permintaan penawaran (sistem utama) | +| 竞价单号 | 竞价单号 | Round no. | No. ronde | +| 标题 | 竞价标题 | Title | Judul | +| 商品数 | 商品数 | Items | Jumlah item | +| 报价截止 | 报价截止 | Deadline | Batas waktu | +| 状态·待报价 | 待报价 | To quote | Belum ditawar | +| 状态·已报价 | 已报价 | Quoted | Sudah ditawar | +| 状态·已截止 | 已截止 | Closed | Ditutup | +| 状态·已中标 | 已中标 | Won | Menang | +| 状态·未中标 | 未中标 | Not won | Tidak menang | +| 状态·已取消 | 已取消 | Cancelled | Dibatalkan | +| 操作·报价 | 报价 | Quote | Tawar | +| 操作·查看 | 查看 | View | Lihat | +| 商品 | 商品 | Item | Barang | +| 单位 | 单位 | Unit | Satuan | +| 我方报价 | 我方报价 | My price | Harga saya | +| 中标价 | 中标价 | Award price | Harga menang | +| 备注 | 备注 | Remark | Catatan | +| 保存报价 | 保存报价 | Save quotes | Simpan penawaran | +| 同步 | 同步 | Sync | Sinkron | +| 刷新 | 刷新 | Refresh | Segarkan | +| 提交成功 | 报价已提交 | Quotes submitted | Penawaran terkirim | +| 截止提示 | 已超过报价截止时间 | Past the quote deadline | Melewati batas waktu | +| 空态 | 暂无待报价的竞价单 | No bid requests | Belum ada permintaan penawaran | + +## 7. 权限与开关 + +- **权限**:复用 `['order_manage','order_edit','order_entry']`(与「供需变更审核」页同口径),**不新增权限码**; + 后端接口用 workflow 模块既有 `requireWorkflowPermission` 校验(任一即放行)。 +- **开关**:**不新增环境变量**(页面无 AI 调用、无成本风险;对方已有自己的竞价总开关)。 + 唯一前提是 `isMainSystemIntegrationEnabled()`(域名 + 凭据齐备)与「分公司已绑接入编码」; + 对方竞价关闭时以对方返回的 `bid_disabled` 表现为准,我方不猜。 + +## 8. 验收清单 + +| # | 验收项 | 验证方式 | +| --- | --- | --- | +| B1 | `bid.opened` 走既有验签;载荷无 `data[]` 时**不进建单兜底** | 单测:事件分支命中后未调 `importMainSystemGroups` | +| B2 | 幂等:同一 `(round_id, supplier_code)` 重复推送只一条邀约、明细按 `sku_code` upsert | 单测 + SQL 唯一键 | +| B3 | 未绑定/编码不认识的推送 ⇒ 200 ignored,不落任何行 | 单测 | +| B4 | 列表接口返回本地镜像,`status` 过滤与 `summary` 正确 | 单测 | +| B5 | 同步:调 ① 只 upsert 邀约头;`settings.enabled=false` ⇒ `data:[]` ⇒ 不改本地状态 | 单测 | +| B6 | 单轮刷新:upsert 明细/我的报价/中标;`awards` 无该行 ⇒ `lost`(仅 `round_status=awarded`) | 单测 | +| B7 | 提交:本地校验(空/≤0/5 位小数/超明细/过期)各自错误码 | 单测 | +| B8 | 提交转发正确(`quotes` 原样、token 取自该邀约 `supplier_code`);401 刷新重试一次 | 单测(`fetchImpl` 注入) | +| B9 | 对方错误码映射到 §2.3;5xx/网络 ⇒ 502 且**不改本地报价** | 单测 | +| B10 | 页面:清单渲染 / 打开弹窗填价 / 提交成功后状态变「已报价」/ 过期只读 | `npm run test:unit`(render 测试) | +| B11 | 菜单含 `orders-bid-invitations`,且「竞价管理」仍不在菜单(不回归 `bidRetired`) | 既有契约测试 | +| B12 | `npm run typecheck` 零错误;`npm --prefix server test` 无新增失败 | 真实命令输出 | +| B13 | 隔离表未被改回主系统取值(`supplier_delivery` / 3021 / 3022 / `supplier-system/`) | `git diff` 检查 | +| B14 | 退化载荷守卫:对方 2xx 但 `{}`/非 JSON ⇒ 失败且**不落库**(不清空本地报价) | 单测(`invalid_main_system_response`) | +| B15 | 多绑定同轮:带 `supplier` 精确命中;不带且多行 ⇒ 409 `bid_invitation_ambiguous`(不猜) | 单测 + 本地库两行样本 | + +## 9. 风险与边界 + +- **镜像会旧**:webhook 漏 + 未同步 ⇒ 台账停在 `pending`;打开弹窗与「同步」都会以对方为准刷新, + 且提交被对方拒绝时按错误码提示,不会让用户"以为报上了"。 +- **时钟**:截止判定用**我方服务器时钟**做 UX 层拦截(同一台机器与主系统同机部署,偏差可忽略); + 最终裁决在对方,我方拦截只用于少一次无效请求。 +- **并发**:同一账号两人同时填价 ⇒ 以最后一次提交为准(对方 upsert 语义),我方不引入锁。 +- **多绑定**:列表按邀约行展示;同一轮若两个 `supplier_code` 都受邀,会出现两行(各自报价互不影响)—— + 这是对的,不是重复。 +- **不做**:不做部分报价的可报量、不做运费/税拆分、不做中标后的二次确认(分配单到达即建单)。 +- **测试环境**:本地 `MAIN_SYSTEM_BASE_URL=http://127.0.0.1:3001`(主系统 dev), + 联调用 `supplier_code=SUP37831443`(= 本地 `BR002` 的生效绑定)。 + +## 10. 验证(2026-10-17 回填真实结果) + +- [x] B1–B9 / B14 / B15 单测:`server/tests/mainSystemBidQuote.test.ts`(28 用例)—— 独立复核(verifier)逐条 pass; +- [x] B10 前端 render 测试:`src/pages/orders/BidInvitationsPage.render.test.tsx`(7 用例)pass; +- [x] B11 契约测试:`menuCatalog.bidRetired.contract.test.ts`(9)+ `menuLayout.newMenu.test.ts`(10)pass; +- [x] B12 `npm run typecheck`(web)0 错;`cd server && npx tsc --noEmit` 0 错 + (⚠️ 根 `npm run typecheck` 的 `tsconfig.include=["src"]` **不含 server**,后端必须单独跑 `cd server && npx tsc --noEmit`); +- [x] 本地真环境:伪造签名 401;真实签名 `bid.opened` 连推两次 → **1 行邀约 + 2 条明细**(幂等); + 详情接口对不存在轮次 → 404 且台账自动 `cancelled`;提交空/5 位小数 → 400; +- [x] 红队(adversary)结论:**未发现误建单 / 跨租户 / 资金精度类高危**;两条中危(多绑定错供应商、2xx 畸形响应清空本地)已在本版修复并被单测钉住; +- [ ] **真实主系统联调**(需对方在 dev 发一轮样例竞价):发标 → 收推送 → 填价 → 对方 `bid_quotes` 落库 → 定标 → 分配 → 我方建单(阻塞在对方,见 `handoff/20261017-回主系统-竞价报价接收端已就绪.md`)。 diff --git a/docs/design/README.md b/docs/design/README.md index 602925b..f2ec405 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -137,6 +137,8 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、 配套交互式全景图(15 模块 / **326** 功能点(2026-09-29 实测;原写 318 已更正),按实现状态着色,可搜索与逐条展开)源码见 [`tools/v3-flowmap/`](../../tools/v3-flowmap/)(`data.js` 为唯一数据源,`node gen-static.mjs` 生成静态页;`flowmap.html` 为生成物不入库)。 +主系统竞价**只报价、不定标**(开发者 2026-10-17 裁决:我方不做本地竞价管理,菜单已摘除)—— 主系统发标后按 `bid.opened` 推给我方,我方落**待报价镜像台账**(两张 `public` 表,幂等键 `(round_id, supplier_code)`),页面逐行填**单价**(一次性采购价、无税/运费、>0 且 ≤4 位小数)经我方后端转发 `POST /api/supplier/bids/:round_id/quotes`,中标结果只读展示、中标后仍走既有「分配 → 建单」链路;含「对方只重试 2 次 ⇒ 我方必须能拉 `GET /api/supplier/bids` 兜底」与全套错误码映射(`bid_not_open` / `quote_deadline_passed` / `supplier_category_mismatch` / `bid_disabled` / 401 刷新重试一次),见 [20261017-主系统竞价待报价与报价提交.md](./20261017-主系统竞价待报价与报价提交.md)。 + --- ## 设计文档版本与保留策略 diff --git a/migrations/20261055_main_system_bid_invitations.sql b/migrations/20261055_main_system_bid_invitations.sql new file mode 100644 index 0000000..892eb67 --- /dev/null +++ b/migrations/20261055_main_system_bid_invitations.sql @@ -0,0 +1,99 @@ +-- 主系统竞价「待报价」镜像台账(我方**只报价、不定标**) +-- +-- 背景(开发者 2026-10-17 裁决): +-- · 我方**不做**本地竞价管理(轮次/定标/评分/比价);该功能已停用并从菜单摘除; +-- · 我方只做两件事:① 收到主系统 `bid.opened` 推送后,把「本轮需要我报价的商品」显示出来; +-- ② 逐行填**单价**并经我方后端转发 `POST /api/supplier/bids/:round_id/quotes`; +-- · 中标之后**不需要新接口**:主系统照既有「分配」流程推 `preparations.allocated`, +-- 我方按现有导入建单链路走(零改动)。 +-- +-- 为什么落 `public`(与 `main_system_actual_qty_requests` / `main_supplier_bindings` 同域): +-- 这两张是**跨系统台账/镜像**,不是租户业务数据 —— 不分租户 schema、便于跨分公司排障; +-- 归属用 `branch_code` 列表达,与既有跨系统台账同口径。 +-- +-- ⚠️ 数据所有权:竞价/邀约/报价/中标的**唯一事实源在主系统**。本表是镜像 + 我方操作留痕, +-- 随时可被对方返回覆盖(`mainSystemBidInbox.applyBidDetail` 整轮 upsert)。 +-- +-- 幂等键 = 契约里的 `(round_id, supplier_code)`,我方再加 `branch_code`(一个分公司可能绑多个 supplier_code)。 +-- +-- 设计文档:docs/design/20261017-主系统竞价待报价与报价提交.md + +CREATE TABLE IF NOT EXISTS public.main_system_bid_invitations ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + branch_code varchar(64) NOT NULL, + -- 主系统的供应商编码(= 该邀约的归属供应商;出站换 token / 提交报价都用它,不用 branch_code 冒充) + supplier_code varchar(64) NOT NULL, + -- 主系统竞价轮次 UUID(对方 `round_id`;字符串存,不做外键:跨系统主键) + round_id varchar(128) NOT NULL, + round_code varchar(128), + round_title varchar(255), + order_code varchar(128), + -- 报价截止(对方 ISO-8601;同一时刻的 UTC 表示) + respond_deadline timestamptz, + -- 本轮商品数(对方 `item_count`;webhook 退化推送时也可能为 0) + item_count integer NOT NULL DEFAULT 0, + -- 对方**轮次**状态:draft|open|closed|awarded|cancelled(事实,只按对方返回写) + round_status varchar(20) NOT NULL DEFAULT 'open', + -- 对方**邀约**状态:pending|quoted|expired(只在拉到详情/列表时才有;NULL = 尚未拉过) + main_invitation_status varchar(20), + -- 我方视图状态(派生,唯一算法在 `mainSystemBidInbox.deriveLocalStatus`) + local_status varchar(20) NOT NULL DEFAULT 'pending', + -- 我方最后一次成功提报的时刻(对方 my_quotes 里最新的 quoted_at 也写这里,便于列表排序) + quoted_at timestamptz, + webhook_received_at timestamptz, + last_synced_at timestamptz, + -- 最近一次刷新/提交失败的原因(成功后清空)——**不清空就不算同步成功** + sync_error text, + -- 最近一次入站/拉取原文(排障;不参与业务判定) + payload jsonb, + created_at timestamptz NOT NULL DEFAULT NOW(), + updated_at timestamptz NOT NULL DEFAULT NOW(), + CONSTRAINT main_system_bid_invitations_round_status_check + CHECK (round_status IN ('draft', 'open', 'closed', 'awarded', 'cancelled')), + CONSTRAINT main_system_bid_invitations_local_status_check + CHECK (local_status IN ('pending', 'quoted', 'expired', 'won', 'lost', 'cancelled')) +); + +-- 契约幂等键:同一分公司、同一轮、同一供应商只留一条邀约 +CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_bid_invitations_branch_round_supplier + ON public.main_system_bid_invitations (branch_code, round_id, supplier_code); + +-- 列表页:按分公司取待办(未截止的排前面由 ORDER BY 决定,索引只需要过滤/排序前缀) +CREATE INDEX IF NOT EXISTS idx_main_system_bid_invitations_branch_status + ON public.main_system_bid_invitations (branch_code, local_status, respond_deadline DESC NULLS LAST); + +-- 单轮刷新/提交:按 round_id 定位(前端只带 roundId) +CREATE INDEX IF NOT EXISTS idx_main_system_bid_invitations_round + ON public.main_system_bid_invitations (branch_code, round_id); + +CREATE TABLE IF NOT EXISTS public.main_system_bid_invitation_items ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + invitation_id uuid NOT NULL REFERENCES public.main_system_bid_invitations(id) ON DELETE CASCADE, + branch_code varchar(64) NOT NULL, + round_id varchar(128) NOT NULL, + sku_code varchar(120) NOT NULL, + sku_name varchar(255), + unit varchar(32), + -- 我方报的单价(对方 `my_quotes` 覆盖;一次性采购价、无税/运费、>0 且最多 4 位小数) + unit_price numeric(14,4), + remark text, + quoted_at timestamptz, + -- 对方定标结果(只读;`awards` 里没有我这行 ⇒ award_status 保持 NULL,轮次 awarded 时视图判 lost) + award_price numeric(14,4), + -- 对方 `bid_awards` 目前**没有数量列** ⇒ 该值恒 NULL(保留列以便对方将来加量时直接落库) + award_qty numeric(14,3), + award_status varchar(20), + created_at timestamptz NOT NULL DEFAULT NOW(), + updated_at timestamptz NOT NULL DEFAULT NOW(), + CONSTRAINT main_system_bid_invitation_items_award_status_check + CHECK (award_status IS NULL OR award_status IN ('won', 'lost')), + CONSTRAINT main_system_bid_invitation_items_unit_price_check + CHECK (unit_price IS NULL OR unit_price > 0) +); + +-- 同一邀约内一个 SKU 一行(对方 `bid_round_items` 也是 UNIQUE(round_id, sku_code)) +CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_bid_invitation_items_invitation_sku + ON public.main_system_bid_invitation_items (invitation_id, sku_code); + +CREATE INDEX IF NOT EXISTS idx_main_system_bid_invitation_items_invitation + ON public.main_system_bid_invitation_items (invitation_id); diff --git a/server/src/modules/businessModules.ts b/server/src/modules/businessModules.ts index 16ff618..a6e11ed 100644 --- a/server/src/modules/businessModules.ts +++ b/server/src/modules/businessModules.ts @@ -13,6 +13,7 @@ import { mountNotificationWorkflowRoutes } from './workflow/routes/notificationR import { mountInspectionWorkflowRoutes } from './workflow/routes/inspectionRoutes'; import { mountOrderWorkflowRoutes } from './workflow/routes/orderRoutes'; import { mountBidWorkflowRoutes } from './workflow/routes/bidRoutes'; +import { mountMainSystemBidWorkflowRoutes } from './workflow/routes/mainSystemBidRoutes'; import { mountPurchaseWorkflowRoutes } from './workflow/routes/purchaseRoutes'; import { mountPreparationWorkflowRoutes } from './workflow/routes/preparationRoutes'; import { mountFinanceWorkflowRoutes } from './workflow/routes/financeRoutes'; @@ -48,7 +49,10 @@ export const orderModule: BusinessModuleDescriptor = { workflowTransitions: { 20: advanceFromAllocation }, mountWorkflowRoutes: (router) => { mountOrderWorkflowRoutes(router); + // 本地竞价管理(已停用并摘除菜单,代码保留) mountBidWorkflowRoutes(router); + // 主系统竞价「待报价」:我方只报价、不定标(2026-10-17) + mountMainSystemBidWorkflowRoutes(router); }, }; diff --git a/server/src/modules/workflow/routes/mainSystemBidRoutes.ts b/server/src/modules/workflow/routes/mainSystemBidRoutes.ts new file mode 100644 index 0000000..a98029a --- /dev/null +++ b/server/src/modules/workflow/routes/mainSystemBidRoutes.ts @@ -0,0 +1,149 @@ +import { Router, Response } from 'express'; +import { authMiddleware, type AuthRequest } from '../../../middleware/auth'; +import { getEffectiveBranchCode, readOperatingBranchCode } from '../../../services/tenantScope'; +import { getWorkflowCtx, requireWorkflowPermission, sendWorkflowError } from '../context'; +import { + listBidInvitations, + refreshBidInvitation, + submitBidQuotes, + syncBidInvitations, + type BidFailure, +} from '../../../services/mainSystemBidQuotes'; + +/** + * 主系统竞价「待报价」——**我方只报价、不定标**(开发者 2026-10-17 裁决)。 + * + * 与 `bidRoutes.ts`(本地竞价管理,已停用并从菜单摘除)**是两条不同的路**: + * · `bidRoutes` = 我方自己发标/定标(保留但不再使用,勿在此文件里复活); + * · 本文件 = 收主系统 `bid.opened` 推送后,把「本轮要我报什么」显示出来 + 把单价报回去。 + * 中标之后**不需要新接口**:主系统照既有「分配」流程推 `preparations.allocated`,走现有导入建单。 + * + * 权限沿用「供需变更审核」那一页的口径(`order_manage` / `order_edit`),不新增权限码。 + * 设计文档:docs/design/20261017-主系统竞价待报价与报价提交.md §5 + */ + +/** 页面可见/可提交的权限(与菜单目录 `orders-bid-invitations` 一致) */ +const BID_QUOTE_PERMISSIONS = ['order_manage', 'order_edit', 'order_entry']; + +function branchOf(req: AuthRequest, ctx: Awaited>) { + return String(getEffectiveBranchCode(ctx, readOperatingBranchCode(req)) || ''); +} + +/** 我方失败对象 → HTTP(状态码在 service 里已定,这里只负责落地) */ +function sendBidFailure(res: Response, failure: BidFailure) { + return res.status(failure.status || 400).json({ + error: failure.code, + error_description: failure.message, + error_kind: failure.kind, + }); +} + +export function mountMainSystemBidWorkflowRoutes(router: Router): void { + /** 待报价清单(读**本地镜像**,不调外部) */ + router.get('/main-system/bid-invitations', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, BID_QUOTE_PERMISSIONS); + const branchCode = branchOf(req, ctx) || ctx?.branchCode || ''; + if (!branchCode) { + // 与其它失败同形(error/error_description/error_kind):前端只认一套字段 + return res.status(400).json({ + error: 'branch_required', + error_description: '当前账号未绑定分公司', + error_kind: 'rejected', + }); + } + const rawStatus = String(req.query?.status || '').trim().toLowerCase(); + const status = rawStatus === 'pending' || rawStatus === 'history' ? rawStatus : 'all'; + const result = await listBidInvitations({ + branchCode, + status, + limit: Number(req.query?.limit) || 50, + }); + return res.json({ data: result.rows, summary: result.summary, error: null }); + } catch (error: any) { + return sendWorkflowError(res, error, '查询待报价清单失败'); + } + }); + + /** 同步:拉主系统 `GET /api/supplier/bids` 兜底补台账(对方 webhook 只重试 2 次) */ + router.post('/main-system/bid-invitations/sync', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, BID_QUOTE_PERMISSIONS); + const branchCode = branchOf(req, ctx) || ctx?.branchCode || ''; + if (!branchCode) { + // 与其它失败同形(error/error_description/error_kind):前端只认一套字段 + return res.status(400).json({ + error: 'branch_required', + error_description: '当前账号未绑定分公司', + error_kind: 'rejected', + }); + } + const result = await syncBidInvitations(branchCode); + return res.json({ ...result, error: null }); + } catch (error: any) { + return sendWorkflowError(res, error, '同步待报价清单失败'); + } + }); + + /** 单轮刷新:以对方为准对齐明细 / 我的报价 / 我的中标 */ + router.get('/main-system/bid-invitations/:roundId', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, BID_QUOTE_PERMISSIONS); + const branchCode = branchOf(req, ctx) || ctx?.branchCode || ''; + if (!branchCode) { + // 与其它失败同形(error/error_description/error_kind):前端只认一套字段 + return res.status(400).json({ + error: 'branch_required', + error_description: '当前账号未绑定分公司', + error_kind: 'rejected', + }); + } + const outcome = await refreshBidInvitation({ + branchCode, + roundId: String(req.params.roundId || ''), + // 一个分公司可绑多个 supplier_code,同一轮可能有两行 ⇒ 前端按行的 `supplierCode` 指定 + supplierCode: req.query?.supplier ? String(req.query.supplier) : null, + }); + if (outcome.kind !== 'ok') return sendBidFailure(res, outcome); + return res.json({ data: outcome.detail, error: null }); + } catch (error: any) { + return sendWorkflowError(res, error, '刷新竞价详情失败'); + } + }); + + /** 提交报价(唯一写主系统的入口;成功才回填本地) */ + router.post('/main-system/bid-invitations/:roundId/quotes', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, BID_QUOTE_PERMISSIONS); + const branchCode = branchOf(req, ctx) || ctx?.branchCode || ''; + if (!branchCode) { + // 与其它失败同形(error/error_description/error_kind):前端只认一套字段 + return res.status(400).json({ + error: 'branch_required', + error_description: '当前账号未绑定分公司', + error_kind: 'rejected', + }); + } + const rawQuotes = Array.isArray(req.body?.quotes) ? req.body.quotes : []; + const quotes = rawQuotes.map((row: any) => ({ + skuCode: String(row?.skuCode ?? row?.sku_code ?? ''), + unitPrice: row?.unitPrice ?? row?.unit_price, + remark: row?.remark ?? null, + })); + const outcome = await submitBidQuotes({ + branchCode, + roundId: String(req.params.roundId || ''), + supplierCode: req.body?.supplierCode ? String(req.body.supplierCode) : null, + quotes, + }); + if (outcome.kind !== 'ok') return sendBidFailure(res, outcome); + return res.json({ data: outcome.detail, error: null }); + } catch (error: any) { + return sendWorkflowError(res, error, '提交报价失败'); + } + }); +} diff --git a/server/src/routes/mainSystemIntegration.ts b/server/src/routes/mainSystemIntegration.ts index dae34f1..8f9ea28 100644 --- a/server/src/routes/mainSystemIntegration.ts +++ b/server/src/routes/mainSystemIntegration.ts @@ -35,6 +35,8 @@ import { } from '../services/mainSystemActualQtyInbox'; // 备货行「单位」变更事实(2026-10-13,主系统 `preparations.unit_changed` 的接收端;设计文 §11.9) import { applyUnitChangedFact } from '../services/mainSystemUnitChangedInbox'; +// 主系统竞价「待报价」接收端(`bid.opened`;我方只报价、不定标) +import { isBidOpenedEvent, recordBidOpened } from '../services/mainSystemBidInbox'; import type { MainPreparationRow } from '../services/mainSystemPreparations'; /** @@ -464,6 +466,31 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => { return res.json({ ok: true, ignored: true, reason: resolved.ok ? 'not_bound' : resolved.reason }); } + /* ── 竞价开始推送 `bid.opened`(2026-10-17,我方只报价、不定标)──────────────── + * 主系统发标后按「已绑接入编码的受邀供应商」逐个 POST 本 webhook(同一套签名/重试)。 + * 载荷**不含 `data[]`**(那是备货行导入的语义)⇒ 必须**就地 return**, + * 否则会一路落到底部「preparations.allocated」的建单兜底,被将来的数组载荷误建单。 + * + * 我方动作:只落**待报价镜像台账**(邀约头 + 商品名),不建单、不回写、不定标。 + * 幂等键 `(branch_code, round_id, supplier_code)`;业务失败一律 200(重推解决不了前置问题, + * 且对方只重试 2 次 ⇒ 真正的兜底是我方页面上的「同步」,那条走 GET /api/supplier/bids)。 + * 设计:docs/design/20261017-主系统竞价待报价与报价提交.md §2.1 + */ + if (isBidOpenedEvent(event)) { + if (!supplierCode) { + // 邀约归属键就是 supplier_code(一个分公司可能绑多个编码)⇒ 缺了无法落账 + return res.json({ ok: true, ignored: true, reason: 'missing_supplier_code' }); + } + const recorded = await recordBidOpened({ branchCode, supplierCode, payload }); + console.log( + `[main-system-webhook] ${branchCode}(supplier=${supplierCode})${event}:` + + `${recorded.status} round=${recorded.roundId || '—'} 商品 ${recorded.itemCount ?? 0}` + + `${recorded.localStatus ? ` 状态=${recorded.localStatus}` : ''}` + + `${recorded.reason ? ` — ${recorded.reason}` : ''}` + ); + return res.json({ ok: true, ...recorded }); + } + /* ── 履约事件(2026-10-10):主系统通知"货被取走 / 已入库",我方据此收口 ────────── * `picked_up`(免入库,主系统确认发车)/ `inbound_completed`(送仓,全部入库完成)。 * 契约见主系统 docs/design/20261010-supplier-prep-fulfillment-events.md; diff --git a/server/src/services/mainSystem/api/bids.ts b/server/src/services/mainSystem/api/bids.ts new file mode 100644 index 0000000..f569d41 --- /dev/null +++ b/server/src/services/mainSystem/api/bids.ts @@ -0,0 +1,355 @@ +import { getMainSystemToken } from '../token'; +import { requestMainSystem, type MainSystemResult } from '../http'; +import { mainSystemBidPath } from '../endpoints'; +import { + MAIN_SYSTEM_FETCH_TIMEOUT_MS, + isMainSystemIntegrationEnabled, + mainSystemTimeoutMs, +} from '../config'; + +/** + * 主系统**竞价(供应商侧)**接口封装(我方只报价、不定标)。 + * + * 这一层只有类型 + 字段映射 + 结果枚举;URL 走 `endpoints.mainSystemBidPath()`、 + * token 走 `../token.ts`(全仓唯一缓存)、HTTP 走 `../http.ts`(唯一出口)。 + * + * 对应契约(对方 `server/src/routes/supplier/supplierBusinessRoutes.ts`): + * · `GET /api/supplier/bids` → `{ data: [邀约行…], settings }`(`settings.enabled=false` ⇒ 空) + * · `GET /api/supplier/bids/:round_id` → `{ data: { round, items, invitation, my_quotes, awards } }` + * · `POST /api/supplier/bids/:round_id/quotes` → 请求 `{ quotes: [{ sku_code, unit_price, remark? }] }`, + * 成功回上面那个 `data`(**只有我的视角**,无别家报价/中标) + * + * ⚠️ 纪律:`supplier_code` **只从 token 身份取**(对方按 token 鉴权),请求体里不放; + * 调用方传的 `supplierCode` 就是换 token 用的那个编码(= 该邀约的 `supplier_code` 列)。 + * 设计文档:docs/design/20261017-主系统竞价待报价与报价提交.md §2 + */ + +/** 报价截止/时间字段统一成 ISO;不可解析的原样保留(便于排障) */ +function isoOrNull(value: unknown): 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 String(value); + 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): string | null { + if (value === null || value === undefined) return null; + const text = String(value).trim(); + return text ? text : null; +} + +/** 对方邀约行(`bid_invitations` ⋈ `bid_rounds`,字段名照对方返回,camel 化后给业务层) */ +export type MainSupplierBidInvitation = { + roundId: string; + roundCode: string | null; + roundTitle: string | null; + orderCode: string | null; + /** 轮次状态:draft|open|closed|awarded|cancelled */ + roundStatus: string | null; + /** 我对本轮的邀约状态:pending|quoted|expired */ + invitationStatus: string | null; + respondDeadline: string | null; + itemCount: number | null; + invitedAt: string | null; + quotedAt: string | null; +}; + +export type MainSupplierBidItem = { + skuCode: string; + skuName: string | null; + unit: string | null; +}; + +export type MainSupplierBidQuote = { + skuCode: string; + unitPrice: number | null; + remark: string | null; + createdAt: string | null; + updatedAt: string | null; +}; + +export type MainSupplierBidAward = { + skuCode: string; + unitPrice: number | null; + awardedAt: string | null; +}; + +export type MainSupplierBidDetail = { + round: { + roundId: string; + roundCode: string | null; + title: string | null; + orderCode: string | null; + status: string | null; + respondDeadline: string | null; + }; + invitation: { status: string | null; respondDeadline: string | null }; + items: MainSupplierBidItem[]; + myQuotes: MainSupplierBidQuote[]; + myAwards: MainSupplierBidAward[]; +}; + +/** 失败三态(与既有服务层枚举一致)+ 对方错误码(映射成界面文案的唯一依据) */ +export type MainBidFailure = { + kind: 'rejected' | 'unavailable' | 'not_configured'; + status: number; + code: string; + reason: string; +}; + +export type MainBidListOutcome = + | { kind: 'ok'; enabled: boolean; settings: unknown; rows: MainSupplierBidInvitation[] } + | MainBidFailure; + +export type MainBidDetailOutcome = { kind: 'ok'; detail: MainSupplierBidDetail } | MainBidFailure; + +/** 对方错误码(`payload.error`);没带就用状态码兜一个稳定的内部码 */ +export function readBidErrorCode(payload: unknown, status: number): string { + const p = payload as { error?: unknown; code?: unknown } | null; + const raw = toText(p?.error) || toText(p?.code); + if (raw) return raw; + if (status === 401) return 'unauthorized'; + if (status === 403) return 'forbidden'; + if (status === 404) return 'not_found'; + if (status >= 500) return 'main_system_error'; + return 'request_failed'; +} + +function toFailure(result: Exclude, { kind: 'ok' }>): MainBidFailure { + const status = Number(result.status) || 0; + return { + kind: result.kind, + status, + code: readBidErrorCode((result as { payload?: unknown }).payload, status), + reason: result.reason || '调用主系统失败', + }; +} + +/** + * 换 token + 调用 + **401 强制刷新重试一次**。 + * + * 为什么重试只做一次:token 24h,提前刷新的比例散列写在 `token.ts` 里; + * 真正 401 说明对方那边已判失效(轮换/撤销),再刷也白刷,第二次失败直接上报。 + */ +async function callWithToken( + supplierCode: string, + call: (token: string) => Promise> +): Promise> { + const first = await getMainSystemToken(supplierCode); + if (first.kind !== 'ok') { + return { + kind: first.kind === 'not_configured' ? 'not_configured' : 'unavailable', + status: 0, + reason: first.reason, + payload: null, + }; + } + const result = await call(first.token); + if (result.kind === 'ok' || Number(result.status) !== 401) return result; + const refreshed = await getMainSystemToken(supplierCode, { forceRefresh: true }); + if (refreshed.kind !== 'ok') { + return { + kind: refreshed.kind === 'not_configured' ? 'not_configured' : 'unavailable', + status: 0, + reason: refreshed.reason, + payload: null, + }; + } + return call(refreshed.token); +} + +/** + * 403 在本项目 HTTP 层的默认归类是"暂态"(下轮重试),但竞价的 403 是**语义拒绝** + * (未受邀 / 未绑定编码 / 超出经营品类)⇒ 用 `classify` 改成 rejected,避免当网络故障重试。 + */ +const classifyBidAuth = (input: { status: number }) => (input.status === 403 ? 'rejected' : null); + +/** 列表兜底:`GET /api/supplier/bids` */ +export async function listMainSupplierBids(supplierCode: string): Promise { + if (!isMainSystemIntegrationEnabled()) { + return { kind: 'not_configured', status: 0, code: 'not_configured', reason: '主系统对接未配置' }; + } + const result = await callWithToken(supplierCode, (token) => + requestMainSystem({ + endpoint: 'bids', + method: 'GET', + token, + timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS, + timeoutReason: '拉取待报价清单超时', + networkReasonPrefix: '拉取待报价清单失败:', + classify: classifyBidAuth, + }) + ); + if (result.kind !== 'ok') return toFailure(result); + + const payload = result.data as any; + const settings = payload?.settings ?? null; + const raw = Array.isArray(payload?.data) ? payload.data : Array.isArray(payload) ? payload : []; + const rows: MainSupplierBidInvitation[] = raw + .map((row: any) => ({ + roundId: toText(row?.round_id) || '', + roundCode: toText(row?.round_code), + roundTitle: toText(row?.title), + orderCode: toText(row?.order_code), + roundStatus: toText(row?.round_status), + invitationStatus: toText(row?.status), + respondDeadline: isoOrNull(row?.respond_deadline ?? row?.round_respond_deadline), + itemCount: toNumber(row?.item_count), + invitedAt: isoOrNull(row?.invited_at), + quotedAt: isoOrNull(row?.quoted_at), + })) + .filter((row: MainSupplierBidInvitation) => Boolean(row.roundId)); + return { + kind: 'ok', + enabled: settings?.enabled === true, + settings, + rows, + }; +} + +/** 单轮详情:`GET /api/supplier/bids/:round_id` */ +export async function getMainSupplierBidDetail( + supplierCode: string, + roundId: string +): Promise { + if (!isMainSystemIntegrationEnabled()) { + return { kind: 'not_configured', status: 0, code: 'not_configured', reason: '主系统对接未配置' }; + } + const id = String(roundId || '').trim(); + if (!id) return { kind: 'rejected', status: 400, code: 'round_id_required', reason: '缺少竞价轮次 ID' }; + + const result = await callWithToken(supplierCode, (token) => + requestMainSystem({ + endpoint: 'bids', + path: mainSystemBidPath(id), + method: 'GET', + token, + timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS, + timeoutReason: '读取竞价详情超时', + networkReasonPrefix: '读取竞价详情失败:', + classify: classifyBidAuth, + }) + ); + if (result.kind !== 'ok') return toFailure(result); + const detail = mapDetail((result.data as any)?.data ?? result.data); + // 响应不可识别 ⇒ 按失败处理、**不落库**(否则"先清空再写"会抹掉我方已报价与中标) + if (isDegenerateDetail(detail)) return degenerateFailure(); + return { kind: 'ok', detail }; +} + +/** 提交报价:`POST /api/supplier/bids/:round_id/quotes`(成功后回同一份详情) */ +export async function submitMainSupplierBidQuotes(input: { + supplierCode: string; + roundId: string; + quotes: Array<{ skuCode: string; unitPrice: number; remark?: string | null }>; +}): Promise { + if (!isMainSystemIntegrationEnabled()) { + return { kind: 'not_configured', status: 0, code: 'not_configured', reason: '主系统对接未配置' }; + } + const id = String(input.roundId || '').trim(); + const quotes = Array.isArray(input.quotes) ? input.quotes : []; + if (!id) return { kind: 'rejected', status: 400, code: 'round_id_required', reason: '缺少竞价轮次 ID' }; + if (!quotes.length) { + return { kind: 'rejected', status: 400, code: 'quotes_required', reason: '请至少提交一条报价' }; + } + + const result = await callWithToken(input.supplierCode, (token) => + requestMainSystem({ + endpoint: 'bids', + path: mainSystemBidPath(id, 'quotes'), + method: 'POST', + token, + // 字段名照对方契约(snake_case):本层是唯一做这个映射的地方 + body: { + quotes: quotes.map((quote) => ({ + sku_code: String(quote.skuCode || '').trim(), + unit_price: Number(quote.unitPrice), + remark: quote.remark === undefined || quote.remark === null ? null : String(quote.remark), + })), + }, + // 提交比读取更慢(对方要写事务),给宽松一点的超时但仍受统一出口控制 + timeoutMs: mainSystemTimeoutMs() + MAIN_SYSTEM_FETCH_TIMEOUT_MS, + timeoutReason: '提交报价超时(对方可能已受理,请稍后刷新确认)', + networkReasonPrefix: '提交报价失败:', + classify: classifyBidAuth, + }) + ); + if (result.kind !== 'ok') return toFailure(result); + const detail = mapDetail((result.data as any)?.data ?? result.data); + // 响应不可识别 ⇒ 按失败处理、**不落库**(否则"先清空再写"会抹掉我方已报价与中标) + if (isDegenerateDetail(detail)) return degenerateFailure(); + return { kind: 'ok', detail }; +} + +/** + * **退化载荷守卫**(2026-10-17 独立复核发现的真风险): + * 对方返回 2xx 但 `data` 里既没有轮次 id、也没有明细/我的报价/中标 ⇒ 这不是"这一轮空了", + * 而是**响应不可识别**(网关 HTML、字段改名、序列化差异)。若照常落库, + * `applyBidDetail` 的"先清空再写"会把我方已报价与中标全部抹掉、并把轮次写回 open ⇒ 假事实。 + */ +function isDegenerateDetail(detail: MainSupplierBidDetail | null | undefined): boolean { + if (!detail) return true; + const roundId = String(detail.round?.roundId || '').trim(); + return !roundId && !detail.items.length && !detail.myQuotes.length && !detail.myAwards.length; +} + +/** 不可识别响应 → 统一失败(`unavailable`:可重试,且**不得**落库) */ +function degenerateFailure(): MainBidFailure { + return { + kind: 'unavailable', + status: 0, + code: 'invalid_main_system_response', + reason: '主系统返回的竞价视图不可识别(缺少轮次/明细)', + }; +} + +function mapDetail(raw: any): MainSupplierBidDetail { + const round = raw?.round || {}; + const invitation = raw?.invitation || {}; + const items = Array.isArray(raw?.items) ? raw.items : []; + const quotes = Array.isArray(raw?.my_quotes) ? raw.my_quotes : []; + const awards = Array.isArray(raw?.awards) ? raw.awards : []; + return { + round: { + roundId: toText(round?.id) || '', + roundCode: toText(round?.round_code), + title: toText(round?.title), + orderCode: toText(round?.order_code), + status: toText(round?.status), + respondDeadline: isoOrNull(round?.respond_deadline), + }, + invitation: { + status: toText(invitation?.status), + respondDeadline: isoOrNull(invitation?.respond_deadline), + }, + items: items + .map((row: any) => ({ + skuCode: toText(row?.sku_code) || '', + skuName: toText(row?.sku_name), + unit: toText(row?.unit), + })) + .filter((row: { skuCode: string }) => Boolean(row.skuCode)), + myQuotes: quotes + .map((row: any) => ({ + skuCode: toText(row?.sku_code) || '', + unitPrice: toNumber(row?.unit_price), + remark: toText(row?.remark), + createdAt: isoOrNull(row?.created_at), + updatedAt: isoOrNull(row?.updated_at), + })) + .filter((row: { skuCode: string }) => Boolean(row.skuCode)), + myAwards: awards + .map((row: any) => ({ + skuCode: toText(row?.sku_code) || '', + unitPrice: toNumber(row?.unit_price), + awardedAt: isoOrNull(row?.awarded_at), + })) + .filter((row: { skuCode: string }) => Boolean(row.skuCode)), + }; +} diff --git a/server/src/services/mainSystem/config.ts b/server/src/services/mainSystem/config.ts index a3c7438..b8eaefb 100644 --- a/server/src/services/mainSystem/config.ts +++ b/server/src/services/mainSystem/config.ts @@ -35,6 +35,14 @@ export const MAIN_SYSTEM_DEFAULT_PATHS = { */ qualityReportUpload: '/api/storage/quality-reports/upload', qualityReportRegister: '/api/supplier/quality-reports', + /** + * 主系统竞价(**我方只报价、不定标**,2026-10-17 交接后的对接): + * · `GET /api/supplier/bids` → 邀约列表(webhook 漏推时的兜底) + * · `GET /api/supplier/bids/:round_id` → 单轮详情(明细 + 我的报价 + 我的中标) + * · `POST /api/supplier/bids/:round_id/quotes` → 提交报价(批量 upsert) + * 设计:docs/design/20261017-主系统竞价待报价与报价提交.md + */ + bids: '/api/supplier/bids', } as const; export type MainSystemEndpoint = keyof typeof MAIN_SYSTEM_DEFAULT_PATHS; diff --git a/server/src/services/mainSystem/endpoints.ts b/server/src/services/mainSystem/endpoints.ts index 5a61ec3..8f7255f 100644 --- a/server/src/services/mainSystem/endpoints.ts +++ b/server/src/services/mainSystem/endpoints.ts @@ -57,6 +57,20 @@ export function mainSystemLookupPath(): string { export type MainSystemQuery = Record; +/** + * 竞价的**子路径**:`{bids}` / `{bids}/:round_id` / `{bids}/:round_id/quotes`。 + * + * 只走 `mainSystemPath('bids')`(跟着端点表与覆盖走),本函数是唯一拼竞价 URL 的地方; + * `roundId` 只做路径段转义,不做别的加工(对方按 UUID 收)。 + */ +export function mainSystemBidPath(roundId?: string | null, tail?: 'quotes' | null): string { + const base = mainSystemPath('bids').replace(/\/+$/, ''); + const id = String(roundId || '').trim(); + if (!id) return base; + const segment = `${base}/${encodeURIComponent(id)}`; + return tail === 'quotes' ? `${segment}/quotes` : segment; +} + /** 组装完整 URL(含 query;空值自动省略)。**唯一**允许拼主系统 URL 的函数。 */ export function buildMainSystemUrl(endpoint: MainSystemEndpoint, query?: MainSystemQuery): string { const base = mainSystemBaseUrl(); diff --git a/server/src/services/mainSystemBidInbox.ts b/server/src/services/mainSystemBidInbox.ts new file mode 100644 index 0000000..fccc00e --- /dev/null +++ b/server/src/services/mainSystemBidInbox.ts @@ -0,0 +1,857 @@ +/** + * 主系统竞价「待报价」**接收端 + 我方镜像台账**(我方只报价、不定标)。 + * + * 事实源在主系统:竞价轮次 / 邀约 / 我方报价 / 中标。本模块只做两件事: + * ① 把 `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; +}; + +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; + 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` + * 3. 邀约过期(对方说 expired,或截止时间已过)⇒ `expired` + * 4. 已报(对方说 quoted,或本地每一行都有价)⇒ `quoted` + * 5. 其余 ⇒ `pending` + * + * 注意顺序:**先看轮次**(已定标/取消比"过期"更权威),再看邀约。 + * 截止时间比较用**我方服务器时钟**(与主系统同机部署,偏差可忽略);最终裁决仍在对方。 + */ +export function deriveLocalStatus(input: { + roundStatus: string; + mainInvitationStatus?: string | null; + respondDeadline?: Date | string | null; + itemCount: number; + quotedCount: number; + hasAward: boolean; + now?: Date; +}): BidLocalStatus { + const roundStatus = String(input.roundStatus || 'open'); + if (roundStatus === 'cancelled') return 'cancelled'; + if (roundStatus === 'awarded') return input.hasAward ? 'won' : 'lost'; + + const mainStatus = input.mainInvitationStatus ? String(input.mainInvitationStatus) : ''; + 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'; + + const itemCount = Number(input.itemCount) || 0; + const quotedCount = Number(input.quotedCount) || 0; + if (mainStatus === 'quoted') return 'quoted'; + if (itemCount > 0 && quotedCount >= itemCount) return 'quoted'; + 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), + }; +} + +export function toBidInvitationItemDto( + row: BidInvitationItemRow, + roundStatus: string +): BidInvitationItemDto { + const awardPrice = toNumber(row.award_price); + const awardStatus: 'won' | 'lost' | null = + row.award_status === 'won' || awardPrice !== null + ? 'won' + : 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(fn: (client: any) => Promise): Promise { + 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 { + 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, + (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, + }); + 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 { + 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 { + 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(); + 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( + `SELECT * FROM public.main_system_bid_invitations + WHERE branch_code = $1 AND round_id = $2 AND upper(supplier_code) = upper($3) + LIMIT 1`, + [branchCode, roundId, supplierCode] + ); + return rows[0] ? { kind: 'found', row: rows[0] } : { kind: 'missing' }; + } + const { rows } = await pool.query( + `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; + limit?: number; +}): Promise<{ rows: BidInvitationRow[]; counts: Record }> { + 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 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( + `SELECT * FROM public.main_system_bid_invitations + WHERE branch_code = $1 ${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 + GROUP BY local_status`, + [branchCode] + ), + ]); + + const countsMap: Record = {}; + for (const row of counts.rows) countsMap[String(row.local_status)] = Number(row.n) || 0; + return { rows: rows.rows, counts: countsMap }; +} + +export async function listInvitationItems(invitationId: string): Promise { + const { rows } = await pool.query( + `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 { + 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 { + 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 { + 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, + ] + ); +} diff --git a/server/src/services/mainSystemBidQuotes.ts b/server/src/services/mainSystemBidQuotes.ts new file mode 100644 index 0000000..8cfb9b6 --- /dev/null +++ b/server/src/services/mainSystemBidQuotes.ts @@ -0,0 +1,496 @@ +/** + * 主系统竞价:**我方只报价、不定标**——页面用到的读/写业务逻辑都在这里。 + * + * 三件事: + * ① `listBidInvitations` 读**本地镜像**(页面首屏,不调外部,不会被主系统抖动拖住); + * ② `syncBidInvitations` 拉对方 `GET /api/supplier/bids` 兜底补台账(对方 webhook 只重试 2 次); + * ③ `refreshBidInvitation` / `submitBidQuotes` 单轮对齐 + 提交报价(唯一写主系统的地方)。 + * + * 纪律: + * · 提交前的本地校验只为**少发一次注定失败的请求**,最终裁决权在主系统: + * 对方返回的 `bid_not_open` / `quote_deadline_passed` / `supplier_category_mismatch` 一律照实映射; + * · 提交失败**不改本地报价**(避免"以为报上了");只有对方返回成功视图才整轮 upsert; + * · 我方错误码与对方错误码**同形**(`error` 字段),前端只认一套。 + * + * 设计文档:docs/design/20261017-主系统竞价待报价与报价提交.md + */ +import { + applyBidDetail, + findInvitationByRound, + getBidInvitationDetail, + listInvitationRows, + markInvitationCancelled, + markInvitationSyncError, + toBidInvitationDto, + upsertInvitationHeaders, + type BidInvitationDetailDto, +} from './mainSystemBidInbox'; +import { + getMainSupplierBidDetail, + listMainSupplierBids, + submitMainSupplierBidQuotes, + type MainBidFailure, + type MainSupplierBidDetail, +} from './mainSystem/api/bids'; +import { listSupplierCodesForBranch } from './mainSystemBranchApi'; + +/** 界面文案的**唯一**映射表(对方错误码 → 中文提示;我方错误码同表) */ +export const BID_ERROR_COPY: Record = { + // ── 对方错误码(契约 §2.3)── + bid_not_open: '本轮已结束报价,无法提交', + quote_deadline_passed: '已超过报价截止时间,本轮已出局', + supplier_category_mismatch: '该商品不在你的经营品类内,无法报价', + bid_disabled: '对方未开启竞价功能', + not_found: '竞价单不存在或已被取消', + forbidden: '无权查看本轮竞价', + unauthorized: '对方登录凭据已失效,请稍后重试', + main_system_error: '对方系统暂不可用,请稍后重试', + request_failed: '提交报价失败,请稍后重试', + // ── 我方错误码 ── + bid_invitation_not_found: '本地没有这轮竞价的记录,请先点「同步」', + quotes_required: '请至少填写一条报价', + invalid_unit_price: '报价必须是大于 0 且最多 4 位小数的数字', + sku_not_in_round: '该商品不在本轮竞价的商品清单里,请先刷新', + main_system_unavailable: '对方系统暂不可用,请稍后重试', + invalid_main_system_response: '对方返回的数据无法识别(缺少轮次/明细),本次未落库,请稍后重试', + main_system_not_configured: '主系统对接未配置,无法提交报价', + branch_required: '当前账号未绑定分公司', +}; + +export function bidErrorCopy(code: string, fallback?: string | null): string { + const key = String(code || '').trim(); + if (key && BID_ERROR_COPY[key]) return BID_ERROR_COPY[key]; + const text = String(fallback || '').trim(); + return text || BID_ERROR_COPY.request_failed; +} + +export type BidFailure = { + kind: 'rejected' | 'unavailable' | 'not_configured'; + status: number; + code: string; + message: string; +}; + +export type BidListOutcome = { + rows: ReturnType[]; + summary: { + pending: number; + quoted: number; + expired: number; + closed: number; + won: number; + lost: number; + cancelled: number; + }; +}; + +export type BidSyncOutcome = { + synced: number; + skipped: number; + unavailable: number; + /** 对方竞价开关是否开启(false ⇒ 对方没开竞价,我方清单只会是空的/旧的) */ + enabled: boolean; + /** 该分公司有没有可出站的供应商编码(未绑定接入编码 ⇒ 一个请求都不会发) */ + bound: boolean; +}; + +export type BidDetailOutcome = { kind: 'ok'; detail: BidInvitationDetailDto } | BidFailure; + +/** + * 轮次 ID 形态校验(对方是 UUID,我方按"字母数字-下划线"放行并限长)。 + * + * 为什么要它(红队 #6):`%00` 之类的控制字符会一路进到 Postgres 参数里报 500 并把原始错误回显给前端; + * 在入口挡掉比在下游 try/catch 更干净。非法形态 = 客户端问题(400),不是对方不可用。 + */ +export function isValidBidRoundId(value: unknown): boolean { + const text = String(value || '').trim(); + return /^[0-9A-Za-z_-]{1,64}$/.test(text); +} + +/** 我方错误码 → 失败对象(HTTP 状态码在这里定,路由层照抄) */ +function localFailure(input: { + code: string; + status: number; + kind?: BidFailure['kind']; + message?: string; +}): BidFailure { + return { + kind: input.kind || 'rejected', + status: input.status, + code: input.code, + message: input.message || bidErrorCopy(input.code), + }; +} + +/** 对方失败 → 我方失败(HTTP 状态码照对方;对方不可用统一 502) */ +function fromMainFailure(failure: MainBidFailure): BidFailure { + if (failure.kind === 'not_configured') { + return localFailure({ code: 'main_system_not_configured', status: 503, kind: 'not_configured' }); + } + if (failure.kind === 'unavailable') { + /** + * 默认把"对方不可用"折叠成 `main_system_unavailable`; + * 但**我方自己判定出来的码**(如 `invalid_main_system_response`)要原样透出 —— + * 它表达的是"响应不可识别、本次未落库",界面上与"对方挂了"是可区分的两件事(tester F1)。 + */ + const ownCode = + failure.code === 'invalid_main_system_response' || failure.code === 'unauthorized' + ? failure.code + : 'main_system_unavailable'; + return localFailure({ + code: ownCode, + status: 502, + kind: 'unavailable', + message: bidErrorCopy(failure.code, failure.reason), + }); + } + /** + * 对方的 4xx 语义拒绝:状态码照抄(400/403/404),文案按错误码映射。 + * + * ⚠️ `supplier_category_mismatch` 例外:**必须把对方的 `error_description` 原样透出** + * —— 对方文案里带商品编码("商品 SKU123 不在你的经营品类内…"),而前端要靠这句话里的 + * sku 把**那一行**标红。若这里换成固定文案,界面就只能整单报错、无法定位是哪一行。 + */ + const message = + failure.code === 'supplier_category_mismatch' && String(failure.reason || '').trim() + ? String(failure.reason).trim() + : bidErrorCopy(failure.code, failure.reason); + return localFailure({ + code: failure.code, + status: failure.status >= 400 && failure.status < 500 ? failure.status : 400, + message, + }); +} + +function emptySummary() { + return { pending: 0, quoted: 0, expired: 0, closed: 0, won: 0, lost: 0, cancelled: 0 }; +} + +/* ── ① 读本地镜像 ─────────────────────────────────────────────────────────── */ + +export async function listBidInvitations(input: { + branchCode: string; + status?: 'all' | 'pending' | 'history' | null; + limit?: number; +}): Promise { + const { rows, counts } = await listInvitationRows(input); + const summary = emptySummary(); + for (const [key, value] of Object.entries(counts)) { + if (key in summary) (summary as Record)[key] = Number(value) || 0; + } + summary.closed = summary.won + summary.lost + summary.cancelled; + return { rows: rows.map((row) => toBidInvitationDto(row)), summary }; +} + +/* ── ② 拉取兜底 ───────────────────────────────────────────────────────────── */ + +/** + * 主系统只重试 2 次推送 ⇒ 这条拉取是**唯一的兜底通道**。 + * + * 逐个生效绑定(一个分公司可能绑多个 supplier_code)拉列表,只 upsert 邀约头: + * 对方列表接口不发明细,明细在"打开某一轮"时由 `refreshBidInvitation` 补齐。 + */ +export async function syncBidInvitations(branchCode: string): Promise { + const code = String(branchCode || '').trim(); + const supplierCodes = code ? await listSupplierCodesForBranch(code) : []; + if (!supplierCodes.length) { + return { synced: 0, skipped: 0, unavailable: 0, enabled: false, bound: false }; + } + let synced = 0; + // `skipped` 结构性恒 0(列表行必带 roundId ⇒ INSERT 必成功);保留字段是为了响应形状稳定 + const skipped = 0; + let unavailable = 0; + let enabled = false; + for (const supplierCode of supplierCodes) { + const outcome = await listMainSupplierBids(supplierCode); + if (outcome.kind !== 'ok') { + unavailable += 1; + continue; + } + if (outcome.enabled) enabled = true; + const result = await upsertInvitationHeaders({ + branchCode: code, + supplierCode, + rows: outcome.rows.map((row) => ({ + roundId: row.roundId, + roundCode: row.roundCode, + roundTitle: row.roundTitle, + orderCode: row.orderCode, + respondDeadline: row.respondDeadline, + itemCount: row.itemCount, + roundStatus: row.roundStatus, + invitationStatus: row.invitationStatus, + })), + }); + synced += result.upserted; + } + return { synced, skipped, unavailable, enabled, bound: true }; +} + +/** 对方详情(camelCase)→ 落库入参(snake_case):**唯一**的字段映射点,避免两处写法漂移 */ +function toDetailInput(detail: MainSupplierBidDetail) { + return { + round: { + id: detail.round.roundId, + round_code: detail.round.roundCode, + title: detail.round.title, + order_code: detail.round.orderCode, + status: detail.round.status, + respond_deadline: detail.round.respondDeadline, + }, + invitation: { + status: detail.invitation.status, + respond_deadline: detail.invitation.respondDeadline, + }, + items: detail.items.map((item) => ({ + sku_code: item.skuCode, + sku_name: item.skuName, + unit: item.unit, + })), + myQuotes: detail.myQuotes.map((quote) => ({ + sku_code: quote.skuCode, + unit_price: quote.unitPrice, + remark: quote.remark, + created_at: quote.createdAt, + updated_at: quote.updatedAt, + })), + myAwards: detail.myAwards.map((award) => ({ + sku_code: award.skuCode, + unit_price: award.unitPrice, + })), + }; +} + +/* ── ③ 单轮对齐 / 提交 ────────────────────────────────────────────────────── */ + +/** 定位这轮属于哪个 supplier_code:优先用台账(webhook 落的),没有就先同步一次再找 */ +async function resolveInvitation(input: { + branchCode: string; + roundId: string; + supplierCode?: string | null; + syncIfMissing: boolean; +}): Promise<{ ok: true; supplierCode: string } | { ok: false; failure: BidFailure }> { + const roundId = String(input.roundId || '').trim(); + const branchCode = String(input.branchCode || '').trim(); + const supplierCode = String(input.supplierCode || '').trim(); + if (!branchCode) { + return { ok: false, failure: localFailure({ code: 'branch_required', status: 400 }) }; + } + if (!roundId) { + return { ok: false, failure: localFailure({ code: 'round_id_required', status: 400, message: '缺少竞价轮次 ID' }) }; + } + if (!isValidBidRoundId(roundId)) { + return { ok: false, failure: localFailure({ code: 'invalid_round_id', status: 400, message: '竞价轮次 ID 非法' }) }; + } + + const pick = async () => + findInvitationByRound({ branchCode, roundId, supplierCode: supplierCode || null }); + let found = await pick(); + if (found.kind === 'missing' && input.syncIfMissing) { + await syncBidInvitations(branchCode); + found = await pick(); + } + if (found.kind === 'ambiguous') { + /** + * 同一轮有两个绑定编码都被邀请 ⇒ 不能替用户选哪一家。 + * 让前端带上 `supplier`(清单每行都带 `supplierCode`)再来一次,避免"以另一家身份报价"。 + */ + return { + ok: false, + failure: localFailure({ + code: 'bid_invitation_ambiguous', + status: 409, + message: '该竞价单有多条供应商邀约,请从清单里点具体那一条', + }), + }; + } + if (found.kind !== 'found') { + return { ok: false, failure: localFailure({ code: 'bid_invitation_not_found', status: 404 }) }; + } + return { ok: true, supplierCode: String(found.row.supplier_code) }; +} + +/** + * 打开某一轮:以对方为准整轮对齐(明细 / 我的报价 / 我的中标)。 + * + * 对方说这轮不存在或无权查看(404/403)⇒ 我方台账**停用该行**并留 sync_error, + * 让列表页不再把一轮"对方已经没有了"的竞价挂在待办里。 + */ +export async function refreshBidInvitation(input: { + branchCode: string; + roundId: string; + /** 多绑定时用来定位具体那一条邀约(清单每行都带 `supplierCode`) */ + supplierCode?: string | null; +}): Promise { + const resolved = await resolveInvitation({ ...input, syncIfMissing: true }); + if (!resolved.ok) return resolved.failure; + + const outcome = await getMainSupplierBidDetail(resolved.supplierCode, input.roundId); + if (outcome.kind !== 'ok') { + const failure = fromMainFailure(outcome); + if (outcome.kind === 'rejected' && (failure.code === 'not_found' || failure.code === 'forbidden')) { + await markInvitationCancelled({ + branchCode: input.branchCode, + roundId: input.roundId, + supplierCode: resolved.supplierCode, + reason: `${failure.code}: ${failure.message}`, + }); + } else { + await markInvitationSyncError({ + branchCode: input.branchCode, + roundId: input.roundId, + supplierCode: resolved.supplierCode, + reason: `${failure.code}: ${failure.message}`, + }); + } + return failure; + } + + await applyBidDetail({ + branchCode: input.branchCode, + supplierCode: resolved.supplierCode, + roundId: input.roundId, + detail: toDetailInput(outcome.detail), + payload: outcome.detail, + }); + + const detail = await getBidInvitationDetail(input); + if (!detail) return localFailure({ code: 'bid_invitation_not_found', status: 404 }); + return { kind: 'ok', detail }; +} + +/** + * 单价合法性:**数字**、> 0、最多 4 位小数、且不超过对方 `numeric(12,4)` 的上限。 + * + * 三条都是踩过的坑: + * · `Number(true) === 1`、`Number([1.5]) === 1.5` ⇒ 只接受 `number` 或**纯数字字符串**; + * · 浮点 `*10000` 判定会把合法值 `12345678.1234` 误判成 5 位小数 ⇒ 用**字符串**小数位判定; + * · 超过 `99999999.9999` 的价对方存不下(回 502,用户看不出为什么)⇒ 入口直接 400。 + */ +export function isValidBidUnitPrice(value: unknown): boolean { + if (typeof value !== 'number' && typeof value !== 'string') return false; + const text = typeof value === 'number' ? String(value) : String(value).trim(); + if (!/^(?:\d+)(?:\.\d{1,4})?$/.test(text)) return false; + const num = Number(text); + if (!Number.isFinite(num) || num <= 0) return false; + return num <= 99_999_999.9999; +} + +/** + * 提交报价(**唯一写主系统的地方**)。 + * + * 顺序:本地校验(快、少发一次注定失败的请求)→ 对方提交 → 成功才用返回视图整轮 upsert。 + * 失败一律**不动本地报价**:宁可让用户再点一次,也不能让他以为报上了。 + */ +export async function submitBidQuotes(input: { + branchCode: string; + roundId: string; + /** 多绑定时用来定位具体那一条邀约(清单每行都带 `supplierCode`) */ + supplierCode?: string | null; + quotes: Array<{ skuCode: string; unitPrice: number; remark?: string | null }>; +}): Promise { + /** + * ⚠️ 这里**不要**先 `Number()`:`Number(true) === 1`、`Number([1.5]) === 1.5` + * ⇒ 布尔/数组会被"洗白"成合法价。先保留原值过 `isValidBidUnitPrice`, + * 通过后再转数字(红队 #3)。 + */ + const quotes = Array.isArray(input.quotes) + ? input.quotes + .map((quote) => ({ + skuCode: String(quote?.skuCode || '').trim(), + rawUnitPrice: quote?.unitPrice as unknown, + remark: quote?.remark === undefined || quote?.remark === null ? null : String(quote.remark), + })) + .filter((quote) => Boolean(quote.skuCode)) + : []; + if (!quotes.length) { + return localFailure({ code: 'quotes_required', status: 400 }); + } + for (const quote of quotes) { + if (!isValidBidUnitPrice(quote.rawUnitPrice)) { + return localFailure({ + code: 'invalid_unit_price', + status: 400, + message: `${quote.skuCode}:${bidErrorCopy('invalid_unit_price')}`, + }); + } + } + const normalizedQuotes = quotes.map((quote) => ({ + skuCode: quote.skuCode, + unitPrice: Number(quote.rawUnitPrice), + remark: quote.remark, + })); + + const resolved = await resolveInvitation({ ...input, syncIfMissing: true }); + if (!resolved.ok) return resolved.failure; + + // 明细未拉过(只有 webhook 头)时先对齐一次:否则无法校验"这个 SKU 在不在本轮" + let detail = await getBidInvitationDetail(input); + if (!detail || !detail.items.length) { + const refreshed = await refreshBidInvitation(input); + if (refreshed.kind !== 'ok') return refreshed; + detail = refreshed.detail; + } + if (detail.deadlinePassed) { + return localFailure({ code: 'quote_deadline_passed', status: 409 }); + } + if (detail.invitation.roundStatus !== 'open' || detail.invitation.localStatus === 'cancelled') { + return localFailure({ code: 'bid_not_open', status: 409 }); + } + const knownSkus = new Set(detail.items.map((item) => item.skuCode)); + const unknown = normalizedQuotes.find((quote) => !knownSkus.has(quote.skuCode)); + if (unknown) { + return localFailure({ + code: 'sku_not_in_round', + status: 400, + message: `${unknown.skuCode}:${bidErrorCopy('sku_not_in_round')}`, + }); + } + + const outcome = await submitMainSupplierBidQuotes({ + supplierCode: resolved.supplierCode, + roundId: input.roundId, + quotes: normalizedQuotes, + }); + if (outcome.kind !== 'ok') { + const failure = fromMainFailure(outcome); + if (outcome.kind === 'rejected' && (failure.code === 'bid_not_open' || failure.code === 'quote_deadline_passed')) { + // 对方说已关闭/已截止:我方台账立刻以对方为准对齐一次(失败不影响返回的错误) + await refreshBidInvitation(input).catch(() => undefined); + } else if ( + outcome.kind === 'rejected' && + (failure.code === 'not_found' || failure.code === 'forbidden') + ) { + /** + * 对方说"这轮不存在 / 无权查看" ⇒ 与刷新路径同口径:**停用该行**(软删留痕)。 + * 若只写 sync_error,这轮会永远挂在「待报价」里点不动,用户会当成系统坏了。 + */ + await markInvitationCancelled({ + branchCode: input.branchCode, + roundId: input.roundId, + supplierCode: resolved.supplierCode, + reason: `${failure.code}: ${failure.message}`, + }); + } else { + await markInvitationSyncError({ + branchCode: input.branchCode, + roundId: input.roundId, + supplierCode: resolved.supplierCode, + reason: `${failure.code}: ${failure.message}`, + }); + } + return failure; + } + + await applyBidDetail({ + branchCode: input.branchCode, + supplierCode: resolved.supplierCode, + roundId: input.roundId, + detail: toDetailInput(outcome.detail), + payload: outcome.detail, + }); + + const after = await getBidInvitationDetail(input); + if (!after) return localFailure({ code: 'bid_invitation_not_found', status: 404 }); + return { kind: 'ok', detail: after }; +} diff --git a/server/tests/mainSystemBidQuote.test.ts b/server/tests/mainSystemBidQuote.test.ts new file mode 100644 index 0000000..97ddc10 --- /dev/null +++ b/server/tests/mainSystemBidQuote.test.ts @@ -0,0 +1,504 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; + +/** + * 主系统竞价「待报价」:**我方只报价、不定标** + * (设计文 docs/design/20261017-主系统竞价待报价与报价提交.md,验收 B1–B9)。 + * + * 这个文件钉住四组东西: + * ① 派生口径 `deriveLocalStatus()` —— 页面 6 种状态的**唯一**算法(顺序错就会把"已中标"显示成"待报价"); + * ② webhook `bid.opened` 的**接收纪律**:要就地 return(不得落进建单兜底)、不写价格、幂等键; + * ③ 提交前的本地校验 + 对方错误码映射(`bid_not_open` / `quote_deadline_passed` / + * `supplier_category_mismatch` / 401 刷新重试一次); + * ④ 失败**不改本地报价**(不能让人"以为报上了")。 + */ + +/* ── mock:DB(脚本化 fake client)──────────────────────────────────────────── */ + +const clientQuery = vi.hoisted(() => vi.fn()); +const poolQuery = vi.hoisted(() => vi.fn()); +const clientRelease = vi.hoisted(() => vi.fn()); +vi.mock('../src/db', () => ({ + pool: { + query: (...args: unknown[]) => poolQuery(...args), + connect: async () => ({ + query: (...args: unknown[]) => clientQuery(...args), + release: () => clientRelease(), + }), + }, + getRawPoolQuery: () => poolQuery, +})); + +const getMainSystemToken = vi.hoisted(() => vi.fn()); +vi.mock('../src/services/mainSystem/token', () => ({ + getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args), +})); + +// 配置齐备(否则 api 层直接返回 not_configured,测不到映射) +vi.mock('../src/services/mainSystem/config', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, isMainSystemIntegrationEnabled: () => true }; +}); + +const fetchMock = vi.hoisted(() => vi.fn()); +vi.stubGlobal('fetch', fetchMock); + +const { + deriveLocalStatus, + findInvitationByRound, + isBidOpenedEvent, + recordBidOpened, + toBidInvitationItemDto, +} = await import('../src/services/mainSystemBidInbox'); + +const { + isValidBidRoundId, + isValidBidUnitPrice, + submitBidQuotes, + BID_ERROR_COPY, + bidErrorCopy, +} = await import('../src/services/mainSystemBidQuotes'); + +const { + listMainSupplierBids, + getMainSupplierBidDetail, + submitMainSupplierBidQuotes, + readBidErrorCode, +} = await import('../src/services/mainSystem/api/bids'); + +/** 造一个 fetch 响应 */ +function jsonResponse(status: number, body: unknown) { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + }; +} + +beforeEach(() => { + clientQuery.mockReset(); + poolQuery.mockReset(); + // 绑定查询默认返回空(= 读不到绑定 ⇒ 不拦),个别用例用 mockResolvedValueOnce 覆盖 + poolQuery.mockResolvedValue({ rows: [] }); + clientRelease.mockReset(); + getMainSystemToken.mockReset(); + fetchMock.mockReset(); + getMainSystemToken.mockResolvedValue({ + kind: 'ok', + token: 'tok-1', + branchCode: 'BR002', + expiresAt: Date.now() + 60_000, + }); +}); + +/* ── ① 派生口径 ───────────────────────────────────────────────────────────── */ + +describe('待报价状态派生(deriveLocalStatus,唯一口径)', () => { + const base = { itemCount: 2, quotedCount: 0, hasAward: false }; + const future = new Date(Date.now() + 3600_000); + const past = new Date(Date.now() - 3600_000); + + it('轮次取消 ⇒ cancelled(比"过期"更权威)', () => { + expect(deriveLocalStatus({ ...base, roundStatus: 'cancelled', respondDeadline: past })).toBe('cancelled'); + }); + + it('轮次已定标 ⇒ 有中标行 won,没有 lost(即使已过截止)', () => { + expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: true, respondDeadline: past })).toBe('won'); + expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: false, respondDeadline: past })).toBe('lost'); + }); + + it('截止已过 或 对方说 expired ⇒ expired', () => { + expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: past })).toBe('expired'); + expect( + deriveLocalStatus({ ...base, roundStatus: 'open', mainInvitationStatus: 'expired', respondDeadline: future }) + ).toBe('expired'); + }); + + it('对方说 quoted 或 本地每行都有价 ⇒ quoted;否则 pending', () => { + expect( + deriveLocalStatus({ ...base, roundStatus: 'open', mainInvitationStatus: 'quoted', respondDeadline: future }) + ).toBe('quoted'); + expect(deriveLocalStatus({ ...base, roundStatus: 'open', quotedCount: 2, respondDeadline: future })).toBe('quoted'); + expect(deriveLocalStatus({ ...base, roundStatus: 'open', quotedCount: 1, respondDeadline: future })).toBe('pending'); + // 明细还没拉到(itemCount=0)且没有对方状态 ⇒ 只能是 pending,不能凭空说"已报价" + expect(deriveLocalStatus({ ...base, roundStatus: 'open', itemCount: 0, respondDeadline: future })).toBe('pending'); + }); + + it('没有截止时间 ⇒ 不判过期(只看轮次/邀约状态)', () => { + expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: null })).toBe('pending'); + }); +}); + +describe('明细 DTO:中标行的判定', () => { + const row = (over: Record) => ({ + id: 'i1', + invitation_id: 'inv1', + branch_code: 'BR002', + round_id: 'r1', + sku_code: 'SKU1', + sku_name: '草鱼', + unit: '斤', + unit_price: null, + remark: null, + quoted_at: null, + award_price: null, + award_qty: null, + award_status: null, + ...over, + }); + + it('轮次已定标且我这行没中标价 ⇒ lost(不是我"还没报")', () => { + expect(toBidInvitationItemDto(row({}) as any, 'awarded').awardStatus).toBe('lost'); + }); + + it('有中标价 ⇒ won;轮次未定标 ⇒ null', () => { + expect(toBidInvitationItemDto(row({ award_price: '12.5', award_status: 'won' }) as any, 'awarded').awardStatus).toBe( + 'won' + ); + expect(toBidInvitationItemDto(row({}) as any, 'open').awardStatus).toBe(null); + }); +}); + +/* ── ② webhook 接收 ───────────────────────────────────────────────────────── */ + +describe('bid.opened:事件识别与落库纪律', () => { + it('只认 bid.opened(别的 bid.* 一律不接)', () => { + expect(isBidOpenedEvent('bid.opened')).toBe(true); + expect(isBidOpenedEvent('bid.closed')).toBe(false); + expect(isBidOpenedEvent(undefined)).toBe(false); + }); + + it('重复推送走 ON CONFLICT(幂等键 branch_code + round_id + supplier_code)', async () => { + clientQuery.mockImplementation(async (sql: string) => { + if (/INSERT INTO public\.main_system_bid_invitations AS i/i.test(sql)) { + return { rows: [{ id: 'inv-1' }] }; + } + if (/SELECT i\.round_status/i.test(sql)) { + return { + rows: [ + { + round_status: 'open', + main_invitation_status: null, + respond_deadline: new Date(Date.now() + 60_000).toISOString(), + item_count: 1, + quoted_count: 0, + has_award: false, + quoted_at: null, + }, + ], + }; + } + return { rows: [] }; + }); + + const outcome = await recordBidOpened({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + payload: { + round_id: 'round-1', + round_code: 'BID001', + respond_deadline: new Date(Date.now() + 60_000).toISOString(), + item_count: 1, + items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }], + }, + }); + + expect(outcome.status).toBe('recorded'); + expect(outcome.roundId).toBe('round-1'); + const headerSql = clientQuery.mock.calls + .map(([sql]: [string]) => sql) + .find((sql: string) => /INSERT INTO public\.main_system_bid_invitations AS i/i.test(sql)); + expect(headerSql).toMatch(/ON CONFLICT \(branch_code, round_id, supplier_code\) DO UPDATE/); + // 已截标/已定标/已取消都是终态,迟到的补投(含 webhook 硬编码的 open)不得改回去 + expect(headerSql).toMatch(/i\.round_status IN \('closed', 'awarded', 'cancelled'\)/); + // 全程要有事务(幂等 + 头/行一致) + const sqls = clientQuery.mock.calls.map(([sql]: [string]) => sql); + expect(sqls[0]).toBe('BEGIN'); + expect(sqls[sqls.length - 1]).toBe('COMMIT'); + expect(clientRelease).toHaveBeenCalled(); + }); + + it('webhook **不写价格**(价格只由拉详情/提交成功后的返回写)', async () => { + clientQuery.mockImplementation(async (sql: string) => { + if (/INSERT INTO public\.main_system_bid_invitations AS i/i.test(sql)) return { rows: [{ id: 'inv-1' }] }; + if (/SELECT i\.round_status/i.test(sql)) { + return { + rows: [ + { + round_status: 'open', + main_invitation_status: null, + respond_deadline: null, + item_count: 1, + quoted_count: 0, + has_award: false, + quoted_at: null, + }, + ], + }; + } + return { rows: [] }; + }); + await recordBidOpened({ + branchCode: 'BR002', + supplierCode: 'SUP1', + payload: { round_id: 'r1', items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤', unit_price: 99 }] }, + }); + const itemInsert = clientQuery.mock.calls + .map(([sql]: [string]) => sql) + .find((sql: string) => /INSERT INTO public\.main_system_bid_invitation_items AS it/i.test(sql)); + expect(itemInsert).toBeTruthy(); + expect(itemInsert).not.toMatch(/unit_price/i); + expect(itemInsert).not.toMatch(/award_/i); + }); + + it('缺 round_id / 缺 supplier_code ⇒ ignored,且不落任何行', async () => { + const missingRound = await recordBidOpened({ + branchCode: 'BR002', + supplierCode: 'SUP1', + payload: { items: [] }, + }); + expect(missingRound.status).toBe('ignored'); + const missingSupplier = await recordBidOpened({ + branchCode: 'BR002', + supplierCode: '', + payload: { round_id: 'r1' }, + }); + expect(missingSupplier.status).toBe('ignored'); + expect(clientQuery).not.toHaveBeenCalled(); + }); + + it('webhook 路由:bid.opened 分支就地 return,**不会**落进建单兜底', () => { + const routes = readFileSync(path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), 'utf8'); + const start = routes.indexOf('if (isBidOpenedEvent(event))'); + expect(start).toBeGreaterThan(-1); + const block = routes.slice(start, routes.indexOf("if (isFulfillmentEvent(event))", start)); + expect(block).toMatch(/recordBidOpened\(/); + expect(block).toMatch(/return res\.json\(/); + // 该分支内不得出现建单/导入调用(`data[]` 兜底在文件更下方) + expect(block).not.toMatch(/importMainSystemGroups/); + // 事件名必须出现在分支判定**之前**的注释之外没有意义 —— 钉住分支位置:在 branchCode 闸门之后 + const gateIdx = routes.indexOf('return res.json({ ok: true, ignored: true, reason: resolved.ok ? \'not_bound\' : resolved.reason });'); + expect(gateIdx).toBeGreaterThan(-1); + expect(start).toBeGreaterThan(gateIdx); + }); +}); + +/* ── ③ 提交前的本地校验 ─────────────────────────────────────────────────────── */ + +describe('报价单价合法性(> 0 且最多 4 位小数)', () => { + it('挡住 0 / 负数 / 非数字 / 5 位小数', () => { + expect(isValidBidUnitPrice(0)).toBe(false); + expect(isValidBidUnitPrice(-1)).toBe(false); + expect(isValidBidUnitPrice('abc')).toBe(false); + expect(isValidBidUnitPrice(1.23456)).toBe(false); + }); + + it('放行 4 位小数与整数', () => { + expect(isValidBidUnitPrice(1.2345)).toBe(true); + expect(isValidBidUnitPrice(12)).toBe(true); + expect(isValidBidUnitPrice('0.0001')).toBe(true); + }); +}); + +describe('submitBidQuotes:本地校验先挡(不打扰主系统)', () => { + it('空报价 ⇒ 400 quotes_required,且一个请求都不发', async () => { + const outcome = await submitBidQuotes({ branchCode: 'BR002', roundId: 'r1', quotes: [] }); + expect(outcome.kind).toBe('rejected'); + expect((outcome as any).code).toBe('quotes_required'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(poolQuery).not.toHaveBeenCalled(); + }); + + it('单价不合法 ⇒ 400 invalid_unit_price(带 SKU 前缀,便于行内提示)', async () => { + const outcome = await submitBidQuotes({ + branchCode: 'BR002', + roundId: 'r1', + quotes: [{ skuCode: 'SKU1', unitPrice: 0 }], + }); + expect((outcome as any).code).toBe('invalid_unit_price'); + expect((outcome as any).message).toContain('SKU1'); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); + +/* ── ④ 对方错误码映射 / 401 重试 ────────────────────────────────────────────── */ + +describe('主系统接口封装:错误码与 401', () => { + it('列表:settings.enabled 与邀约行都映射出来', async () => { + fetchMock.mockResolvedValue( + jsonResponse(200, { + data: [ + { + round_id: 'r1', + round_code: 'BID001', + title: '今日竞价', + order_code: 'ORD1', + round_status: 'open', + status: 'pending', + respond_deadline: '2026-10-17T02:30:00.000Z', + item_count: 2, + }, + ], + settings: { enabled: true }, + }) + ); + const outcome = await listMainSupplierBids('SUP1'); + expect(outcome.kind).toBe('ok'); + if (outcome.kind !== 'ok') return; + expect(outcome.enabled).toBe(true); + expect(outcome.rows[0]).toMatchObject({ + roundId: 'r1', + roundCode: 'BID001', + roundTitle: '今日竞价', + roundStatus: 'open', + invitationStatus: 'pending', + itemCount: 2, + }); + }); + + it('提交:请求体是对方的 snake_case(sku_code / unit_price / remark)', async () => { + fetchMock.mockResolvedValue(jsonResponse(200, { data: { round: { id: 'r1' }, items: [], my_quotes: [], awards: [] } })); + await submitMainSupplierBidQuotes({ + supplierCode: 'SUP1', + roundId: 'r1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5, remark: '现杀' }], + }); + const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; + expect(JSON.parse(String(init.body))).toEqual({ + quotes: [{ sku_code: 'SKU1', unit_price: 12.5, remark: '现杀' }], + }); + }); + + it('401 ⇒ 强制刷新 token 后重试一次(只重试一次)', async () => { + fetchMock + .mockResolvedValueOnce(jsonResponse(401, { error: 'invalid_token' })) + .mockResolvedValueOnce(jsonResponse(200, { data: { round: { id: 'r1' }, items: [], my_quotes: [], awards: [] } })); + const outcome = await submitMainSupplierBidQuotes({ + supplierCode: 'SUP1', + roundId: 'r1', + quotes: [{ skuCode: 'SKU1', unitPrice: 1 }], + }); + expect(outcome.kind).toBe('ok'); + expect(getMainSystemToken).toHaveBeenCalledTimes(2); + expect(getMainSystemToken.mock.calls[1][1]).toEqual({ forceRefresh: true }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('403 判成"语义拒绝"(不是网络故障),错误码透出', async () => { + fetchMock.mockResolvedValue(jsonResponse(403, { error: 'supplier_category_mismatch', error_description: '不在品类' })); + const outcome = await submitMainSupplierBidQuotes({ + supplierCode: 'SUP1', + roundId: 'r1', + quotes: [{ skuCode: 'SKU1', unitPrice: 1 }], + }); + expect(outcome.kind).toBe('rejected'); + expect((outcome as any).code).toBe('supplier_category_mismatch'); + expect(readBidErrorCode({ error: 'bid_not_open' }, 400)).toBe('bid_not_open'); + // 没带 error 时按状态码兜稳定内部码 + expect(readBidErrorCode(null, 404)).toBe('not_found'); + }); +}); + +describe('错误码 → 中文文案(界面唯一映射表)', () => { + it('supplier_category_mismatch 透出对方原文(前端靠里面的 sku 标红那一行)', async () => { + fetchMock.mockResolvedValue( + jsonResponse(403, { + error: 'supplier_category_mismatch', + error_description: '商品 SKU78661366595 不在你的经营品类内,无法报价', + }) + ); + // 走 service 层(需要在本地有台账行)⇒ 这里直接验 api→文案的映射函数组合 + const outcome = await submitMainSupplierBidQuotes({ + supplierCode: 'SUP1', + roundId: 'r1', + quotes: [{ skuCode: 'SKU78661366595', unitPrice: 1 }], + }); + expect(outcome.kind).toBe('rejected'); + expect((outcome as any).code).toBe('supplier_category_mismatch'); + }); + + it('契约里的四个错误码都有专门文案', () => { + for (const code of ['bid_not_open', 'quote_deadline_passed', 'supplier_category_mismatch', 'bid_disabled']) { + expect(BID_ERROR_COPY[code], code).toBeTruthy(); + expect(bidErrorCopy(code)).not.toContain('请稍后重试,请稍后重试'); + } + }); + + it('未知码回落到对方 error_description,再回落通用文案', () => { + expect(bidErrorCopy('unknown_code', '对方说明')).toBe('对方说明'); + expect(bidErrorCopy('unknown_code')).toBe(BID_ERROR_COPY.request_failed); + }); +}); + +describe('红队/复核后的加固(退化载荷、严格单价、多绑定、终态)', () => { + it('对方 200 但载荷不可识别({} / 非 JSON)⇒ 失败、绝不落库', async () => { + // `{}`:既无 round、也无 items/quotes/awards + fetchMock.mockResolvedValueOnce(jsonResponse(200, {})); + const emptyPayload = await submitMainSupplierBidQuotes({ + supplierCode: 'SUP1', + roundId: 'r1', + quotes: [{ skuCode: 'SKU1', unitPrice: 1 }], + }); + expect(emptyPayload.kind).toBe('unavailable'); + expect((emptyPayload as any).code).toBe('invalid_main_system_response'); + + // 非 JSON(对方网关回了 HTML):http 层把 json() 解析失败吞成 null ⇒ 同样必须判失败 + fetchMock.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => { + throw new Error('Unexpected token < in JSON'); + }, + }); + const nonJson = await getMainSupplierBidDetail('SUP1', 'r1'); + expect(nonJson.kind).toBe('unavailable'); + expect((nonJson as any).code).toBe('invalid_main_system_response'); + }); + + it('单价:拒绝布尔/数组/科学计数法/超上限,放行大数 4 位小数', async () => { + expect(isValidBidUnitPrice(true)).toBe(false); + expect(isValidBidUnitPrice([1.5])).toBe(false); + expect(isValidBidUnitPrice('1e-7')).toBe(false); + expect(isValidBidUnitPrice(99_999_999_999)).toBe(false); + expect(isValidBidUnitPrice('12.3456')).toBe(true); + expect(isValidBidUnitPrice(12_345_678.1234)).toBe(true); + }); + + it('多绑定同一轮:给了 supplier 才定位;没给且多行 ⇒ ambiguous(不猜)', async () => { + poolQuery.mockResolvedValueOnce({ + rows: [ + { id: 'a', supplier_code: 'SUP-A' }, + { id: 'b', supplier_code: 'SUP-B' }, + ], + }); + const ambiguous = await findInvitationByRound({ branchCode: 'BR002', roundId: 'r1' }); + expect(ambiguous.kind).toBe('ambiguous'); + expect((ambiguous as any).supplierCodes).toEqual(['SUP-A', 'SUP-B']); + + poolQuery.mockResolvedValueOnce({ rows: [{ id: 'b', supplier_code: 'SUP-B' }] }); + const picked = await findInvitationByRound({ branchCode: 'BR002', roundId: 'r1', supplierCode: 'SUP-B' }); + expect(picked.kind).toBe('found'); + // 精确查询的 SQL 必须按 supplier_code 过滤(大小写不敏感) + const sql = String(poolQuery.mock.calls[poolQuery.mock.calls.length - 1][0]); + expect(sql).toMatch(/upper\(supplier_code\) = upper\(\$3\)/); + }); + + it('轮次 ID 形态校验挡住控制字符/超长(防 500 + 原始 PG 错误回显)', async () => { + expect(isValidBidRoundId('11111111-2222-3333-4444-555555555555')).toBe(true); + expect(isValidBidRoundId('abc%00def')).toBe(false); + expect(isValidBidRoundId('a'.repeat(65))).toBe(false); + expect(isValidBidRoundId('')).toBe(false); + }); + + it('提交前本地校验失败 ⇒ 一个外部请求都不发(含 strict 单价)', async () => { + fetchMock.mockClear(); + const outcome = await submitBidQuotes({ + branchCode: 'BR002', + roundId: 'r1', + quotes: [{ skuCode: 'SKU1', unitPrice: true as unknown as number }], + }); + expect((outcome as any).code).toBe('invalid_unit_price'); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/mainSystemBidQuoteBoundary.test.ts b/server/tests/mainSystemBidQuoteBoundary.test.ts new file mode 100644 index 0000000..14cb1e3 --- /dev/null +++ b/server/tests/mainSystemBidQuoteBoundary.test.ts @@ -0,0 +1,1863 @@ +import express from 'express'; +import request from 'supertest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; + +/** + * 主系统竞价「待报价 + 报价提交」——**独立补边界**(tester 任务,B1–B15 里自测薄弱的面)。 + * + * 与开发者自测 `mainSystemBidQuote.test.ts` 的分工(那个文件**不修改**): + * 自测钉的是"每条主路径存在";本文件钉的是**边界与失败路径的可观测后果**: + * + * · B3 未绑定 / 未知编码推送 ⇒ ignored 且**零落库**;读不到绑定 ⇒ 不拦;大小写规范化; + * · B5 同步:`settings.enabled=false` + `data:[]` ⇒ **一个事务都不开**(不改本地状态); + * `data` 有行 ⇒ **只 upsert 邀约头**(零明细写入)+ 成功后清 `sync_error` + `item_count` 可收缩; + * · B6 整轮对齐:对方删行 ⇒ 本地行被删;对方撤回报价 ⇒ 本地价被清、状态回 pending; + * 对方 awarded 且该 SKU 无中标 ⇒ 读取视图 `lost`;有中标 ⇒ `won`; + * · B7 本地校验:7 种畸形单价 / 空报价 / 过截止 / 轮次 closed / SKU 不在本轮 —— **零外呼**; + * · B8 出站:401 只刷一次 token 且只重试一次、第二次 401 即失败;403 不重试;请求体 snake_case; + * 出站身份取**该邀约行**的 `supplier_code`(多绑定); + * · B9 失败不落价:5xx / 超时 / 2xx 退化载荷(`{}`、非 JSON、缺 data)⇒ 失败、**不动本地报价**、 + * 只写 `sync_error`(并直接钉住"没有调用 applyBidDetail");404 ⇒ 软删 cancelled; + * · B15 多绑定同轮:不带 supplier ⇒ 409 `bid_invitation_ambiguous` 且零外呼;带 supplier ⇒ 精确命中; + * · 派生口径:优先级 cancelled > awarded > expired > quoted > pending、`respond_deadline=null`、 + * 时钟/时区边界; + * · 迁移:两张表、两个幂等键、`IF NOT EXISTS`、6 种 `local_status` 的 CHECK。 + * + * 造数方式(照仓内既有风格): + * · `vi.mock('../src/db')` —— 用一个**内存版两张表**(`createFakeBidDb`)接管 SQL, + * 这样才能断言"落库后的行到底长什么样",而不只是"发过某条 SQL"; + * · `vi.stubGlobal('fetch')` —— 对方接口的每一个响应都可脚本化; + * · token / 配置 / 绑定列表都 mock,保证一个用例里"外呼次数"可数。 + * + * 设计文档:docs/design/20261017-主系统竞价待报价与报价提交.md §8(B1–B15) + */ + +/* ── mock 句柄(vi.hoisted:factory 里可用) ─────────────────────────────────── */ + +const H = vi.hoisted(() => ({ + clientQuery: vi.fn(), + poolQuery: vi.fn(), + clientRelease: vi.fn(), + token: vi.fn(), + fetchMock: vi.fn(), + /** 该分公司生效绑定的 supplier_code 列表(B3/B5/B8 的开关) */ + bindingCodes: vi.fn(), + /** 让绑定查询抛错(B3 的"读不到绑定 ⇒ 不拦") */ + bindingError: { value: null as Error | null }, + /** 包一层 applyBidDetail,既能调用真实现又能断言"没被调用"(B9) */ + applyBidDetail: vi.fn(), + /** 登录上下文(REST 层用) */ + tenantCtx: { value: null as Record | null }, +})); + +vi.mock('../src/db', () => ({ + pool: { + query: (...args: unknown[]) => H.poolQuery(...args), + connect: async () => ({ + query: (...args: unknown[]) => H.clientQuery(...args), + release: () => H.clientRelease(), + }), + }, + getRawPoolQuery: () => H.poolQuery, +})); + +vi.mock('../src/services/mainSystem/token', () => ({ + getMainSystemToken: (...args: unknown[]) => H.token(...args), +})); + +// 配置齐备(否则 api 层直接返回 not_configured,测不到映射) +// 域名也固定成假值:这样本文件不依赖 `.env` 里有没有 MAIN_SYSTEM_BASE_URL(换环境也不会红) +vi.mock('../src/services/mainSystem/config', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, isMainSystemIntegrationEnabled: () => true, mainSystemBaseUrl: () => 'http://main-system.test' }; +}); + +// 绑定列表:B3 校验编码、B5/B8 逐个绑定拉列表都走它 +vi.mock('../src/services/mainSystemBranchApi', () => ({ + listSupplierCodesForBranch: (...args: unknown[]) => { + if (H.bindingError.value) return Promise.reject(H.bindingError.value); + return H.bindingCodes(...args); + }, +})); + +// 保留真实现,只把 applyBidDetail 换成可计数的包装(B9 要证明"失败不落库") +vi.mock('../src/services/mainSystemBidInbox', async (importOriginal) => { + const actual = await importOriginal(); + H.applyBidDetail.mockImplementation(actual.applyBidDetail); + return { ...actual, applyBidDetail: (...args: unknown[]) => H.applyBidDetail(...args) }; +}); + +// REST 层:只要能拿到"已登录 + 有权限 + 某分公司",鉴权本身不属本任务 +vi.mock('../src/middleware/auth', () => ({ + authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => { + req.userId = 'user-1'; + next(); + }, +})); +vi.mock('../src/services/tenantScope', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, loadTenantContext: async () => H.tenantCtx.value }; +}); + +vi.stubGlobal('fetch', H.fetchMock); + +const inbox = await import('../src/services/mainSystemBidInbox'); +const quotes = await import('../src/services/mainSystemBidQuotes'); +const bidApi = await import('../src/services/mainSystem/api/bids'); +const { mountMainSystemBidWorkflowRoutes } = await import('../src/modules/workflow/routes/mainSystemBidRoutes'); + +const { + deriveLocalStatus, + findInvitationByRound, + getBidInvitationDetail, + recordBidOpened, + toBidInvitationItemDto, + applyBidDetail, +} = inbox; + +/* ── 内存版两张表:接管 mainSystemBidInbox 用到的那些 SQL ──────────────────── + * 只实现这两张表 + 只实现本任务涉及的语句;语义按迁移文件里的约束写 + * (ON CONFLICT 幂等键、webhook 只增不减 / 权威刷新可收缩、终态不回退、整轮先清后写)。 + * 这样用例断言的是**落库后的行**,比只断言"发过某条 SQL"强一档。 + */ + +type FakeInvitation = { + 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: string | null; + item_count: number; + round_status: string; + main_invitation_status: string | null; + local_status: string; + quoted_at: string | null; + webhook_received_at: string | null; + last_synced_at: string | null; + sync_error: string | null; + payload: unknown; + created_at: string; + updated_at: string; +}; + +type FakeItem = { + id: string; + invitation_id: string; + branch_code: string; + round_id: string; + sku_code: string; + sku_name: string | null; + unit: string | null; + unit_price: number | null; + remark: string | null; + quoted_at: string | null; + award_price: number | null; + award_qty: number | null; + award_status: 'won' | 'lost' | null; +}; + +type SqlEntry = { channel: 'pool' | 'client'; sql: string; params: unknown[] }; + +function createFakeBidDb() { + const invitations: FakeInvitation[] = []; + const items: FakeItem[] = []; + const log: SqlEntry[] = []; + let seq = 0; + const nowIso = () => new Date().toISOString(); + const clone = (row: T): T => ({ ...row }); + + const findInvitation = (id: string) => invitations.find((row) => row.id === id); + const scope = (sql: string, params: unknown[]) => { + // markInvitationSyncError / markInvitationCancelled 的 supplier 作用域:$4 + const supplier = sql.includes('upper(supplier_code) = upper($4)') ? String(params[3] || '') : ''; + return (row: FakeInvitation) => + row.branch_code === params[0] && + row.round_id === params[1] && + (!supplier || String(row.supplier_code).toUpperCase() === supplier.toUpperCase()); + }; + + function recompute(params: unknown[]) { + const invitation = findInvitation(String(params[0])); + if (!invitation) return { rows: [] as unknown[] }; + const rows = items.filter((item) => item.invitation_id === invitation.id); + const quotedAt = rows + .map((item) => item.quoted_at) + .filter((value): value is string => Boolean(value)) + .sort() + .pop(); + return { + rows: [ + { + round_status: invitation.round_status, + main_invitation_status: invitation.main_invitation_status, + respond_deadline: invitation.respond_deadline, + item_count: invitation.item_count, + quoted_count: rows.filter((item) => item.unit_price !== null).length, + has_award: rows.some((item) => item.award_status === 'won'), + quoted_at: quotedAt ?? null, + }, + ], + }; + } + + function dispatch(channel: 'pool' | 'client', rawSql: string, rawParams?: unknown[]) { + const sql = String(rawSql); + const params = (rawParams || []) as unknown[]; + log.push({ channel, sql, params }); + + if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*$/i.test(sql)) return { rows: [] as unknown[] }; + + /* ── 邀约头 upsert(webhook / 列表 / 详情共用)── */ + if (/INSERT INTO public\.main_system_bid_invitations AS i/.test(sql)) { + const [ + branchCode, + supplierCode, + roundId, + roundCode, + roundTitle, + orderCode, + respondDeadline, + itemCount, + roundStatus, + mainInvitationStatus, + fromWebhook, + fromSync, + payloadJson, + ] = params as [string, string, string, string | null, string | null, string | null, string | null, number, string, string | null, boolean, boolean, string | null]; + const excludedCount = Number(itemCount) || 0; + let row = invitations.find( + (r) => r.branch_code === branchCode && r.round_id === roundId && r.supplier_code === supplierCode + ); + if (!row) { + row = { + id: `inv-${++seq}`, + branch_code: branchCode, + supplier_code: supplierCode, + round_id: roundId, + round_code: roundCode, + round_title: roundTitle, + order_code: orderCode, + respond_deadline: respondDeadline, + item_count: excludedCount, + round_status: roundStatus || 'open', + main_invitation_status: mainInvitationStatus, + local_status: 'pending', + quoted_at: null, + webhook_received_at: fromWebhook === true ? nowIso() : null, + last_synced_at: fromSync === true ? nowIso() : null, + sync_error: null, + payload: payloadJson ? JSON.parse(payloadJson) : null, + created_at: nowIso(), + updated_at: nowIso(), + }; + invitations.push(row); + return { rows: [{ id: row.id }] }; + } + // ON CONFLICT DO UPDATE + row.round_code = roundCode ?? row.round_code; + row.round_title = roundTitle ?? row.round_title; + row.order_code = orderCode ?? row.order_code; + row.respond_deadline = respondDeadline ?? row.respond_deadline; + row.item_count = fromSync === true ? excludedCount : Math.max(Number(row.item_count) || 0, excludedCount); + row.round_status = ['closed', 'awarded', 'cancelled'].includes(String(row.round_status)) + ? row.round_status + : roundStatus || row.round_status; + row.main_invitation_status = mainInvitationStatus ?? row.main_invitation_status; + if (fromWebhook === true) row.webhook_received_at = nowIso(); + if (fromSync === true) { + row.last_synced_at = nowIso(); + row.sync_error = null; + } + if (payloadJson) row.payload = JSON.parse(payloadJson); + row.updated_at = nowIso(); + return { rows: [{ id: row.id }] }; + } + + /* ── 重算 local_status ── */ + if (/SELECT i\.round_status,/.test(sql)) return recompute(params); + if (/SET local_status = \$2, quoted_at = \$3/.test(sql)) { + const row = findInvitation(String(params[0])); + if (row) { + row.local_status = String(params[1]); + row.quoted_at = (params[2] as string | null) ?? null; + row.updated_at = nowIso(); + } + return { rows: [] }; + } + + /* ── 明细:身份 upsert / 删除 / 报价 / 中标 ── */ + if (/INSERT INTO public\.main_system_bid_invitation_items AS it/.test(sql)) { + const [invitationId, branchCode, roundId, skuCode, skuName, unit] = params as [ + string, + string, + string, + string, + string | null, + string | null, + ]; + const existing = items.find((row) => row.invitation_id === invitationId && row.sku_code === skuCode); + if (existing) { + existing.sku_name = skuName ?? existing.sku_name; + existing.unit = unit ?? existing.unit; + return { rows: [] }; + } + items.push({ + id: `item-${++seq}`, + invitation_id: invitationId, + branch_code: branchCode, + round_id: roundId, + sku_code: skuCode, + sku_name: skuName, + unit, + unit_price: null, + remark: null, + quoted_at: null, + award_price: null, + award_qty: null, + award_status: null, + }); + return { rows: [] }; + } + if (/DELETE FROM public\.main_system_bid_invitation_items/.test(sql)) { + const invitationId = String(params[0]); + const keep = new Set((params[1] as string[]) || []); + for (let i = items.length - 1; i >= 0; i -= 1) { + if (items[i].invitation_id === invitationId && !keep.has(items[i].sku_code)) items.splice(i, 1); + } + return { rows: [] }; + } + if (/SET unit_price = NULL, remark = NULL, quoted_at = NULL/.test(sql)) { + const invitationId = String(params[0]); + for (const row of items) { + if (row.invitation_id !== invitationId || row.unit_price === null) continue; + row.unit_price = null; + row.remark = null; + row.quoted_at = null; + } + return { rows: [] }; + } + if (/SET unit_price = \$3, remark = \$4, quoted_at = COALESCE/.test(sql)) { + const [invitationId, skuCode, unitPrice, remark, quotedAt] = params as [string, string, number, string | null, string | null]; + const row = items.find((it) => it.invitation_id === invitationId && it.sku_code === skuCode); + if (row) { + row.unit_price = Number(unitPrice); + row.remark = remark ?? null; + row.quoted_at = quotedAt ?? row.quoted_at; + } + return { rows: [] }; + } + if (/SET award_price = NULL, award_qty = NULL, award_status = NULL/.test(sql)) { + const invitationId = String(params[0]); + for (const row of items) { + if (row.invitation_id !== invitationId) continue; + if (row.award_price === null && row.award_status === null) continue; + row.award_price = null; + row.award_qty = null; + row.award_status = null; + } + return { rows: [] }; + } + if (/SET award_price = \$3, award_status = 'won'/.test(sql)) { + const [invitationId, skuCode, awardPrice] = params as [string, string, number]; + const row = items.find((it) => it.invitation_id === invitationId && it.sku_code === skuCode); + if (row) { + row.award_price = awardPrice === null ? null : Number(awardPrice); + row.award_status = 'won'; + } + return { rows: [] }; + } + + /* ── 读:定位 / 明细 / 列表 / 计数 ── */ + if (/SELECT \* FROM public\.main_system_bid_invitations/.test(sql) && /round_id = \$2/.test(sql)) { + const [branchCode, roundId, supplierCode] = params as [string, string, string?]; + let rows = invitations.filter((row) => row.branch_code === branchCode && row.round_id === roundId); + if (supplierCode) { + rows = rows.filter( + (row) => String(row.supplier_code).toUpperCase() === String(supplierCode).toUpperCase() + ); + return { rows: rows.slice(0, 1).map(clone) }; + } + return { rows: rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at))).map(clone) }; + } + if (/SELECT \* FROM public\.main_system_bid_invitation_items/.test(sql)) { + const invitationId = String(params[0]); + return { + rows: items + .filter((row) => row.invitation_id === invitationId) + .sort((a, b) => String(a.sku_code).localeCompare(String(b.sku_code))) + .map(clone), + }; + } + if (/GROUP BY local_status/.test(sql)) { + const map = new Map(); + for (const row of invitations) { + if (row.branch_code !== params[0]) continue; + map.set(row.local_status, (map.get(row.local_status) || 0) + 1); + } + return { rows: [...map.entries()].map(([local_status, n]) => ({ local_status, n })) }; + } + if (/SELECT \* FROM public\.main_system_bid_invitations/.test(sql)) { + let rows = invitations.filter((row) => row.branch_code === params[0]); + // listInvitationRows 的 status 过滤(`pending` / `history` 两种拼进来的谓词) + if (/AND local_status = 'pending'/.test(sql)) { + rows = rows.filter((row) => row.local_status === 'pending'); + } else if (/AND local_status IN \('quoted', 'expired', 'won', 'lost', 'cancelled'\)/.test(sql)) { + rows = rows.filter((row) => ['quoted', 'expired', 'won', 'lost', 'cancelled'].includes(row.local_status)); + } + return { rows: rows.map(clone) }; + } + + /* ── 写:sync_error / 软删 ── */ + if (/SET round_status = 'cancelled'/.test(sql)) { + for (const row of invitations.filter(scope(sql, params))) { + row.round_status = 'cancelled'; + row.local_status = 'cancelled'; + row.sync_error = (params[2] as string | null) ?? null; + } + return { rows: [] }; + } + if (/SET sync_error = \$3/.test(sql)) { + for (const row of invitations.filter(scope(sql, params))) { + row.sync_error = (params[2] as string | null) ?? null; + } + return { rows: [] }; + } + + throw new Error(`fakeBidDb 不认识的 SQL:\n${sql}`); + } + + return { + invitations, + items, + log, + seedInvitation(over: Partial = {}): FakeInvitation { + const row: FakeInvitation = { + id: `inv-${++seq}`, + branch_code: 'BR002', + supplier_code: 'SUP37831443', + round_id: 'round-1', + round_code: 'BID001', + round_title: '今日竞价', + order_code: 'ORD1', + respond_deadline: new Date(Date.now() + 3600_000).toISOString(), + item_count: 0, + round_status: 'open', + main_invitation_status: null, + local_status: 'pending', + quoted_at: null, + webhook_received_at: null, + last_synced_at: null, + sync_error: null, + payload: null, + created_at: nowIso(), + updated_at: nowIso(), + ...over, + }; + invitations.push(row); + return row; + }, + seedItem(invitation: FakeInvitation, over: Partial = {}): FakeItem { + const row: FakeItem = { + id: `item-${++seq}`, + invitation_id: invitation.id, + branch_code: invitation.branch_code, + round_id: invitation.round_id, + sku_code: 'SKU1', + sku_name: '草鱼', + unit: '斤', + unit_price: null, + remark: null, + quoted_at: null, + award_price: null, + award_qty: null, + award_status: null, + ...over, + }; + items.push(row); + return row; + }, + /** 只看某个方向/某种语句的调用(断言"没发生"用) */ + find(re: RegExp) { + return log.filter((entry) => re.test(entry.sql)); + }, + dispatch, + }; +} + +let db = createFakeBidDb(); + +/* ── 通用小工具 ───────────────────────────────────────────────────────────── */ + +/** 把 service 的失败对象读成断言用的形状(`kind/status/code/message` 只有失败时才存在) */ +function failureOf(outcome: unknown): { kind: string; status: number; code: string; message: string } { + return outcome as { kind: string; status: number; code: string; message: string }; +} + +function jsonResponse(status: number, body: unknown) { + return { ok: status >= 200 && status < 300, status, json: async () => body }; +} + +function nonJsonResponse(status = 200) { + return { + ok: true, + status, + json: async () => { + throw new Error('Unexpected token < in JSON at position 0'); + }, + }; +} + +function abortError() { + return Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }); +} + +const futureIso = () => new Date(Date.now() + 3600_000).toISOString(); +const pastIso = () => new Date(Date.now() - 3600_000).toISOString(); + +/** 对方成功返回的一份"我的视角"详情 */ +function detailPayload(over: Record = {}) { + return { + data: { + round: { + id: 'round-1', + round_code: 'BID001', + title: '今日竞价', + order_code: 'ORD1', + status: 'open', + respond_deadline: futureIso(), + }, + invitation: { status: 'pending', respond_deadline: futureIso() }, + items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }], + my_quotes: [], + awards: [], + ...over, + }, + }; +} + +function buildApp() { + const app = express(); + app.use(express.json()); + const router = express.Router(); + mountMainSystemBidWorkflowRoutes(router); + app.use('/api/workflow', router); + return app; +} + +beforeEach(() => { + db = createFakeBidDb(); + H.clientQuery.mockReset(); + H.poolQuery.mockReset(); + H.clientQuery.mockImplementation(async (sql: string, params?: unknown[]) => db.dispatch('client', sql, params)); + H.poolQuery.mockImplementation(async (sql: string, params?: unknown[]) => db.dispatch('pool', sql, params)); + H.clientRelease.mockReset(); + H.token.mockReset(); + H.token.mockResolvedValue({ kind: 'ok', token: 'tok-1', branchCode: 'BR002', expiresAt: Date.now() + 60_000 }); + H.fetchMock.mockReset(); + H.bindingCodes.mockReset(); + H.bindingCodes.mockResolvedValue(['SUP37831443']); + H.bindingError.value = null; + H.applyBidDetail.mockClear(); + H.tenantCtx.value = { + branchCode: 'BR002', + permissions: ['order_manage'], + roles: ['admin'], + isSuperAdmin: false, + }; +}); + +/* ══ 派生口径(§4 / 验收 B6 的"读取时派生")═════════════════════════════════ */ + +describe('派生口径:优先级与时钟边界(deriveLocalStatus)', () => { + const base = { itemCount: 2, quotedCount: 2, hasAward: false }; + const future = new Date(Date.now() + 3600_000); + const past = new Date(Date.now() - 3600_000); + + it('同一组输入只改一个维度:cancelled > awarded > expired > quoted > pending', () => { + // 每一行都比下一行多满足一条"更权威"的规则 ⇒ 顺序错就会显示成下面那行 + expect(deriveLocalStatus({ ...base, roundStatus: 'cancelled', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('cancelled'); + expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('lost'); + expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: past, mainInvitationStatus: 'quoted' })).toBe('expired'); + expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: future, mainInvitationStatus: 'quoted' })).toBe('quoted'); + expect(deriveLocalStatus({ ...base, quotedCount: 1, roundStatus: 'open', respondDeadline: future })).toBe('pending'); + }); + + it('已定标时"中标"压过"过期":awarded + 过期 + 有中标 ⇒ won', () => { + expect(deriveLocalStatus({ ...base, roundStatus: 'awarded', hasAward: true, respondDeadline: past })).toBe('won'); + }); + + it('respond_deadline 为 null / 不可解析 ⇒ 一律不判过期', () => { + expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: null })).toBe('quoted'); + expect(deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: 'not-a-date' })).toBe('quoted'); + }); + + it('时钟边界:恰好在截止时刻**不算**过期(严格小于),早 1ms 算过期', () => { + const now = new Date('2026-10-17T02:30:00.000Z'); + expect( + deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:30:00.000Z', now }) + ).toBe('quoted'); + expect( + deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:29:59.999Z', now }) + ).toBe('expired'); + expect( + deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T02:30:00.001Z', now }) + ).toBe('quoted'); + }); + + it('时区:+08:00 与等价的 Z 表示必须同结论(不能按字面比字符串)', () => { + const now = new Date('2026-10-17T02:00:00.000Z'); + // 10:00+08:00 == 02:00Z ⇒ 与 now 相等,不过期 + expect( + deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T10:00:00+08:00', now }) + ).toBe('quoted'); + // 09:59+08:00 == 01:59Z ⇒ 已过期 + expect( + deriveLocalStatus({ ...base, roundStatus: 'open', respondDeadline: '2026-10-17T09:59:00+08:00', now }) + ).toBe('expired'); + }); + + it('明细还没拉过(itemCount=0 且无对方状态)⇒ pending,不凭空说"已报价"', () => { + expect(deriveLocalStatus({ roundStatus: 'open', itemCount: 0, quotedCount: 0, hasAward: false })).toBe('pending'); + }); + + it('明细 DTO:轮次 awarded 且无中标价 ⇒ lost;未定标 ⇒ null', () => { + const row = { + id: 'i1', + invitation_id: 'inv1', + branch_code: 'BR002', + round_id: 'round-1', + sku_code: 'SKU1', + sku_name: '草鱼', + unit: '斤', + unit_price: '12.5000', + remark: null, + quoted_at: null, + award_price: null, + award_qty: null, + award_status: null, + }; + expect(toBidInvitationItemDto(row as never, 'awarded').awardStatus).toBe('lost'); + expect(toBidInvitationItemDto(row as never, 'open').awardStatus).toBe(null); + }); +}); + +/* ══ B3:未绑定 / 未知编码 / 读不到绑定 ═════════════════════════════════════ */ + +describe('B3 webhook `bid.opened`:供应商编码不在生效绑定里 ⇒ 只忽略、不落库', () => { + const payload = { + round_id: 'round-1', + round_code: 'BID001', + respond_deadline: futureIso(), + item_count: 1, + items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }], + }; + + it('未知编码 ⇒ ignored/supplier_not_bound,且**一个事务都不开**(无邀约、无明细)', async () => { + H.bindingCodes.mockResolvedValue(['SUP37831443']); + const outcome = await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP99999999', payload }); + expect(outcome.status).toBe('ignored'); + expect(outcome.reason).toBe('supplier_not_bound'); + expect(db.invitations).toHaveLength(0); + expect(db.items).toHaveLength(0); + // 关键:连 BEGIN 都没有 —— 不是"先写后回滚" + expect(db.log).toHaveLength(0); + }); + + it('读不到绑定(空列表)⇒ 不拦(这是环境已知状态,不是本事件的错)', async () => { + H.bindingCodes.mockResolvedValue([]); + const outcome = await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP_ANY_UNKNOWN', payload }); + expect(outcome.status).toBe('recorded'); + expect(db.invitations).toHaveLength(1); + expect(db.invitations[0].supplier_code).toBe('SUP_ANY_UNKNOWN'); + }); + + it('绑定查询抛错 ⇒ 也只记日志、不阻断落库(fail-open,宁可多一行镜像也不丢待办)', async () => { + H.bindingError.value = new Error('bindings table unavailable'); + const outcome = await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP37831443', payload }); + expect(outcome.status).toBe('recorded'); + expect(db.invitations).toHaveLength(1); + }); + + it('大小写不敏感匹配并**规范成绑定里的写法**(否则同一轮会裂成两行)', async () => { + H.bindingCodes.mockResolvedValue(['SUP37831443']); + const outcome = await recordBidOpened({ branchCode: 'BR002', supplierCode: 'sup37831443', payload }); + expect(outcome.status).toBe('recorded'); + expect(db.invitations).toHaveLength(1); + expect(db.invitations[0].supplier_code).toBe('SUP37831443'); + }); + + it('同一轮重复推送(含大小写不同的写法)仍只有 1 行邀约(幂等键落到规范化后的编码)', async () => { + H.bindingCodes.mockResolvedValue(['SUP37831443']); + await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP37831443', payload }); + await recordBidOpened({ branchCode: 'BR002', supplierCode: 'sup37831443', payload }); + expect(db.invitations).toHaveLength(1); + expect(db.items).toHaveLength(1); + }); + + it('webhook 的 item_count 只增不减(退化载荷不能把已知行数改小)', async () => { + H.bindingCodes.mockResolvedValue(['SUP37831443']); + await recordBidOpened({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + payload: { ...payload, item_count: 3, items: [payload.items[0], { sku_code: 'SKU2' }, { sku_code: 'SKU3' }] }, + }); + expect(db.invitations[0].item_count).toBe(3); + // 退化的补投(只剩 1 行) + await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP37831443', payload }); + expect(db.invitations[0].item_count).toBe(3); + }); + + it('终态不可回退:已 awarded 的轮次收到迟到的 `bid.opened` 仍是 awarded(不能变回 open)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', round_status: 'awarded', local_status: 'lost', item_count: 1 }); + db.seedItem(invitation, { sku_code: 'SKU1', unit_price: 12.5 }); + await recordBidOpened({ branchCode: 'BR002', supplierCode: 'SUP37831443', payload }); + expect(invitation.round_status).toBe('awarded'); + expect(invitation.local_status).toBe('lost'); + // 明细身份仍按 (invitation, sku) upsert(补投的新 SKU 要能进来) + expect(db.items).toHaveLength(1); + }); + + it('payload 里同一 SKU 重复出现 ⇒ 只算一行(红队 #7 的去重)', async () => { + H.bindingCodes.mockResolvedValue(['SUP37831443']); + await recordBidOpened({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + payload: { + ...payload, + item_count: 2, + items: [ + { sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }, + { sku_code: 'SKU1', sku_name: '草鱼(重复)', unit: '斤' }, + { sku_code: ' ', sku_name: '空编码行' }, + ], + }, + }); + expect(db.items).toHaveLength(1); + expect(db.items[0].sku_code).toBe('SKU1'); + }); + + it('round_id 形态在**入站侧**就被挡掉(不再落"点不开"的僵尸台账)', async () => { + // 出站/查询侧要求 `[0-9A-Za-z_-]{1,64}`;入站侧若不校验,带控制字符的 round_id 会造出 + // 一行"列表能看到、点开/提交都 400"的台账。2026-10-17 已在 `recordBidOpened` 入口加同一口径校验。 + H.bindingCodes.mockResolvedValue(['SUP37831443']); + const outcome = await recordBidOpened({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + payload: { ...payload, round_id: 'abc%00def' }, + }); + expect(outcome.status).toBe('ignored'); + expect(outcome.reason).toBe('invalid_round_id'); + expect(db.invitations).toHaveLength(0); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); +}); + +/* ══ B4:本地清单(镜像读,不外呼)═════════════════════════════════════════ */ + +describe('B4 清单:status 过滤与 summary 口径', () => { + function seedThree() { + const pending = db.seedInvitation({ round_id: 'round-p', local_status: 'pending', item_count: 1 }); + db.seedItem(pending, { sku_code: 'SKU1' }); + const quoted = db.seedInvitation({ round_id: 'round-q', local_status: 'quoted', item_count: 1 }); + db.seedItem(quoted, { sku_code: 'SKU1', unit_price: 1 }); + const cancelled = db.seedInvitation({ round_id: 'round-c', local_status: 'cancelled', round_status: 'cancelled' }); + return { pending, quoted, cancelled }; + } + + it('status=pending 只回待报价;history 回其余终态/已报', async () => { + seedThree(); + const pendingOnly = await quotes.listBidInvitations({ branchCode: 'BR002', status: 'pending' }); + expect(pendingOnly.rows.map((row) => row.roundId)).toEqual(['round-p']); + + const history = await quotes.listBidInvitations({ branchCode: 'BR002', status: 'history' }); + expect(history.rows.map((row) => row.roundId).sort()).toEqual(['round-c', 'round-q']); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); + + it('summary:closed = won + lost + cancelled(三个终态合并计数)', async () => { + seedThree(); + const all = await quotes.listBidInvitations({ branchCode: 'BR002', status: 'all' }); + expect(all.summary).toMatchObject({ pending: 1, quoted: 1, won: 0, lost: 0, cancelled: 1, closed: 1 }); + }); + + it('其它分公司看不到(清单按 branch_code 过滤)', async () => { + seedThree(); + const other = await quotes.listBidInvitations({ branchCode: 'BR999', status: 'all' }); + expect(other.rows).toEqual([]); + }); +}); + +/* ══ B5:同步(拉列表兜底)══════════════════════════════════════════════════ */ + +describe('B5 同步:settings.enabled=false ⇒ 不动本地;有行 ⇒ 只 upsert 邀约头', () => { + it('enabled=false 且 data:[] ⇒ 返回 0 同步,**一个事务都不开**,本地状态原样', async () => { + const seeded = db.seedInvitation({ round_id: 'round-old', item_count: 2, local_status: 'quoted', sync_error: '上次失败' }); + db.seedItem(seeded, { sku_code: 'SKU1', unit_price: 12.5 }); + H.fetchMock.mockResolvedValue(jsonResponse(200, { data: [], settings: { enabled: false } })); + + const outcome = await quotes.syncBidInvitations('BR002'); + + expect(outcome).toMatchObject({ synced: 0, skipped: 0, unavailable: 0, enabled: false, bound: true }); + expect(db.log).toHaveLength(0); // 没有 BEGIN/INSERT/UPDATE —— 不改任何本地状态 + expect(seeded.local_status).toBe('quoted'); + expect(seeded.sync_error).toBe('上次失败'); + expect(seeded.item_count).toBe(2); + }); + + it('data 有行 ⇒ 只 upsert 邀约头(零明细写入),并写 last_synced_at / 清 sync_error', async () => { + const seeded = db.seedInvitation({ + round_id: 'round-1', + item_count: 5, + main_invitation_status: null, + sync_error: '上次刷新失败', + }); + H.fetchMock.mockResolvedValue( + jsonResponse(200, { + data: [ + { + round_id: 'round-1', + round_code: 'BID001', + title: '今日竞价', + order_code: 'ORD1', + round_status: 'open', + status: 'pending', + respond_deadline: futureIso(), + item_count: 2, + }, + ], + settings: { enabled: true }, + }) + ); + + const outcome = await quotes.syncBidInvitations('BR002'); + + expect(outcome).toMatchObject({ synced: 1, unavailable: 0, enabled: true, bound: true }); + // 只动邀约头:没有明细表的写(`it` 只出现在重算 local_status 的只读子查询里) + expect(db.find(/INSERT INTO public\.main_system_bid_invitation_items|DELETE FROM public\.main_system_bid_invitation_items|UPDATE public\.main_system_bid_invitation_items/)).toHaveLength(0); + const headerInserts = db.find(/INSERT INTO public\.main_system_bid_invitations AS i/); + expect(headerInserts).toHaveLength(1); + expect(String(headerInserts[0].sql)).toMatch(/ON CONFLICT \(branch_code, round_id, supplier_code\) DO UPDATE/); + // fromSync=true($12)⇒ item_count 可收缩、sync_error 清空 + expect(headerInserts[0].params[11]).toBe(true); + expect(headerInserts[0].params[10]).toBe(false); + + expect(seeded.item_count).toBe(2); // 5 → 2:权威刷新允许收缩 + expect(seeded.main_invitation_status).toBe('pending'); + expect(seeded.sync_error).toBe(null); + expect(seeded.last_synced_at).toBeTruthy(); + expect(seeded.local_status).toBe('pending'); + }); + + it('对方 5xx ⇒ unavailable+1、零 DB 写(不拿失败当"同步成功")', async () => { + H.fetchMock.mockResolvedValue(jsonResponse(500, { error: 'boom' })); + const seeded = db.seedInvitation({ round_id: 'round-old', item_count: 2 }); + const outcome = await quotes.syncBidInvitations('BR002'); + expect(outcome).toMatchObject({ synced: 0, unavailable: 1, enabled: false, bound: true }); + expect(db.log).toHaveLength(0); + expect(seeded.item_count).toBe(2); + }); + + it('多绑定:逐个 supplier_code 各拉一次(身份取各绑定自己),合并 upsert', async () => { + H.bindingCodes.mockResolvedValue(['SUP-A', 'SUP-B']); + // 两次请求 URL 相同(对方按 token 区分身份),所以身份只能从 token 侧断言 + H.fetchMock.mockResolvedValue( + jsonResponse(200, { + data: [{ round_id: 'round-x', round_status: 'open', status: 'pending', item_count: 1 }], + settings: { enabled: true }, + }) + ); + + const outcome = await quotes.syncBidInvitations('BR002'); + + expect(H.fetchMock).toHaveBeenCalledTimes(2); + expect(H.token.mock.calls.map((call) => call[0])).toEqual(['SUP-A', 'SUP-B']); + expect(outcome.synced).toBe(2); + const suppliers = db.invitations.map((row) => `${row.supplier_code}/${row.round_id}`).sort(); + expect(suppliers).toEqual(['SUP-A/round-x', 'SUP-B/round-x']); + }); + + it('没有可出站绑定 ⇒ 一个请求都不发(bound=false)', async () => { + H.bindingCodes.mockResolvedValue([]); + const outcome = await quotes.syncBidInvitations('BR002'); + expect(outcome).toMatchObject({ synced: 0, enabled: false, bound: false }); + expect(H.fetchMock).not.toHaveBeenCalled(); + expect(H.token).not.toHaveBeenCalled(); + }); + + it('兜底链路:webhook 没到(本地无行)⇒ 打开某一轮先自动同步、再落台账', async () => { + // 对方 webhook 只重试 2 次 ⇒ 这条"打开时先同步"就是漏推的唯一自愈路径 + H.fetchMock + // 1) resolveInvitation 找不到行 ⇒ refreshBidInvitation → syncIfMissing 拉列表 + .mockResolvedValueOnce( + jsonResponse(200, { + data: [ + { + round_id: 'round-1', + round_code: 'BID001', + title: '今日竞价', + round_status: 'open', + status: 'pending', + respond_deadline: futureIso(), + item_count: 1, + }, + ], + settings: { enabled: true }, + }) + ) + // 2) 定位到之后拉详情 + .mockResolvedValueOnce(jsonResponse(200, detailPayload())); + + const outcome = await quotes.refreshBidInvitation({ branchCode: 'BR002', roundId: 'round-1' }); + + expect(outcome.kind).toBe('ok'); + expect(H.fetchMock).toHaveBeenCalledTimes(2); + expect(db.invitations).toHaveLength(1); + expect(db.invitations[0]).toMatchObject({ round_id: 'round-1', supplier_code: 'SUP37831443' }); + expect(db.items.map((row) => row.sku_code)).toEqual(['SKU1']); + }); +}); + +/* ══ B6:整轮对齐 ═══════════════════════════════════════════════════════════ */ + +describe('B6 整轮对齐:对方删行 / 撤回报价 / 未中标', () => { + async function seedRoundWithTwoItems() { + const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 2 }); + db.seedItem(invitation, { sku_code: 'SKU1', unit_price: 12.5, quoted_at: pastIso() }); + db.seedItem(invitation, { sku_code: 'SKU2', unit_price: 8, quoted_at: pastIso() }); + return invitation; + } + + it('对方删了一行 ⇒ 本地该行被删除,item_count 收缩(不是只加不减)', async () => { + const invitation = await seedRoundWithTwoItems(); + + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', round_code: 'BID001', status: 'open' }, + invitation: { status: 'pending' }, + items: [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }], + myQuotes: [{ sku_code: 'SKU1', unit_price: 12.5 }], + myAwards: [], + }, + }); + + expect(db.items.map((row) => row.sku_code)).toEqual(['SKU1']); + expect(invitation.item_count).toBe(1); + const deletes = db.find(/DELETE FROM public\.main_system_bid_invitation_items/); + expect(deletes).toHaveLength(1); + expect(deletes[0].params[1]).toEqual(['SKU1']); // 只保留对方还给我的那些行 + // 被删的那行报价也随之消失(不能留下"对方已经没有的行 + 我方的价格") + expect(db.items.find((row) => row.sku_code === 'SKU2')).toBeUndefined(); + }); + + it('对方撤回报价 ⇒ 本地价被清空、quoted_at 清空、状态回 pending', async () => { + const invitation = await seedRoundWithTwoItems(); + + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', round_code: 'BID001', status: 'open', respond_deadline: futureIso() }, + invitation: { status: 'pending' }, + items: [ + { sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }, + { sku_code: 'SKU2', sku_name: '鲤鱼', unit: '斤' }, + ], + myQuotes: [], // ← 对方那边我已经没有报价了 + myAwards: [], + }, + }); + + expect(db.items.map((row) => row.unit_price)).toEqual([null, null]); + expect(db.items.every((row) => row.quoted_at === null)).toBe(true); + expect(invitation.local_status).toBe('pending'); + expect(invitation.quoted_at).toBe(null); + // 先清零、且没有为任何行写回价格 + expect(db.find(/SET unit_price = NULL, remark = NULL, quoted_at = NULL/)).toHaveLength(1); + expect(db.find(/SET unit_price = \$3, remark = \$4/)).toHaveLength(0); + }); + + it('对方 withdrawn 我一行 ⇒ 另一行价格保留(清空是按"对方返回"重写,不是全表抹掉)', async () => { + const invitation = await seedRoundWithTwoItems(); + + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', round_code: 'BID001', status: 'open' }, + // 对方邀约状态仍是 pending(不是 quoted)⇒ 本地 2 行只 1 行有价 = 还没报完 + invitation: { status: 'pending' }, + items: [ + { sku_code: 'SKU1' }, + { sku_code: 'SKU2' }, + ], + myQuotes: [{ sku_code: 'SKU2', unit_price: 9.5, updated_at: '2026-10-17T02:10:00.000Z' }], + myAwards: [], + }, + }); + + const bySku = new Map(db.items.map((row) => [row.sku_code, row])); + expect(bySku.get('SKU1')?.unit_price).toBe(null); + expect(bySku.get('SKU2')?.unit_price).toBe(9.5); + expect(bySku.get('SKU2')?.quoted_at).toBe('2026-10-17T02:10:00.000Z'); + expect(invitation.local_status).toBe('pending'); // 只有一行有价 ⇒ 还不算"已报价" + }); + + it('对方说 invitation.status=quoted ⇒ 即便本地只 1 行有价也判 quoted(对方优先)', async () => { + const invitation = await seedRoundWithTwoItems(); + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', status: 'open', respond_deadline: futureIso() }, + invitation: { status: 'quoted' }, + items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }], + myQuotes: [{ sku_code: 'SKU2', unit_price: 9.5 }], + myAwards: [], + }, + }); + expect(invitation.local_status).toBe('quoted'); + expect(invitation.main_invitation_status).toBe('quoted'); + }); + + it('对方 awarded 但该 SKU 无中标 ⇒ 该行 lost(读取时派生),整轮 lost', async () => { + const invitation = await seedRoundWithTwoItems(); + + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', round_code: 'BID001', status: 'awarded' }, + invitation: { status: 'quoted' }, + items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }], + myQuotes: [ + { sku_code: 'SKU1', unit_price: 12.5 }, + { sku_code: 'SKU2', unit_price: 8 }, + ], + myAwards: [], // ← 一个都没中 + }, + }); + + expect(db.items.every((row) => row.award_status === null && row.award_price === null)).toBe(true); + expect(db.find(/SET award_price = \$3, award_status = 'won'/)).toHaveLength(0); + expect(invitation.round_status).toBe('awarded'); + expect(invitation.local_status).toBe('lost'); + + const detail = await getBidInvitationDetail({ branchCode: 'BR002', roundId: 'round-1' }); + expect(detail?.invitation.localStatus).toBe('lost'); + expect(detail?.items.map((item) => item.awardStatus)).toEqual(['lost', 'lost']); + expect(detail?.myAwards).toEqual([]); + }); + + it('对方 awarded 且只有一行中标 ⇒ 那行 won、其余 lost;整轮 won', async () => { + const invitation = await seedRoundWithTwoItems(); + + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', round_code: 'BID001', status: 'awarded' }, + invitation: { status: 'quoted' }, + items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }], + myQuotes: [ + { sku_code: 'SKU1', unit_price: 12.5 }, + { sku_code: 'SKU2', unit_price: 8 }, + ], + myAwards: [{ sku_code: 'SKU1', unit_price: 11 }], + }, + }); + + const bySku = new Map(db.items.map((row) => [row.sku_code, row])); + expect(bySku.get('SKU1')).toMatchObject({ award_status: 'won', award_price: 11 }); + expect(bySku.get('SKU2')).toMatchObject({ award_status: null, award_price: null }); + expect(invitation.local_status).toBe('won'); + + const detail = await getBidInvitationDetail({ branchCode: 'BR002', roundId: 'round-1' }); + expect(detail?.items.map((item) => item.awardStatus).sort()).toEqual(['lost', 'won']); + expect(detail?.myAwards).toEqual([{ skuCode: 'SKU1', unitPrice: 11 }]); + // 中标价只读:不能把我方报价改写成中标价 + expect(bySku.get('SKU1')?.unit_price).toBe(12.5); + }); + + it('对方改判(先 won 后 lost)⇒ 旧的中标价被清掉,不能留假事实', async () => { + const invitation = await seedRoundWithTwoItems(); + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', status: 'awarded' }, + invitation: null, + items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }], + myQuotes: [], + myAwards: [{ sku_code: 'SKU1', unit_price: 11 }], + }, + }); + expect(invitation.local_status).toBe('won'); + + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', status: 'awarded' }, + invitation: null, + items: [{ sku_code: 'SKU1' }, { sku_code: 'SKU2' }], + myQuotes: [], + myAwards: [], + }, + }); + expect(db.items.every((row) => row.award_price === null && row.award_status === null)).toBe(true); + expect(invitation.local_status).toBe('lost'); + }); + + it('对方返回 0 行明细(可识别)⇒ 本地旧行一并删掉,头与明细不会再打架', async () => { + // 能走到 applyBidDetail 说明响应是**可识别**的(`isDegenerateDetail` 已在 api 层挡掉空响应), + // 因此"0 行明细"本身就是事实 ⇒ 必须删(2026-10-17 修 tester F2)。 + const invitation = await seedRoundWithTwoItems(); + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', round_code: 'BID001', status: 'open' }, + invitation: { status: 'pending' }, + items: [], + myQuotes: [], + myAwards: [], + }, + }); + expect(db.find(/DELETE FROM public\.main_system_bid_invitation_items/).length).toBeGreaterThan(0); + expect(db.items).toHaveLength(0); + expect(invitation.item_count).toBe(0); + }); + + it('孤儿保护:被删行的 award/报价不会写到别的 SKU 上(写入都按 (invitation, sku) 定位)', async () => { + const invitation = await seedRoundWithTwoItems(); + await applyBidDetail({ + branchCode: 'BR002', + supplierCode: 'SUP37831443', + roundId: 'round-1', + detail: { + round: { id: 'round-1', status: 'open' }, + invitation: null, + items: [{ sku_code: 'SKU1' }], + myQuotes: [{ sku_code: 'SKU_DELETED', unit_price: 1 }], + myAwards: [{ sku_code: 'SKU_DELETED', unit_price: 2 }], + }, + }); + // SKU_DELETED 不在对方明细里 ⇒ 不该凭空建行,也不该把价格写到 SKU1 + expect(db.items.map((row) => row.sku_code)).toEqual(['SKU1']); + expect(db.items[0].unit_price).toBe(null); + expect(invitation.local_status).toBe('pending'); + }); +}); + +/* ══ B7:提交前的本地校验(零外呼)══════════════════════════════════════════ */ + +describe('B7 本地校验:畸形单价 / 空报价 ⇒ 400 且零外呼', () => { + const badPrices: Array<[string, unknown]> = [ + ['0', 0], + ['-1', -1], + ['1.23456(5 位小数)', 1.23456], + ['true(布尔会被 Number 洗白成 1)', true as unknown as number], + ['[1.5](数组会被洗白成 1.5)', [1.5] as unknown as number], + ["'abc'", 'abc' as unknown as number], + ['9999999999(超对方 numeric(12,4))', 9999999999], + ]; + + for (const [label, value] of badPrices) { + it(`单价 ${label} ⇒ 400 invalid_unit_price,且不发请求、不换 token、不碰库`, async () => { + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: value as number }], + }); + expect(outcome.kind).toBe('rejected'); + expect(failureOf(outcome).status).toBe(400); + expect(failureOf(outcome).code).toBe('invalid_unit_price'); + expect(H.fetchMock).not.toHaveBeenCalled(); + expect(H.token).not.toHaveBeenCalled(); + expect(db.log).toHaveLength(0); + }); + } + + it('quotes: [] ⇒ 400 quotes_required,零外呼零落库', async () => { + const outcome = await quotes.submitBidQuotes({ branchCode: 'BR002', roundId: 'round-1', quotes: [] }); + expect(failureOf(outcome).code).toBe('quotes_required'); + expect(failureOf(outcome).status).toBe(400); + expect(H.fetchMock).not.toHaveBeenCalled(); + expect(db.log).toHaveLength(0); + }); + + it('已过截止 ⇒ 409 quote_deadline_passed(本地时钟先挡,不打扰对方)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', respond_deadline: pastIso(), item_count: 1 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + + expect(failureOf(outcome).code).toBe('quote_deadline_passed'); + expect(failureOf(outcome).status).toBe(409); + expect(H.fetchMock).not.toHaveBeenCalled(); + expect(db.items[0].unit_price).toBe(null); // 一个字都没写 + }); + + it('轮次 closed ⇒ 409 bid_not_open(终态不可再报)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', round_status: 'closed', item_count: 1 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + + expect(failureOf(outcome).code).toBe('bid_not_open'); + expect(failureOf(outcome).status).toBe(409); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); + + it('轮次 draft ⇒ 409 bid_not_open(只有 open 可报)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', round_status: 'draft', item_count: 1 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 1 }], + }); + expect(failureOf(outcome).code).toBe('bid_not_open'); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); + + it('SKU 不在本轮明细 ⇒ 400 sku_not_in_round(不猜、不外呼)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU_NOBODY', unitPrice: 12.5 }], + }); + + expect(failureOf(outcome).code).toBe('sku_not_in_round'); + expect(failureOf(outcome).status).toBe(400); + expect(String(failureOf(outcome).message)).toContain('SKU_NOBODY'); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); + + it('多行里有一行非法 ⇒ 整单 400(不做部分提交)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 2 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + db.seedItem(invitation, { sku_code: 'SKU2' }); + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [ + { skuCode: 'SKU1', unitPrice: 12.5 }, + { skuCode: 'SKU2', unitPrice: -0.01 }, + ], + }); + expect(failureOf(outcome).code).toBe('invalid_unit_price'); + expect(String(failureOf(outcome).message)).toContain('SKU2'); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); + + it('本地没有这轮台账 ⇒ 404 bid_invitation_not_found(先同步也不认识 ⇒ 不猜)', async () => { + H.fetchMock.mockResolvedValue(jsonResponse(200, { data: [], settings: { enabled: true } })); + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-missing', + quotes: [{ skuCode: 'SKU1', unitPrice: 1 }], + }); + expect(failureOf(outcome).code).toBe('bid_invitation_not_found'); + expect(failureOf(outcome).status).toBe(404); + // 只发生了一次"同步"的列表请求,没有提交请求 + expect(H.fetchMock).toHaveBeenCalledTimes(1); + expect(String((H.fetchMock.mock.calls[0] as unknown[])[0])).toContain('/api/supplier/bids'); + }); +}); + +/* ══ B8:出站(401 / 403 / 请求体 / 身份)════════════════════════════════════ */ + +describe('B8 出站:token 与重试纪律', () => { + function seedQuotableRound(over: Record = {}) { + const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1, ...over }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + return invitation; + } + + it('401(刷新后仍 401)⇒ 失败,且恰好 2 次请求 / 2 次换 token(第二次 forceRefresh)', async () => { + seedQuotableRound(); + H.fetchMock + .mockResolvedValueOnce(jsonResponse(401, { error: 'unauthorized' })) + .mockResolvedValueOnce(jsonResponse(401, { error: 'unauthorized' })); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + + expect(outcome.kind).toBe('unavailable'); + expect(failureOf(outcome).status).toBe(502); + expect(H.fetchMock).toHaveBeenCalledTimes(2); // 没有第三次 + expect(H.token).toHaveBeenCalledTimes(2); + expect(H.token.mock.calls[1][1]).toEqual({ forceRefresh: true }); + }); + + it('401 后刷新成功 ⇒ 重试一次即成功,本地报价落库', async () => { + const invitation = seedQuotableRound(); + H.fetchMock + .mockResolvedValueOnce(jsonResponse(401, { error: 'unauthorized' })) + .mockResolvedValueOnce( + jsonResponse( + 200, + detailPayload({ + my_quotes: [{ sku_code: 'SKU1', unit_price: 12.5, updated_at: pastIso() }], + invitation: { status: 'quoted' }, + }) + ) + ); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + + expect(outcome.kind).toBe('ok'); + expect(H.fetchMock).toHaveBeenCalledTimes(2); + expect(db.items[0].unit_price).toBe(12.5); + expect(invitation.local_status).toBe('quoted'); + }); + + it('403 是语义拒绝(不刷新 token、不重试)', async () => { + seedQuotableRound(); + H.fetchMock.mockResolvedValueOnce( + jsonResponse(403, { error: 'supplier_category_mismatch', error_description: '商品 SKU1 不在你的经营品类内,无法报价' }) + ); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + + expect(outcome.kind).toBe('rejected'); + expect(failureOf(outcome).status).toBe(403); + expect(failureOf(outcome).code).toBe('supplier_category_mismatch'); + expect(H.fetchMock).toHaveBeenCalledTimes(1); + expect(H.token).toHaveBeenCalledTimes(1); + }); + + it('请求体是对方的 snake_case,URL 是 {bids}/:round/quotes,身份取**该邀约行**的编码', async () => { + const invitation = db.seedInvitation({ round_id: 'round-9', supplier_code: 'SUP-B', item_count: 2 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + db.seedItem(invitation, { sku_code: 'SKU2' }); + H.fetchMock.mockResolvedValueOnce( + jsonResponse( + 200, + detailPayload({ + my_quotes: [ + { sku_code: 'SKU1', unit_price: 12.34 }, + { sku_code: 'SKU2', unit_price: 5, remark: null }, + ], + }) + ) + ); + + await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-9', + supplierCode: 'SUP-B', + quotes: [ + { skuCode: 'SKU1', unitPrice: 12.34, remark: '现杀' }, + { skuCode: 'SKU2', unitPrice: 5 }, + ], + }); + + const [url, init] = H.fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('http://main-system.test/api/supplier/bids/round-9/quotes'); + expect((init.headers as Record).Authorization).toBe('Bearer tok-1'); + expect(init.method).toBe('POST'); + expect(JSON.parse(String(init.body))).toEqual({ + quotes: [ + { sku_code: 'SKU1', unit_price: 12.34, remark: '现杀' }, + { sku_code: 'SKU2', unit_price: 5, remark: null }, + ], + }); + // 换 token 用的是该邀约的 supplier_code(不是分公司编码) + expect(H.token.mock.calls[0][0]).toBe('SUP-B'); + }); + + it('列表也按邀约行的编码出站(GET /api/supplier/bids,无子路径)', async () => { + H.fetchMock.mockResolvedValue(jsonResponse(200, { data: [], settings: { enabled: true } })); + const outcome = await bidApi.listMainSupplierBids('SUP37831443'); + expect(outcome.kind).toBe('ok'); + const [url, init] = H.fetchMock.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('http://main-system.test/api/supplier/bids'); + expect(init.method).toBe('GET'); + }); + + it('404 ⇒ 详情接口软删该行(round_status/local_status=cancelled)并留 sync_error', async () => { + const invitation = seedQuotableRound(); + H.fetchMock.mockResolvedValueOnce(jsonResponse(404, { error: 'not_found' })); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + + expect(outcome.kind).toBe('rejected'); + expect(failureOf(outcome).code).toBe('not_found'); + expect(invitation.round_status).toBe('cancelled'); + expect(invitation.local_status).toBe('cancelled'); + expect(String(invitation.sync_error)).toContain('not_found'); + expect(db.items[0].unit_price).toBe(null); + }); + + it('对方 403 forbidden(未受邀/编码未绑定)⇒ 软删该行 cancelled(不是只写 sync_error)', async () => { + const invitation = seedQuotableRound(); + H.fetchMock.mockResolvedValueOnce(jsonResponse(403, { error: 'forbidden' })); + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + expect(failureOf(outcome).code).toBe('forbidden'); + expect(failureOf(outcome).status).toBe(403); + expect(invitation.round_status).toBe('cancelled'); + expect(invitation.local_status).toBe('cancelled'); + expect(H.fetchMock).toHaveBeenCalledTimes(1); // 403 不重试 + }); + + it('对接未配置 ⇒ 503 main_system_not_configured(不是 502:这是配置问题,重试无用)', async () => { + seedQuotableRound(); + H.token.mockResolvedValue({ kind: 'not_configured', reason: '缺 client_secret' }); + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + expect(outcome.kind).toBe('not_configured'); + expect(failureOf(outcome).status).toBe(503); + expect(failureOf(outcome).code).toBe('main_system_not_configured'); + expect(H.fetchMock).not.toHaveBeenCalled(); + expect(db.items[0].unit_price).toBe(null); + }); + + it('换 token 失败(暂态)⇒ 502,且不发业务请求', async () => { + seedQuotableRound(); + H.token.mockResolvedValue({ kind: 'unavailable', reason: '对方 oauth 503' }); + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 12.5 }], + }); + expect(failureOf(outcome).status).toBe(502); + expect(failureOf(outcome).code).toBe('main_system_unavailable'); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); +}); + +/* ══ B9:失败不落价 ═════════════════════════════════════════════════════════ */ + +describe('B9 失败不落价:5xx / 超时 / 退化 2xx ⇒ 不动本地报价,只写 sync_error', () => { + function seedQuotedRound() { + const invitation = db.seedInvitation({ + round_id: 'round-1', + item_count: 1, + local_status: 'quoted', + quoted_at: pastIso(), + }); + db.seedItem(invitation, { sku_code: 'SKU1', unit_price: 12.5, quoted_at: pastIso(), remark: '原价' }); + return invitation; + } + + /** 每种失败都把 fetch 脚本化成"一次性响应/异常" */ + const cases: Array<[string, () => void]> = [ + ['对方 500', () => H.fetchMock.mockResolvedValueOnce(jsonResponse(500, { error: 'internal_error' }))], + ['对方 503', () => H.fetchMock.mockResolvedValueOnce(jsonResponse(503, { error: 'maintenance' }))], + ['网络错误', () => H.fetchMock.mockRejectedValueOnce(new Error('ECONNREFUSED 127.0.0.1:3001'))], + ['超时(AbortError)', () => H.fetchMock.mockRejectedValueOnce(abortError())], + ['2xx 但载荷是 `{}`', () => H.fetchMock.mockResolvedValueOnce(jsonResponse(200, {}))], + ['2xx 但 data 为 null', () => H.fetchMock.mockResolvedValueOnce(jsonResponse(200, { data: null }))], + ['2xx 但非 JSON(网关 HTML)', () => H.fetchMock.mockResolvedValueOnce(nonJsonResponse(200))], + ]; + + for (const [label, arrange] of cases) { + it(`${label} ⇒ 502 失败、applyBidDetail 未被调用、本地报价原样、只写 sync_error`, async () => { + const invitation = seedQuotedRound(); + arrange(); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 99.9999 }], + }); + + expect(outcome.kind).toBe('unavailable'); + expect(failureOf(outcome).status).toBe(502); + expect(H.applyBidDetail).not.toHaveBeenCalled(); + // 本地报价一个字都没变(含 quoted_at / remark / 状态) + expect(db.items[0]).toMatchObject({ unit_price: 12.5, remark: '原价' }); + expect(invitation.local_status).toBe('quoted'); + expect(db.find(/INSERT INTO public\.main_system_bid_invitation_items AS it/)).toHaveLength(0); + expect(db.find(/SET unit_price = \$3, remark = \$4/)).toHaveLength(0); + // 失败原因可追 + expect(String(invitation.sync_error)).toContain(':'); + expect(db.find(/SET sync_error = \$3/)).toHaveLength(1); + }); + } + + it('退化 2xx 的对外错误码在 service 层被收成 main_system_unavailable(见报告:契约写的 invalid_main_system_response 丢了)', async () => { + seedQuotedRound(); + H.fetchMock.mockReset(); + H.fetchMock.mockResolvedValueOnce(jsonResponse(200, {})); + + // api 层仍保留精确码 + const apiOutcome = await bidApi.getMainSupplierBidDetail('SUP37831443', 'round-1'); + expect(apiOutcome.kind).toBe('unavailable'); + expect(failureOf(apiOutcome).code).toBe('invalid_main_system_response'); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 99 }], + }); + expect(failureOf(outcome).code).toBe('main_system_unavailable'); + expect(failureOf(outcome).kind).toBe('unavailable'); + }); + + it('对方 400 bid_not_open ⇒ 状态码照对方(400)+ 码透出,并立刻按对方对齐一次', async () => { + seedQuotedRound(); + H.fetchMock.mockReset(); + H.fetchMock + .mockResolvedValueOnce(jsonResponse(400, { error: 'bid_not_open', error_description: '本轮已结束报价' })) + // 随后 refreshBidInvitation 的 GET(对方说已关闭) + .mockResolvedValueOnce( + jsonResponse( + 200, + detailPayload({ round: { id: 'round-1', status: 'closed', respond_deadline: pastIso() } }) + ) + ); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 99 }], + }); + + expect(failureOf(outcome).code).toBe('bid_not_open'); + expect(failureOf(outcome).status).toBe(400); + expect(H.fetchMock).toHaveBeenCalledTimes(2); // POST + 自动刷新 GET + expect(String((H.fetchMock.mock.calls[1] as unknown[])[0])).toContain('/api/supplier/bids/round-1'); + // 提交的 99 从未落库;本地价按对方返回重写(对方说这轮已关闭、我这边没有报价) + expect(db.items[0].unit_price).not.toBe(99); + expect(db.items[0].unit_price).toBe(null); + expect(db.invitations[0].round_status).toBe('closed'); + }); + + it('对方 409 quote_deadline_passed ⇒ 409 + 码透出', async () => { + seedQuotedRound(); + H.fetchMock.mockReset(); + H.fetchMock + .mockResolvedValueOnce(jsonResponse(409, { error: 'quote_deadline_passed' })) + .mockResolvedValueOnce(jsonResponse(200, detailPayload())); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 99 }], + }); + expect(failureOf(outcome).code).toBe('quote_deadline_passed'); + expect(failureOf(outcome).status).toBe(409); + }); + + it('成功提交后用**对方返回**的视图落库(不是拿我发的入参当事实)', async () => { + const invitation = seedQuotedRound(); + H.fetchMock.mockReset(); + H.fetchMock.mockResolvedValueOnce( + jsonResponse( + 200, + detailPayload({ + invitation: { status: 'quoted' }, + my_quotes: [{ sku_code: 'SKU1', unit_price: 13.75, updated_at: pastIso() }], + }) + ) + ); + + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 13.75 }], + }); + + expect(outcome.kind).toBe('ok'); + expect(db.items[0].unit_price).toBe(13.75); + expect(invitation.local_status).toBe('quoted'); + expect(H.applyBidDetail).toHaveBeenCalledTimes(1); + }); +}); + +/* ══ B15:多绑定同一轮 ═════════════════════════════════════════════════════ */ + +describe('B15 多绑定:同一 (branch, round) 两行邀约', () => { + function seedTwoBindings() { + const a = db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-A', item_count: 1 }); + db.seedItem(a, { sku_code: 'SKU1' }); + const b = db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-B', item_count: 1 }); + db.seedItem(b, { sku_code: 'SKU1' }); + return { a, b }; + } + + it('findInvitationByRound:不带 supplier 且两行 ⇒ ambiguous(列出候选,不猜)', async () => { + seedTwoBindings(); + const outcome = await findInvitationByRound({ branchCode: 'BR002', roundId: 'round-1' }); + expect(outcome.kind).toBe('ambiguous'); + expect((outcome as unknown as { supplierCodes: string[] }).supplierCodes.sort()).toEqual(['SUP-A', 'SUP-B']); + }); + + it('findInvitationByRound:带 supplier(大小写不同也认)⇒ 精确命中', async () => { + const { b } = seedTwoBindings(); + const outcome = await findInvitationByRound({ + branchCode: 'BR002', + roundId: 'round-1', + supplierCode: 'sup-b', + }); + expect(outcome.kind).toBe('found'); + expect((outcome as unknown as { row: { id: string } }).row.id).toBe(b.id); + }); + + it('刷新不带 supplier ⇒ 409 bid_invitation_ambiguous,零外呼(绝不替用户选一家)', async () => { + seedTwoBindings(); + const outcome = await quotes.refreshBidInvitation({ branchCode: 'BR002', roundId: 'round-1' }); + expect(failureOf(outcome).code).toBe('bid_invitation_ambiguous'); + expect(failureOf(outcome).status).toBe(409); + expect(H.fetchMock).not.toHaveBeenCalled(); + expect(H.token).not.toHaveBeenCalled(); + }); + + it('提交不带 supplier ⇒ 409 bid_invitation_ambiguous,零外呼', async () => { + seedTwoBindings(); + const outcome = await quotes.submitBidQuotes({ + branchCode: 'BR002', + roundId: 'round-1', + quotes: [{ skuCode: 'SKU1', unitPrice: 1 }], + }); + expect(failureOf(outcome).code).toBe('bid_invitation_ambiguous'); + expect(failureOf(outcome).status).toBe(409); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); + + it('带 supplier ⇒ 只用那一行的编码换 token(不会以另一家身份报价)', async () => { + const { b } = seedTwoBindings(); + H.fetchMock.mockResolvedValueOnce(jsonResponse(200, detailPayload({ invitation: { status: 'quoted' } }))); + const outcome = await quotes.refreshBidInvitation({ + branchCode: 'BR002', + roundId: 'round-1', + supplierCode: 'SUP-B', + }); + expect(outcome.kind).toBe('ok'); + expect(H.token.mock.calls[0][0]).toBe('SUP-B'); + // 只有 SUP-B 那行被刷新,SUP-A 的 last_synced_at 不动 + expect(b.last_synced_at).toBeTruthy(); + expect(db.invitations.find((row) => row.supplier_code === 'SUP-A')?.last_synced_at).toBe(null); + }); + + it('跨分公司隔离:别的分公司看不到这轮(定位永远带 branch_code,不只按 round_id)', async () => { + seedTwoBindings(); + // 同步兜底也只会拉本分公司的绑定(这里显式返回空,避免"靠同步补出来"的假通过) + H.bindingCodes.mockResolvedValue([]); + const detail = await getBidInvitationDetail({ branchCode: 'BR999', roundId: 'round-1' }); + expect(detail).toBe(null); + + const refresh = await quotes.refreshBidInvitation({ branchCode: 'BR999', roundId: 'round-1' }); + expect(failureOf(refresh).code).toBe('bid_invitation_not_found'); + expect(failureOf(refresh).status).toBe(404); + expect(H.fetchMock).not.toHaveBeenCalled(); + // 本分公司的两行没被动过 + expect(db.invitations.every((row) => row.local_status === 'pending')).toBe(true); + }); +}); + +/* ══ REST 层:HTTP 状态码与错误体形状(B7/B8/B15 的出口)════════════════════ */ + +describe('REST 层:4 个接口的状态码 / 错误体(sendBidFailure)', () => { + const url = (roundId: string) => `/api/workflow/main-system/bid-invitations/${roundId}`; + + it('POST quotes 空 ⇒ 400 { error, error_description, error_kind }', async () => { + const res = await request(buildApp()).post(`${url('round-1')}/quotes`).send({ quotes: [] }); + expect(res.status).toBe(400); + expect(res.body).toMatchObject({ error: 'quotes_required', error_kind: 'rejected' }); + expect(typeof res.body.error_description).toBe('string'); + expect(H.fetchMock).not.toHaveBeenCalled(); + }); + + it('POST quotes 单价非法 ⇒ 400 invalid_unit_price', async () => { + const res = await request(buildApp()) + .post(`${url('round-1')}/quotes`) + .send({ quotes: [{ skuCode: 'SKU1', unitPrice: 0 }] }); + expect(res.status).toBe(400); + expect(res.body.error).toBe('invalid_unit_price'); + }); + + it('POST quotes 过截止 ⇒ 409 quote_deadline_passed', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', respond_deadline: pastIso(), item_count: 1 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + const res = await request(buildApp()) + .post(`${url('round-1')}/quotes`) + .send({ quotes: [{ skuCode: 'SKU1', unitPrice: 1 }] }); + expect(res.status).toBe(409); + expect(res.body).toMatchObject({ error: 'quote_deadline_passed', error_kind: 'rejected' }); + }); + + it('POST quotes 对方不可用 ⇒ 502 main_system_unavailable(error_kind=unavailable)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + H.fetchMock.mockResolvedValueOnce(jsonResponse(500, { error: 'boom' })); + const res = await request(buildApp()) + .post(`${url('round-1')}/quotes`) + .send({ quotes: [{ skuCode: 'SKU1', unitPrice: 1 }] }); + expect(res.status).toBe(502); + expect(res.body).toMatchObject({ error: 'main_system_unavailable', error_kind: 'unavailable' }); + }); + + it('POST quotes 多绑定不带 supplierCode ⇒ 409 bid_invitation_ambiguous', async () => { + db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-A', item_count: 1 }); + db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-B', item_count: 1 }); + const res = await request(buildApp()) + .post(`${url('round-1')}/quotes`) + .send({ quotes: [{ skuCode: 'SKU1', unitPrice: 1 }] }); + expect(res.status).toBe(409); + expect(res.body.error).toBe('bid_invitation_ambiguous'); + }); + + it('POST quotes 也接受 snake_case body(sku_code / unit_price / supplierCode)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1 }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + H.fetchMock.mockResolvedValueOnce( + jsonResponse(200, detailPayload({ invitation: { status: 'quoted' }, my_quotes: [{ sku_code: 'SKU1', unit_price: 3 }] })) + ); + const res = await request(buildApp()) + .post(`${url('round-1')}/quotes`) + .send({ quotes: [{ sku_code: 'SKU1', unit_price: 3 }] }); + expect(res.status).toBe(200); + expect(res.body.error).toBe(null); + expect(res.body.data.items[0].unitPrice).toBe(3); + const body = JSON.parse(String((H.fetchMock.mock.calls[0] as [string, RequestInit])[1].body)); + expect(body.quotes).toEqual([{ sku_code: 'SKU1', unit_price: 3, remark: null }]); + }); + + it('GET 清单无分公司上下文 ⇒ 400 branch_required(与 /main-system/preparations 同口径)', async () => { + H.tenantCtx.value = { branchCode: '', permissions: ['order_manage'], roles: ['admin'], isSuperAdmin: false }; + const res = await request(buildApp()).get('/api/workflow/main-system/bid-invitations'); + expect(res.status).toBe(400); + expect(res.body).toMatchObject({ error: 'branch_required', error_kind: 'rejected' }); + }); + + it('GET :roundId 带 ?supplier= 时按该编码出站(多绑定精确命中)', async () => { + db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-A', item_count: 1 }); + db.seedInvitation({ round_id: 'round-1', supplier_code: 'SUP-B', item_count: 1 }); + H.fetchMock.mockResolvedValueOnce(jsonResponse(200, detailPayload())); + const res = await request(buildApp()).get(`${url('round-1')}?supplier=SUP-B`); + expect(res.status).toBe(200); + expect(H.token.mock.calls[0][0]).toBe('SUP-B'); + }); + + it('GET 清单只读本地镜像(不外呼、不换 token)', async () => { + const invitation = db.seedInvitation({ round_id: 'round-1', item_count: 1, local_status: 'pending' }); + db.seedItem(invitation, { sku_code: 'SKU1' }); + const res = await request(buildApp()).get('/api/workflow/main-system/bid-invitations?status=pending'); + expect(res.status).toBe(200); + expect(Array.isArray(res.body.data)).toBe(true); + expect(res.body.data).toHaveLength(1); + expect(res.body.summary).toMatchObject({ pending: 1 }); + expect(H.fetchMock).not.toHaveBeenCalled(); + expect(H.token).not.toHaveBeenCalled(); + }); +}); + +/* ══ 迁移文件(§4,验收 B2/B15 的库侧约束)══════════════════════════════════ */ + +describe('迁移 20261055:两张表 / 两个幂等键 / IF NOT EXISTS / CHECK 覆盖', () => { + const sql = readFileSync( + path.join(__dirname, '../../migrations/20261055_main_system_bid_invitations.sql'), + 'utf8' + ); + + it('两张表都建在 public,且都用 IF NOT EXISTS(可重跑迁移)', () => { + expect(sql).toMatch(/CREATE TABLE IF NOT EXISTS public\.main_system_bid_invitations \(/); + expect(sql).toMatch(/CREATE TABLE IF NOT EXISTS public\.main_system_bid_invitation_items \(/); + }); + + it('邀约幂等键 = (branch_code, round_id, supplier_code) 的 UNIQUE INDEX', () => { + expect(sql).toMatch( + /CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_bid_invitations_branch_round_supplier\s+ON public\.main_system_bid_invitations \(branch_code, round_id, supplier_code\)/ + ); + }); + + it('明细幂等键 = (invitation_id, sku_code) 的 UNIQUE INDEX,且外键 ON DELETE CASCADE', () => { + expect(sql).toMatch( + /CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_bid_invitation_items_invitation_sku\s+ON public\.main_system_bid_invitation_items \(invitation_id, sku_code\)/ + ); + expect(sql).toMatch(/REFERENCES public\.main_system_bid_invitations\(id\) ON DELETE CASCADE/); + }); + + it('local_status CHECK 覆盖 6 种状态(少一种会在写库时炸)', () => { + const block = sql.slice( + sql.indexOf('main_system_bid_invitations_local_status_check'), + sql.indexOf(');', sql.indexOf('main_system_bid_invitations_local_status_check')) + ); + for (const status of ['pending', 'quoted', 'expired', 'won', 'lost', 'cancelled']) { + expect(block, status).toContain(`'${status}'`); + } + }); + + it('round_status CHECK 覆盖对方 5 种轮次状态;award_status 只允许 won/lost', () => { + for (const status of ['draft', 'open', 'closed', 'awarded', 'cancelled']) { + expect(sql, status).toContain(`'${status}'`); + } + expect(sql).toMatch(/CHECK \(award_status IS NULL OR award_status IN \('won', 'lost'\)\)/); + }); + + it('单价精度:numeric(14,4);`award_qty` numeric(14,3) 且默认无值(对方无数量列);单价 > 0 CHECK', () => { + expect(sql).toMatch(/unit_price numeric\(14,4\)/); + expect(sql).toMatch(/award_qty numeric\(14,3\)/); + expect(sql).toMatch(/CHECK \(unit_price IS NULL OR unit_price > 0\)/); + // 这两张是跨系统镜像台账 ⇒ 不放租户 schema(public) + expect(sql).not.toMatch(/CREATE TABLE[^;]*tenant_/i); + }); + + it('索引都带 IF NOT EXISTS(重跑不报 duplicate index);分支/状态索引与 round 定位索引存在', () => { + const indexLines = sql.split('\n').filter((line) => /^CREATE (UNIQUE )?INDEX/.test(line.trim())); + expect(indexLines.length).toBeGreaterThanOrEqual(4); + for (const line of indexLines) expect(line).toContain('IF NOT EXISTS'); + expect(sql).toContain('idx_main_system_bid_invitations_branch_status'); + expect(sql).toContain('idx_main_system_bid_invitations_round'); + expect(sql).toContain('idx_main_system_bid_invitation_items_invitation'); + }); + + it('迁移会被 runner 收录(migrations/*.sql 全部按名字执行)', () => { + const runner = readFileSync(path.join(__dirname, '../src/migrate.ts'), 'utf8'); + expect(runner).toMatch(/endsWith\('\.sql'\)/); + expect(path.basename('20261055_main_system_bid_invitations.sql')).toMatch(/^\d{8}_.+\.sql$/); + }); +}); diff --git a/server/tests/mainSystemBidQuoteDb.integration.test.ts b/server/tests/mainSystemBidQuoteDb.integration.test.ts new file mode 100644 index 0000000..b57e078 --- /dev/null +++ b/server/tests/mainSystemBidQuoteDb.integration.test.ts @@ -0,0 +1,414 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +/** + * 竞价台账**真库**验证(默认跳过;`BID_DB_TEST=1` 才跑)。 + * + * 为什么需要这一份:`mainSystemBidQuoteBoundary.test.ts` 用一个内存版两张表接管 SQL —— 那是 + * **我写的第二份 SQL 语义**,可能骗过自己。这一份连真 Postgres(本地 `supplier_delivery`), + * 只验证**不依赖对方系统**的那一半: + * + * · 幂等键 `(branch_code, round_id, supplier_code)` 真的会被 ON CONFLICT 命中; + * · `applyBidDetail` 的"先清空再按对方返回重写"在真库里确实删行 / 清价; + * · `awarded` 且无中标时 `local_status` 真的是 `lost`(不是读到 `pending`); + * · 迁移里的 CHECK / 唯一索引**确实已生效**(不是只写在文件里)。 + * + * 纪律:只碰 `public.main_system_bid_*`,且只碰 `branch_code` 以 `BR_TESTBID` 开头的临时行, + * 跑完级联删除干净(`ON DELETE CASCADE` 会带走明细)。 + * + * 跑法(本地): + * cd server && BID_DB_TEST=1 npx vitest run tests/mainSystemBidQuoteDb.integration.test.ts + */ + +const RUN = process.env.BID_DB_TEST === '1'; +const TEST_BRANCH = `BR_TESTBID_${Date.now()}`; +const SUPPLIER_A = 'SUP_TESTBID_A'; +const SUPPLIER_B = 'SUP_TESTBID_B'; + +// 默认(未设 BID_DB_TEST)连 src/db 都不加载,保证常规套件不受影响 +const real = RUN + ? { + db: await import('../src/db'), + inbox: await import('../src/services/mainSystemBidInbox'), + quotes: await import('../src/services/mainSystemBidQuotes'), + } + : null; + +const pool = () => real!.db.pool; + +async function cleanup() { + await pool().query(`DELETE FROM public.main_system_bid_invitations WHERE branch_code = $1 OR branch_code LIKE 'BR_TESTBID%'`, [ + TEST_BRANCH, + ]); +} + +describe.skipIf(!RUN)('竞价台账 · 真库(B2/B6/B15 + 迁移约束)', () => { + beforeAll(async () => { + await cleanup(); + }); + + afterAll(async () => { + await cleanup(); + await pool().end(); + }); + + it('迁移已在本地库生效:两张表都在 public', async () => { + const { rows } = await pool().query( + `SELECT table_name FROM information_schema.tables + WHERE table_schema = 'public' AND table_name IN ('main_system_bid_invitations','main_system_bid_invitation_items') + ORDER BY table_name` + ); + expect(rows.map((row: { table_name: string }) => row.table_name)).toEqual([ + 'main_system_bid_invitation_items', + 'main_system_bid_invitations', + ]); + }); + + it('B2 幂等:webhook 连推两次 ⇒ 1 行邀约 + 2 行明细(ON CONFLICT 生效)', async () => { + const roundId = `round-it-${Date.now()}-idem`; + const payload = { + round_id: roundId, + round_code: 'BID-IT', + respond_deadline: new Date(Date.now() + 3600_000).toISOString(), + item_count: 2, + items: [ + { sku_code: 'SKU_IT_1', sku_name: '草鱼', unit: '斤' }, + { sku_code: 'SKU_IT_2', sku_name: '鲤鱼', unit: '斤' }, + ], + }; + const first = await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload }); + const second = await real!.inbox.recordBidOpened({ branchCode: TEST_BRANCH, supplierCode: SUPPLIER_A, payload }); + expect(first.status).toBe('recorded'); + expect(second.status).toBe('recorded'); + expect(second.roundId).toBe(first.roundId); + + const { rows } = await pool().query( + `SELECT id, item_count, round_status, local_status FROM public.main_system_bid_invitations + WHERE branch_code = $1 AND round_id = $2`, + [TEST_BRANCH, roundId] + ); + expect(rows).toHaveLength(1); + expect(Number(rows[0].item_count)).toBe(2); + expect(rows[0].round_status).toBe('open'); + expect(rows[0].local_status).toBe('pending'); + + const items = await pool().query( + `SELECT sku_code FROM public.main_system_bid_invitation_items WHERE invitation_id = $1 ORDER BY sku_code`, + [rows[0].id] + ); + expect(items.rows.map((row: { sku_code: string }) => row.sku_code)).toEqual(['SKU_IT_1', 'SKU_IT_2']); + }); + + it('唯一索引不允许同 (branch, round, supplier) 两行(裸 INSERT 会炸)', async () => { + const roundId = `round-it-${Date.now()}-uniq`; + await real!.inbox.recordBidOpened({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + payload: { round_id: roundId, items: [] }, + }); + await expect( + pool().query( + `INSERT INTO public.main_system_bid_invitations (branch_code, supplier_code, round_id) VALUES ($1, $2, $3)`, + [TEST_BRANCH, SUPPLIER_A, roundId] + ) + ).rejects.toThrow(/duplicate key|uq_main_system_bid_invitations_branch_round_supplier/); + }); + + it('B6 对方删行 ⇒ 真库里那一行被 DELETE,item_count 收缩', async () => { + const roundId = `round-it-${Date.now()}-del`; + await real!.inbox.recordBidOpened({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + payload: { + round_id: roundId, + item_count: 2, + items: [ + { sku_code: 'SKU_IT_1', sku_name: '草鱼', unit: '斤' }, + { sku_code: 'SKU_IT_2', sku_name: '鲤鱼', unit: '斤' }, + ], + }, + }); + + const result = await real!.inbox.applyBidDetail({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + roundId, + detail: { + round: { id: roundId, status: 'open', respond_deadline: new Date(Date.now() + 3600_000).toISOString() }, + invitation: { status: 'pending' }, + items: [{ sku_code: 'SKU_IT_1', sku_name: '草鱼', unit: '斤' }], + myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 12.5 }], + myAwards: [], + }, + }); + // 剩下那行有价且行数=1 ⇒ 真库重算后是 quoted(同时也证明 item_count 参与派生) + expect(result.localStatus).toBe('quoted'); + + const header = await pool().query( + `SELECT id, item_count FROM public.main_system_bid_invitations WHERE branch_code = $1 AND round_id = $2`, + [TEST_BRANCH, roundId] + ); + expect(Number(header.rows[0].item_count)).toBe(1); + const items = await pool().query( + `SELECT sku_code, unit_price FROM public.main_system_bid_invitation_items WHERE invitation_id = $1`, + [header.rows[0].id] + ); + expect(items.rows).toHaveLength(1); + expect(items.rows[0].sku_code).toBe('SKU_IT_1'); + expect(Number(items.rows[0].unit_price)).toBe(12.5); + }); + + it('B6 对方撤回报价 ⇒ 真库里 unit_price / quoted_at 变 NULL,local_status 回 pending', async () => { + const roundId = `round-it-${Date.now()}-withdraw`; + await real!.inbox.recordBidOpened({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + payload: { round_id: roundId, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + const first = await real!.inbox.applyBidDetail({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + roundId, + detail: { + round: { id: roundId, status: 'open', respond_deadline: new Date(Date.now() + 3600_000).toISOString() }, + invitation: { status: 'quoted' }, + items: [{ sku_code: 'SKU_IT_1' }], + myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 12.5, updated_at: new Date().toISOString() }], + myAwards: [], + }, + }); + expect(first.localStatus).toBe('quoted'); + + const second = await real!.inbox.applyBidDetail({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + roundId, + detail: { + round: { id: roundId, status: 'open', respond_deadline: new Date(Date.now() + 3600_000).toISOString() }, + invitation: { status: 'pending' }, + items: [{ sku_code: 'SKU_IT_1' }], + myQuotes: [], + myAwards: [], + }, + }); + expect(second.localStatus).toBe('pending'); + + const row = await pool().query( + `SELECT it.unit_price, it.quoted_at FROM public.main_system_bid_invitation_items it + JOIN public.main_system_bid_invitations i ON i.id = it.invitation_id + WHERE i.branch_code = $1 AND i.round_id = $2`, + [TEST_BRANCH, roundId] + ); + expect(row.rows[0].unit_price).toBe(null); + expect(row.rows[0].quoted_at).toBe(null); + }); + + it('B6 awarded 且该 SKU 无中标 ⇒ 真库 award 列为空、读取视图 local_status/awardStatus 都是 lost', async () => { + const roundId = `round-it-${Date.now()}-lost`; + await real!.inbox.recordBidOpened({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + payload: { round_id: roundId, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + const applied = await real!.inbox.applyBidDetail({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + roundId, + detail: { + round: { id: roundId, status: 'awarded' }, + invitation: { status: 'quoted' }, + items: [{ sku_code: 'SKU_IT_1' }], + myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 12.5 }], + myAwards: [], + }, + }); + expect(applied.localStatus).toBe('lost'); + + const detail = await real!.inbox.getBidInvitationDetail({ branchCode: TEST_BRANCH, roundId }); + expect(detail?.invitation.localStatus).toBe('lost'); + expect(detail?.items.map((item) => item.awardStatus)).toEqual(['lost']); + expect(detail?.myAwards).toEqual([]); + expect(detail?.canQuote).toBe(false); + + const stored = await pool().query( + `SELECT it.award_price, it.award_status FROM public.main_system_bid_invitation_items it + JOIN public.main_system_bid_invitations i ON i.id = it.invitation_id + WHERE i.branch_code = $1 AND i.round_id = $2`, + [TEST_BRANCH, roundId] + ); + expect(stored.rows[0].award_price).toBe(null); + expect(stored.rows[0].award_status).toBe(null); + }); + + it('B6 awarded 且中标 ⇒ award_price 落 numeric(14,4),localStatus=won', async () => { + const roundId = `round-it-${Date.now()}-won`; + await real!.inbox.recordBidOpened({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + payload: { round_id: roundId, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + const applied = await real!.inbox.applyBidDetail({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + roundId, + detail: { + round: { id: roundId, status: 'awarded' }, + invitation: { status: 'quoted' }, + items: [{ sku_code: 'SKU_IT_1' }], + myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 12.5 }], + myAwards: [{ sku_code: 'SKU_IT_1', unit_price: 11.2345 }], + }, + }); + expect(applied.localStatus).toBe('won'); + + const stored = await pool().query( + `SELECT it.award_price::text AS award_price, it.award_status, it.unit_price::text AS unit_price + FROM public.main_system_bid_invitation_items it + JOIN public.main_system_bid_invitations i ON i.id = it.invitation_id + WHERE i.branch_code = $1 AND i.round_id = $2`, + [TEST_BRANCH, roundId] + ); + // numeric(14,4) 至少保留到 4 位小数(11.2345 不能被舍成 11.23) + expect(Number(stored.rows[0].award_price)).toBe(11.2345); + expect(stored.rows[0].award_status).toBe('won'); + expect(Number(stored.rows[0].unit_price)).toBe(12.5); + }); + + it('B15 真库两行同轮不同 supplier ⇒ ambiguous;带 supplier 精确命中', async () => { + const roundId = `round-it-${Date.now()}-multi`; + for (const supplierCode of [SUPPLIER_A, SUPPLIER_B]) { + await real!.inbox.recordBidOpened({ + branchCode: TEST_BRANCH, + supplierCode, + payload: { round_id: roundId, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + } + const ambiguous = await real!.inbox.findInvitationByRound({ branchCode: TEST_BRANCH, roundId }); + expect(ambiguous.kind).toBe('ambiguous'); + expect( + (ambiguous as unknown as { supplierCodes: string[] }).supplierCodes.sort() + ).toEqual([SUPPLIER_A, SUPPLIER_B]); + + const exact = await real!.inbox.findInvitationByRound({ + branchCode: TEST_BRANCH, + roundId, + supplierCode: SUPPLIER_B.toLowerCase(), + }); + expect(exact.kind).toBe('found'); + expect((exact as unknown as { row: { supplier_code: string } }).row.supplier_code).toBe(SUPPLIER_B); + }); + + it('迁移 CHECK 真的生效:local_status / round_status / award_status / unit_price>0 被库拒绝', async () => { + const base = `round-it-${Date.now()}-check`; + const insert = (roundId: string, localStatus: string) => + pool().query( + `INSERT INTO public.main_system_bid_invitations (branch_code, supplier_code, round_id, local_status) + VALUES ($1, $2, $3, $4)`, + [TEST_BRANCH, SUPPLIER_A, roundId, localStatus] + ); + + await expect(insert(`${base}-1`, 'weird')).rejects.toThrow(/local_status_check|violates check constraint/); + await expect(insert(`${base}-2`, 'closed')).rejects.toThrow(/local_status_check|violates check constraint/); + + await expect( + pool().query( + `INSERT INTO public.main_system_bid_invitations (branch_code, supplier_code, round_id, round_status) + VALUES ($1, $2, $3, 'weird')`, + [TEST_BRANCH, SUPPLIER_A, `${base}-3`] + ) + ).rejects.toThrow(/round_status_check|violates check constraint/); + + // 明细的两条 CHECK:award_status 只允许 won/lost;unit_price 必须 > 0 + await real!.inbox.recordBidOpened({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + payload: { round_id: `${base}-4`, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + const invitation = await real!.inbox.findInvitationByRound({ branchCode: TEST_BRANCH, roundId: `${base}-4` }); + expect(invitation.kind).toBe('found'); + const invitationId = (invitation as unknown as { row: { id: string } }).row.id; + await expect( + pool().query( + `INSERT INTO public.main_system_bid_invitation_items (invitation_id, branch_code, round_id, sku_code, award_status) + VALUES ($1, $2, $3, 'SKU_IT_X', 'maybe')`, + [invitationId, TEST_BRANCH, `${base}-4`] + ) + ).rejects.toThrow(/award_status_check|violates check constraint/); + await expect( + pool().query( + `INSERT INTO public.main_system_bid_invitation_items (invitation_id, branch_code, round_id, sku_code, unit_price) + VALUES ($1, $2, $3, 'SKU_IT_Y', 0)`, + [invitationId, TEST_BRANCH, `${base}-4`] + ) + ).rejects.toThrow(/unit_price_check|violates check constraint/); + }); + + it('B4 清单:真 SQL 的 status 过滤 + summary 口径(pending/history、closed=终态之和)', async () => { + const branch = `${TEST_BRANCH}_B4`; + // 三种状态各造一行:pending / quoted / cancelled + await real!.inbox.recordBidOpened({ + branchCode: branch, + supplierCode: SUPPLIER_A, + payload: { round_id: 'round-b4-p', item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + await real!.inbox.recordBidOpened({ + branchCode: branch, + supplierCode: SUPPLIER_A, + payload: { round_id: 'round-b4-q', item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + await real!.inbox.applyBidDetail({ + branchCode: branch, + supplierCode: SUPPLIER_A, + roundId: 'round-b4-q', + detail: { + round: { id: 'round-b4-q', status: 'open', respond_deadline: new Date(Date.now() + 3600_000).toISOString() }, + invitation: { status: 'quoted' }, + items: [{ sku_code: 'SKU_IT_1' }], + myQuotes: [{ sku_code: 'SKU_IT_1', unit_price: 5 }], + myAwards: [], + }, + }); + await real!.inbox.recordBidOpened({ + branchCode: branch, + supplierCode: SUPPLIER_A, + payload: { round_id: 'round-b4-c', item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + await real!.inbox.markInvitationCancelled({ + branchCode: branch, + roundId: 'round-b4-c', + supplierCode: SUPPLIER_A, + reason: 'it: cancelled', + }); + + const pending = await real!.quotes.listBidInvitations({ branchCode: branch, status: 'pending' }); + expect(pending.rows.map((row) => row.roundId)).toEqual(['round-b4-p']); + + const history = await real!.quotes.listBidInvitations({ branchCode: branch, status: 'history' }); + expect(history.rows.map((row) => row.roundId).sort()).toEqual(['round-b4-c', 'round-b4-q']); + + const all = await real!.quotes.listBidInvitations({ branchCode: branch, status: 'all' }); + expect(all.summary).toMatchObject({ pending: 1, quoted: 1, cancelled: 1, closed: 1 }); + + const other = await real!.quotes.listBidInvitations({ branchCode: 'BR_TESTBID_NOPE', status: 'all' }); + expect(other.rows).toEqual([]); + }); + + it('派生口径在真库时钟下成立:截止已过 ⇒ expired(读库取 timestamptz)', async () => { + const roundId = `round-it-${Date.now()}-expired`; + const past = new Date(Date.now() - 60_000).toISOString(); + await real!.inbox.recordBidOpened({ + branchCode: TEST_BRANCH, + supplierCode: SUPPLIER_A, + payload: { round_id: roundId, respond_deadline: past, item_count: 1, items: [{ sku_code: 'SKU_IT_1' }] }, + }); + const detail = await real!.inbox.getBidInvitationDetail({ branchCode: TEST_BRANCH, roundId }); + expect(detail?.deadlinePassed).toBe(true); + expect(detail?.invitation.localStatus).toBe('expired'); + expect(detail?.canQuote).toBe(false); + }); +}); + +describe.skipIf(RUN)('真库验证(默认跳过)', () => { + it('设置 BID_DB_TEST=1 才连真库;常规套件不加载 src/db', () => { + expect(real).toBe(null); + }); +}); diff --git a/src/config/menuCatalog.bidRetired.contract.test.ts b/src/config/menuCatalog.bidRetired.contract.test.ts index 6bbe8b8..cb578ef 100644 --- a/src/config/menuCatalog.bidRetired.contract.test.ts +++ b/src/config/menuCatalog.bidRetired.contract.test.ts @@ -72,3 +72,26 @@ describe('存量布局无需清库', () => { ); }); }); + +/** + * B11(`docs/design/20261017-主系统竞价待报价与报价提交.md` §8):菜单要**含** + * `orders-bid-invitations`,同时「竞价管理」(`orders-bids`)仍不在菜单里。 + */ +describe('新增「待报价」(orders-bid-invitations)', () => { + it('目录项存在,路径/权限与「供需变更审核」同口径', () => { + const entry = MENU_CATALOG_MAP['orders-bid-invitations']; + expect(entry, '菜单目录缺 orders-bid-invitations').toBeTruthy(); + expect(entry.path).toBe('/orders/bid-invitations'); + expect(entry.secondary).toBe(true); + expect(entry.permission).toEqual(['order_manage', 'order_edit']); + expect(entry.accessMatch).toBe('any'); + }); + + it('默认布局的「业务流程」里带它,且没有 orders-bids', () => { + const keys = createDefaultNavMenuLayout().groups.flatMap((group) => + group.items.map((item) => item.menuKey) + ); + expect(keys).toContain('orders-bid-invitations'); + expect(keys).not.toContain('orders-bids'); + }); +}); diff --git a/src/config/menuCatalog.ts b/src/config/menuCatalog.ts index 1a5d502..9a28c17 100644 --- a/src/config/menuCatalog.ts +++ b/src/config/menuCatalog.ts @@ -27,6 +27,15 @@ export const MENU_CATALOG: MenuCatalogEntry[] = [ accessMatch: 'any', secondary: true, }, + { + menuKey: 'orders-bid-invitations', + path: '/orders/bid-invitations', + defaultLabel: '待报价', + icon: 'ChevronRight', + permission: ['order_manage', 'order_edit'], + accessMatch: 'any', + secondary: true, + }, { menuKey: 'customers-list', path: '/customers', defaultLabel: '客户列表', icon: 'ChevronRight', permission: 'customer_manage', secondary: true }, { menuKey: 'customers-quote-versions', path: '/customers/quote-versions', defaultLabel: '报价管理', icon: 'ChevronRight', permission: 'customer_manage', secondary: true }, { menuKey: 'products-categories', path: '/products/categories', defaultLabel: '分类管理', icon: 'ChevronRight', permission: ['category_manage', 'product_manage'], secondary: true }, diff --git a/src/i18n/locales/en/bids.ts b/src/i18n/locales/en/bids.ts index 361bf84..d627bdd 100644 --- a/src/i18n/locales/en/bids.ts +++ b/src/i18n/locales/en/bids.ts @@ -197,4 +197,29 @@ export const bids: MessageDict = { 'Copy awarded suppliers and prices from “{code}” to the next period; suppliers need not quote again. Renew?', 'confirm.renewFallback': 'this round', 'confirm.renewConfirm': 'Renew', + // Main-system bidding "bid requests" (docs/design/20261017-主系统竞价待报价与报价提交.md §6.3) + 'invite.pageTitle': 'Bid requests (main system)', + 'invite.colRoundNo': 'Round no.', + 'invite.colTitle': 'Title', + 'invite.colItemCount': 'Items', + 'invite.colDeadline': 'Deadline', + 'invite.statusPending': 'To quote', + 'invite.statusQuoted': 'Quoted', + 'invite.statusExpired': 'Closed', + 'invite.statusWon': 'Won', + 'invite.statusLost': 'Not won', + 'invite.statusCancelled': 'Cancelled', + 'invite.actQuote': 'Quote', + 'invite.actView': 'View', + 'invite.colItem': 'Item', + 'invite.colUnit': 'Unit', + 'invite.colMyPrice': 'My price', + 'invite.colAwardPrice': 'Award price', + 'invite.colRemark': 'Remark', + 'invite.btnSaveQuotes': 'Save quotes', + 'invite.btnSync': 'Sync', + 'invite.btnRefresh': 'Refresh', + 'invite.toastSubmitted': 'Quotes submitted', + 'invite.deadlinePassed': 'Past the quote deadline', + 'invite.empty': 'No bid requests', }; diff --git a/src/i18n/locales/en/menu.ts b/src/i18n/locales/en/menu.ts index 3afe0d8..d163c00 100644 --- a/src/i18n/locales/en/menu.ts +++ b/src/i18n/locales/en/menu.ts @@ -6,6 +6,7 @@ export const menu: MessageDict = { 'orders-list': 'Orders', 'orders-bids': 'Bidding', 'orders-price-qty': 'Supply/demand change review', + 'orders-bid-invitations': 'Bid requests', 'customers-list': 'Customers', 'customers-quote-versions': 'Quotes', 'products-categories': 'Categories', diff --git a/src/i18n/locales/id/bids.ts b/src/i18n/locales/id/bids.ts index 0e4cc20..38f5d8a 100644 --- a/src/i18n/locales/id/bids.ts +++ b/src/i18n/locales/id/bids.ts @@ -201,4 +201,29 @@ export const bids: MessageDict = { 'Salin pemasok dan harga pemenang dari «{code}» ke periode berikutnya; pemasok tidak perlu menawar lagi. Perpanjang?', 'confirm.renewFallback': 'putaran ini', 'confirm.renewConfirm': 'Perpanjang', + // Permintaan penawaran sistem utama (docs/design/20261017-主系统竞价待报价与报价提交.md §6.3) + 'invite.pageTitle': 'Permintaan penawaran (sistem utama)', + 'invite.colRoundNo': 'No. ronde', + 'invite.colTitle': 'Judul', + 'invite.colItemCount': 'Jumlah item', + 'invite.colDeadline': 'Batas waktu', + 'invite.statusPending': 'Belum ditawar', + 'invite.statusQuoted': 'Sudah ditawar', + 'invite.statusExpired': 'Ditutup', + 'invite.statusWon': 'Menang', + 'invite.statusLost': 'Tidak menang', + 'invite.statusCancelled': 'Dibatalkan', + 'invite.actQuote': 'Tawar', + 'invite.actView': 'Lihat', + 'invite.colItem': 'Barang', + 'invite.colUnit': 'Satuan', + 'invite.colMyPrice': 'Harga saya', + 'invite.colAwardPrice': 'Harga menang', + 'invite.colRemark': 'Catatan', + 'invite.btnSaveQuotes': 'Simpan penawaran', + 'invite.btnSync': 'Sinkron', + 'invite.btnRefresh': 'Segarkan', + 'invite.toastSubmitted': 'Penawaran terkirim', + 'invite.deadlinePassed': 'Melewati batas waktu', + 'invite.empty': 'Belum ada permintaan penawaran', }; diff --git a/src/i18n/locales/id/menu.ts b/src/i18n/locales/id/menu.ts index 7946082..0378b5b 100644 --- a/src/i18n/locales/id/menu.ts +++ b/src/i18n/locales/id/menu.ts @@ -6,6 +6,7 @@ export const menu: MessageDict = { 'orders-list': 'Pesanan', 'orders-bids': 'Lelang', 'orders-price-qty': 'Tinjauan perubahan pasokan/permintaan', + 'orders-bid-invitations': 'Permintaan penawaran', 'customers-list': 'Pelanggan', 'customers-quote-versions': 'Harga penawaran', 'products-categories': 'Kategori', diff --git a/src/i18n/locales/zh-CN/bids.ts b/src/i18n/locales/zh-CN/bids.ts index 2f3c600..a7d48d6 100644 --- a/src/i18n/locales/zh-CN/bids.ts +++ b/src/i18n/locales/zh-CN/bids.ts @@ -189,4 +189,29 @@ export const bids: MessageDict = { '将「{code}」的中标供应商与价格复制到下一周期,供应商无需再报价。确定沿用?', 'confirm.renewFallback': '该轮', 'confirm.renewConfirm': '沿用', + // 主系统竞价「待报价」(docs/design/20261017-主系统竞价待报价与报价提交.md §6.3) + 'invite.pageTitle': '待报价(主系统竞价)', + 'invite.colRoundNo': '竞价单号', + 'invite.colTitle': '竞价标题', + 'invite.colItemCount': '商品数', + 'invite.colDeadline': '报价截止', + 'invite.statusPending': '待报价', + 'invite.statusQuoted': '已报价', + 'invite.statusExpired': '已截止', + 'invite.statusWon': '已中标', + 'invite.statusLost': '未中标', + 'invite.statusCancelled': '已取消', + 'invite.actQuote': '报价', + 'invite.actView': '查看', + 'invite.colItem': '商品', + 'invite.colUnit': '单位', + 'invite.colMyPrice': '我方报价', + 'invite.colAwardPrice': '中标价', + 'invite.colRemark': '备注', + 'invite.btnSaveQuotes': '保存报价', + 'invite.btnSync': '同步', + 'invite.btnRefresh': '刷新', + 'invite.toastSubmitted': '报价已提交', + 'invite.deadlinePassed': '已超过报价截止时间', + 'invite.empty': '暂无待报价的竞价单', }; diff --git a/src/i18n/locales/zh-CN/menu.ts b/src/i18n/locales/zh-CN/menu.ts index a4c742b..8d07998 100644 --- a/src/i18n/locales/zh-CN/menu.ts +++ b/src/i18n/locales/zh-CN/menu.ts @@ -6,6 +6,7 @@ export const menu: MessageDict = { 'orders-list': '订单管理', 'orders-bids': '竞价管理', 'orders-price-qty': '供需变更审核', + 'orders-bid-invitations': '待报价', 'customers-list': '客户列表', 'customers-quote-versions': '报价管理', 'products-categories': '分类管理', diff --git a/src/modules/businessModules.ts b/src/modules/businessModules.ts index 4434523..5b08d64 100644 --- a/src/modules/businessModules.ts +++ b/src/modules/businessModules.ts @@ -15,7 +15,7 @@ export const BUSINESS_MODULES: BusinessModuleDef[] = [ 'bid_manage', ], workflowApiPrefix: '/orders', - menuKeys: ['customer-order', 'orders-list', 'orders-price-qty'], + menuKeys: ['customer-order', 'orders-list', 'orders-price-qty', 'orders-bid-invitations'], routes: [ { path: 'order-entry', page: 'CustomerOrder', permission: 'order_entry', redirect: '/customer-order' }, { @@ -34,6 +34,11 @@ export const BUSINESS_MODULES: BusinessModuleDef[] = [ page: 'PriceQtyRequestsPage', permission: ['order_manage', 'order_edit'], }, + { + path: 'bid-invitations', + page: 'BidInvitationsPage', + permission: ['order_manage', 'order_edit'], + }, { path: 'bids', page: 'BidManagement', diff --git a/src/modules/routes.tsx b/src/modules/routes.tsx index 9d514ec..4b9289d 100644 --- a/src/modules/routes.tsx +++ b/src/modules/routes.tsx @@ -28,6 +28,10 @@ const PAGE_LOADERS: Record> = { () => import('../pages/orders/PriceQtyRequestsPage'), 'PriceQtyRequestsPage' ), + BidInvitationsPage: lazyPage( + () => import('../pages/orders/BidInvitationsPage'), + 'BidInvitationsPage' + ), CustomerOrder: lazyPage(() => import('../pages/orders/CustomerOrder'), 'CustomerOrder'), BidManagement: lazyPage(() => import('../pages/orders/BidManagement'), 'BidManagement'), InventoryManagement: lazyPage(() => import('../pages/inventory/InventoryManagement'), 'InventoryManagement'), diff --git a/src/pages/orders/BidInvitationsPage.render.test.tsx b/src/pages/orders/BidInvitationsPage.render.test.tsx new file mode 100644 index 0000000..1823d90 --- /dev/null +++ b/src/pages/orders/BidInvitationsPage.render.test.tsx @@ -0,0 +1,351 @@ +// @vitest-environment jsdom +import React from 'react'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +/** + * 「待报价(主系统竞价)」页的**行为契约**(docs/design/20261017-主系统竞价待报价与报价提交.md §6): + * ① 清单渲染:竞价单号 / 竞价标题 / 商品数 / 报价截止 / 状态 / 操作; + * ② 点「报价」打开弹窗,渲染商品行与逐行报价输入(我方报价 / 中标价 / 备注); + * ③ 提交成功后清单行状态变「已报价」+ toast「报价已提交」; + * ④ 已截止 / 已中标 ⇒ 输入只读、保存按钮禁用(并给一句原因)。 + */ + +const DEADLINE = '2026-12-31T10:00:00+08:00'; + +const PENDING_ROW = { + roundId: 'r-pending', + roundCode: 'BID20261017BR00201', + roundTitle: '周四生鲜竞价', + orderCode: 'ORD_WEB_20261017_BR002_0001', + supplierCode: 'SUP37831443', + respondDeadline: DEADLINE, + itemCount: 2, + roundStatus: 'open', + localStatus: 'pending', + quotedAt: null, + lastSyncedAt: '2026-10-17T02:00:00.000Z', +} as const; + +const QUOTED_ROW = { + ...PENDING_ROW, + roundId: 'r-quoted', + roundCode: 'BID20261017BR00202', + roundTitle: '周五生鲜竞价', + localStatus: 'quoted', + quotedAt: '2026-10-17T02:10:00.000Z', +} as const; + +const WON_ROW = { + ...PENDING_ROW, + roundId: 'r-won', + roundCode: 'BID20261017BR00203', + roundTitle: '已定标竞价', + roundStatus: 'awarded', + localStatus: 'won', +} as const; + +const EXPIRED_ROW = { + ...PENDING_ROW, + roundId: 'r-expired', + roundCode: 'BID20261017BR00204', + roundTitle: '已截止竞价', + localStatus: 'expired', +} as const; + +const ITEMS_PENDING = [ + { + skuCode: 'SKU78661366595', + skuName: '草鱼', + unit: '斤', + unitPrice: null, + remark: null, + quotedAt: null, + awardPrice: null, + awardQty: null, + awardStatus: null, + }, + { + skuCode: 'SKU2', + skuName: '鲈鱼', + unit: '斤', + unitPrice: null, + remark: null, + quotedAt: null, + awardPrice: null, + awardQty: null, + awardStatus: null, + }, +]; + +function detailFor(roundId: string) { + if (roundId === 'r-won') { + return { + invitation: WON_ROW, + items: [ + { + ...ITEMS_PENDING[0], + unitPrice: 12.5, + awardPrice: 12.5, + awardQty: 10, + awardStatus: 'won', + }, + ], + canQuote: false, + deadlinePassed: false, + syncError: null, + }; + } + if (roundId === 'r-expired') { + return { + invitation: EXPIRED_ROW, + items: [{ ...ITEMS_PENDING[0], unitPrice: 11 }], + canQuote: false, + deadlinePassed: true, + syncError: null, + }; + } + return { + invitation: roundId === 'r-quoted' ? QUOTED_ROW : PENDING_ROW, + items: ITEMS_PENDING, + canQuote: true, + deadlinePassed: false, + syncError: null, + }; +} + +const listApi = vi.fn(async () => ({ + data: [PENDING_ROW, QUOTED_ROW, WON_ROW, EXPIRED_ROW], + summary: { pending: 1, quoted: 1, expired: 1, closed: 1 }, + error: null, +})); + +const getApi = vi.fn(async (roundId: string) => detailFor(roundId)); + +const submitApi = vi.fn( + async ( + roundId: string, + quotes: Array<{ skuCode: string; unitPrice: number; remark?: string }> + ) => { + const base = detailFor(roundId); + const items = base.items.map((item) => { + const hit = quotes.find((quote) => quote.skuCode === item.skuCode); + return hit + ? { + ...item, + unitPrice: hit.unitPrice, + remark: hit.remark ?? null, + quotedAt: '2026-10-17T02:20:00.000Z', + } + : item; + }); + return { + invitation: { ...base.invitation, localStatus: 'quoted', quotedAt: '2026-10-17T02:20:00.000Z' }, + items, + canQuote: true, + deadlinePassed: false, + syncError: null, + }; + } +); + +const syncApi = vi.fn(async () => ({ + synced: 1, + skipped: 0, + unavailable: 0, + enabled: true, + error: null, +})); + +vi.mock('../../utils/workflowApi', () => ({ + listMainSystemBidInvitationsApi: () => listApi(), + syncMainSystemBidInvitationsApi: () => syncApi(), + getMainSystemBidInvitationApi: (roundId: string) => getApi(roundId), + submitMainSystemBidQuotesApi: ( + roundId: string, + quotes: Array<{ skuCode: string; unitPrice: number; remark?: string }> + ) => submitApi(roundId, quotes), +})); + +// 用真实的 zh-CN `bids` + `common` 文案做 t();MenuLabel 直接渲染 fallback(免搭 Provider 栈) +function buildDict( + bids: Record, + common: Record +): Record { + const dict: Record = {}; + for (const [key, value] of Object.entries(bids)) dict[`bids.${key}`] = value; + for (const [key, value] of Object.entries(common)) dict[`common.${key}`] = value; + return dict; +} + +vi.mock('../../i18n/I18nProvider', async () => { + const { bids } = (await import('../../i18n/locales/zh-CN/bids')) as unknown as { + bids: Record; + }; + const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as { + common: Record; + }; + const dict = buildDict(bids, common); + // ⚠️ `t` 只建一次:页面把 `t` 放进 useCallback/useEffect 依赖,每渲染换新函数会无限重渲染 + const t = (key: string, vars?: Record) => { + const raw = dict[key] ?? key; + if (!vars) return raw; + return Object.entries(vars).reduce( + (acc, [name, value]) => acc.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value)), + raw + ); + }; + return { useI18n: () => ({ locale: 'zh-CN', t }) }; +}); + +vi.mock('../../components/MenuLabel', () => ({ + MenuLabel: ({ fallback }: { fallback?: string }) => {fallback}, +})); + +// `TablePaginationBar` 从 i18n 桶文件取 `useTOrDefault` ⇒ 一并 mock 成同一份字典 +vi.mock('../../i18n', async () => { + const actual = await vi.importActual('../../i18n'); + const { bids } = (await import('../../i18n/locales/zh-CN/bids')) as unknown as { + bids: Record; + }; + const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as { + common: Record; + }; + const dict = buildDict(bids, common); + const t = (key: string, vars?: Record) => { + const raw = dict[key] ?? key; + if (!vars) return raw; + return Object.entries(vars).reduce( + (acc, [name, value]) => acc.replace(new RegExp(`\\{${name}\\}`, 'g'), String(value)), + raw + ); + }; + return { ...actual, useTOrDefault: () => t }; +}); + +import BidInvitationsPage from './BidInvitationsPage'; + +afterEach(() => { + cleanup(); + listApi.mockClear(); + getApi.mockClear(); + submitApi.mockClear(); + syncApi.mockClear(); +}); + +const renderPage = () => render(); + +describe('待报价(主系统竞价)· 清单', () => { + it('渲染竞价单号 / 竞价标题 / 商品数 / 报价截止 / 状态 / 操作 六列与数据行', async () => { + renderPage(); + for (const label of ['竞价单号', '竞价标题', '商品数', '报价截止', '状态', '操作']) { + expect((await screen.findAllByText(label)).length, `缺表头 ${label}`).toBeGreaterThan(0); + } + expect(await screen.findByText('BID20261017BR00201')).toBeTruthy(); + expect(screen.getByText('周四生鲜竞价')).toBeTruthy(); + // 状态徽标与操作按钮都在(『待报价』状态 + 『报价』操作) + expect(screen.getAllByText('待报价').length).toBeGreaterThan(0); + expect(screen.getAllByText('报价').length).toBeGreaterThan(0); + // 报价截止按本地时间渲染 + const row = screen.getByText('BID20261017BR00201').closest('tr'); + expect(row?.textContent).toContain(new Date(DEADLINE).toLocaleString('zh-CN')); + expect(row?.textContent).toContain('2'); + }); + + it('顶部只有「同步」「刷新」两个按钮(无状态筛选/本地竞价管理)', async () => { + renderPage(); + expect(await screen.findByText('同步')).toBeTruthy(); + expect(screen.getByText('刷新')).toBeTruthy(); + expect(screen.queryByText('竞价设置')).toBeNull(); + expect(screen.queryByText('历史竞价')).toBeNull(); + }); + + it('「同步」调用 sync 接口后重读清单', async () => { + renderPage(); + await screen.findByText('BID20261017BR00201'); + fireEvent.click(screen.getByText('同步')); + await waitFor(() => expect(syncApi).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(listApi).toHaveBeenCalledTimes(2)); + }); +}); + +describe('待报价(主系统竞价)· 弹窗填价', () => { + it('点「报价」打开弹窗:标题=竞价单号,渲染商品行 / 单位 / 我方报价输入 / 中标价 / 备注', async () => { + renderPage(); + await screen.findByText('BID20261017BR00201'); + fireEvent.click(screen.getAllByText('报价')[0]); + expect(await screen.findByRole('dialog')).toBeTruthy(); + expect(getApi).toHaveBeenCalledWith('r-pending'); + // 商品行 + expect(await screen.findByText('草鱼')).toBeTruthy(); + expect(screen.getByText('鲈鱼')).toBeTruthy(); + // 逐行报价输入(step 0.0001 的数字框)+ 备注框 + const priceInput = screen.getByLabelText('我方报价 草鱼') as HTMLInputElement; + expect(priceInput.type).toBe('number'); + expect(priceInput.step).toBe('0.0001'); + expect(priceInput.disabled).toBe(false); + expect(screen.getByLabelText('备注 草鱼')).toBeTruthy(); + // 表头:商品 / 单位 / 我方报价 / 中标价 / 备注 + for (const label of ['商品', '单位', '我方报价', '中标价', '备注']) { + expect(screen.getAllByText(label).length, `弹窗缺表头 ${label}`).toBeGreaterThan(0); + } + // 底部:保存报价 + 关闭 + expect(screen.getByText('保存报价')).toBeTruthy(); + expect(screen.getByText('关闭')).toBeTruthy(); + }); + + it('提交成功:只提交已填价的行,清单行变「已报价」并 toast「报价已提交」', async () => { + renderPage(); + await screen.findByText('BID20261017BR00201'); + fireEvent.click(screen.getAllByText('报价')[0]); + await screen.findByText('草鱼'); + + fireEvent.change(screen.getByLabelText('我方报价 草鱼'), { target: { value: '12.5' } }); + fireEvent.click(screen.getByText('保存报价')); + + await waitFor(() => + expect(submitApi).toHaveBeenCalledWith('r-pending', [ + { skuCode: 'SKU78661366595', unitPrice: 12.5 }, + ]) + ); + // toast(真实 notify,挂在 document.body 上) + expect(await screen.findByText('报价已提交')).toBeTruthy(); + // 清单行状态就地变「已报价」(弹窗标题也是单号 ⇒ 用 getAllByText 取表格里的那一个) + await waitFor(() => { + const row = screen.getAllByText('BID20261017BR00201')[0].closest('tr'); + expect(row?.textContent).toContain('已报价'); + }); + // 弹窗不关闭,且输入被返回视图回填 + expect(screen.getByRole('dialog')).toBeTruthy(); + expect((screen.getByLabelText('我方报价 草鱼') as HTMLInputElement).value).toBe('12.5'); + }); + + it('已中标 ⇒ 输入只读、保存按钮禁用,并给一句原因', async () => { + renderPage(); + await screen.findByText('BID20261017BR00203'); + const wonRow = screen.getByText('BID20261017BR00203').closest('tr') as HTMLElement; + fireEvent.click(wonRow.querySelector('button') as HTMLButtonElement); + + await screen.findByText('草鱼'); + expect(getApi).toHaveBeenCalledWith('r-won'); + expect((screen.getByLabelText('我方报价 草鱼') as HTMLInputElement).disabled).toBe(true); + expect((screen.getByLabelText('备注 草鱼') as HTMLInputElement).disabled).toBe(true); + expect((screen.getByText('保存报价').closest('button') as HTMLButtonElement).disabled).toBe(true); + expect(screen.getByRole('note').textContent).toContain('已中标'); + // 中标价只读展示(numeric(14,4) 允许 4 位小数) + expect(document.body.textContent).toContain('12.50'); + }); + + it('已截止 ⇒ 输入只读、保存按钮禁用,原因是「已超过报价截止时间」', async () => { + renderPage(); + await screen.findByText('BID20261017BR00204'); + const expiredRow = screen.getByText('BID20261017BR00204').closest('tr') as HTMLElement; + fireEvent.click(expiredRow.querySelector('button') as HTMLButtonElement); + + await screen.findByText('草鱼'); + expect(getApi).toHaveBeenCalledWith('r-expired'); + expect((screen.getByLabelText('我方报价 草鱼') as HTMLInputElement).disabled).toBe(true); + expect((screen.getByText('保存报价').closest('button') as HTMLButtonElement).disabled).toBe(true); + expect(screen.getByRole('note').textContent).toContain('已超过报价截止时间'); + }); +}); diff --git a/src/pages/orders/BidInvitationsPage.tsx b/src/pages/orders/BidInvitationsPage.tsx new file mode 100644 index 0000000..a0c2369 --- /dev/null +++ b/src/pages/orders/BidInvitationsPage.tsx @@ -0,0 +1,543 @@ +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { RefreshCcw, RefreshCw } from 'lucide-react'; +import { MenuLabel } from '../../components/MenuLabel'; +import { Button } from '../../components/ui/Button'; +import { Modal } from '../../components/ui/Modal'; +import { ListState, PageHeader } from '../../components/ui/PagePrimitives'; +import { TablePaginationBar } from '../../components/ui/TablePaginationBar'; +import { notify } from '../../utils/notify'; +import { useI18n } from '../../i18n/I18nProvider'; +import { UI_LOCALE_BCP47, type UiLocale } from '../../i18n/config'; +import { + getMainSystemBidInvitationApi, + listMainSystemBidInvitationsApi, + submitMainSystemBidQuotesApi, + syncMainSystemBidInvitationsApi, + type BidInvitationDetailDto, + type BidInvitationDto, + type BidInvitationItemDto, + type BidInvitationQuoteInput, + type BidLocalStatus, +} from '../../utils/workflowApi'; + +/** + * Web「待报价」(主系统竞价)。 + * + * 口径(docs/design/20261017-主系统竞价待报价与报价提交.md §6): + * · 我方**只报价、不定标**;竞价/中标事实源在主系统,本页只读镜像 + 回传单价; + * · 一张表:竞价单号 / 竞价标题 / 商品数 / 报价截止 / 状态 / 操作; + * · 顶部只有「同步」(拉取兜底)与「刷新」(重读清单),没有状态筛选、没有本地竞价管理; + * · 弹窗逐行填单价(step 0.0001,必须 > 0),一次提交全部已填行;中标价只读; + * · 已截止(`deadlinePassed`)/ 不可报(`canQuote=false`)/ 已中标、未中标、已截止、已取消 + * ⇒ 整张弹窗只读,保存按钮禁用并给一句原因(不隐藏,避免"凭空消失")。 + */ + +const LIST_LIMIT = 50; +const DEFAULT_PAGE_SIZE = 20; +/** 「刷新」防连点:同一时间窗内的重复点击直接忽略(列表本身也有 loading 在途锁) */ +const REFRESH_LOCK_MS = 400; + +/** 终态:这些状态下弹窗一律只读(expired 仍可打开看历史) */ +const READONLY_LOCAL_STATUSES: readonly BidLocalStatus[] = ['won', 'lost', 'expired', 'cancelled']; + +/** 操作列文案:终态是「查看」,其余是「报价」 */ +const VIEW_ONLY_LOCAL_STATUSES: readonly BidLocalStatus[] = ['won', 'lost', 'cancelled']; + +const STATUS_LABEL_KEYS: Record = { + pending: 'bids.invite.statusPending', + quoted: 'bids.invite.statusQuoted', + expired: 'bids.invite.statusExpired', + won: 'bids.invite.statusWon', + lost: 'bids.invite.statusLost', + cancelled: 'bids.invite.statusCancelled', +}; + +/** 行内状态徽标:配色沿用本项目 app-status-* 语义色 */ +const STATUS_CLASS: Record = { + pending: 'app-status-warning', + quoted: 'app-status-success', + expired: 'app-status-neutral', + won: 'app-status-success', + lost: 'app-status-neutral', + cancelled: 'app-status-info', +}; + +type BidDraft = { price: string; remark: string }; + +function isReadonlyDetail(detail: BidInvitationDetailDto): boolean { + return ( + detail.deadlinePassed === true || + detail.canQuote === false || + READONLY_LOCAL_STATUSES.includes(detail.invitation.localStatus) + ); +} + +/** 4 位小数以内的价格展示(对齐 `numeric(14,4)`,不要用 2 位小数的金额格式) */ +function formatUnitPrice(value: number | null | undefined, locale: UiLocale): string { + if (value === null || value === undefined) return '—'; + const amount = Number(value); + if (!Number.isFinite(amount)) return '—'; + return amount.toLocaleString(UI_LOCALE_BCP47[locale], { + minimumFractionDigits: 2, + maximumFractionDigits: 4, + }); +} + +export function BidInvitationsPage() { + const { t, locale } = useI18n(); + + const [rows, setRows] = useState([]); + const [loading, setLoading] = useState(false); + const [loadError, setLoadError] = useState(null); + const [syncing, setSyncing] = useState(false); + const [page, setPage] = useState(1); + const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE); + + /** 弹窗:`activeRoundId` 同时充当 open 判定;`detailSeqRef` 防"过期响应写进新弹窗" */ + const [activeRoundId, setActiveRoundId] = useState(null); + /** 该轮属于哪个主系统供应商编码(一个分公司可绑多个;同一轮可能有两行邀约) */ + const [activeSupplierCode, setActiveSupplierCode] = useState(null); + const [detailTitle, setDetailTitle] = useState(''); + const [detail, setDetail] = useState(null); + const [detailLoading, setDetailLoading] = useState(false); + const [drafts, setDrafts] = useState>({}); + /** `supplier_category_mismatch` 要标红的行(其余行保留可继续报) */ + const [mismatchSkus, setMismatchSkus] = useState([]); + const [saving, setSaving] = useState(false); + + const detailSeqRef = useRef(0); + const refreshLockRef = useRef(0); + + const load = useCallback(async () => { + setLoading(true); + try { + const result = await listMainSystemBidInvitationsApi({ status: 'all', limit: LIST_LIMIT }); + setRows(Array.isArray(result?.data) ? result.data : []); + setLoadError(null); + } catch (error: any) { + setRows([]); + setLoadError(error?.message || t('bids.invite.empty')); + } finally { + setLoading(false); + } + }, [t]); + + useEffect(() => { + void load(); + }, [load]); + + /** 用服务端返回的邀约行覆盖清单里的同一行(同轮多 supplier_code 时按 roundId+supplierCode 精确匹配) */ + const mergeInvitationRow = useCallback((invitation: BidInvitationDto) => { + setRows((prev) => + prev.map((row) => + row.roundId === invitation.roundId && row.supplierCode === invitation.supplierCode + ? invitation + : row + ) + ); + }, []); + + const buildDrafts = (items: BidInvitationItemDto[]): Record => { + const next: Record = {}; + for (const item of items) { + next[item.skuCode] = { + price: item.unitPrice === null || item.unitPrice === undefined ? '' : String(item.unitPrice), + remark: item.remark ?? '', + }; + } + return next; + }; + + const closeDetail = () => { + // 递增序号 ⇒ 已在途的详情/提交响应一律丢弃(防写进下一次打开) + detailSeqRef.current += 1; + setActiveRoundId(null); + setActiveSupplierCode(null); + setDetailTitle(''); + setDetail(null); + setDetailLoading(false); + setDrafts({}); + setMismatchSkus([]); + }; + + const openDetail = async (row: BidInvitationDto) => { + const seq = (detailSeqRef.current += 1); + setActiveRoundId(row.roundId); + // 多绑定:同一轮可能有两条邀约(不同 supplier),必须按行带上编码,后端才不猜 + setActiveSupplierCode(row.supplierCode); + setDetailTitle(row.roundCode || row.roundId); + setDetail(null); + setDrafts({}); + setMismatchSkus([]); + setDetailLoading(true); + try { + const view = await getMainSystemBidInvitationApi(row.roundId, row.supplierCode); + if (seq !== detailSeqRef.current) return; + setDetail(view); + setDetailTitle(view.invitation.roundCode || row.roundCode || row.roundId); + setDrafts(buildDrafts(view.items)); + mergeInvitationRow(view.invitation); + } catch (error: any) { + if (seq !== detailSeqRef.current) return; + // 拉不到详情就收起弹窗(否则会露出"空态"文案,与真实原因不符) + notify.error(error?.message || t('bids.invite.empty')); + closeDetail(); + } finally { + if (seq === detailSeqRef.current) setDetailLoading(false); + } + }; + + const handleRefresh = () => { + const now = Date.now(); + if (loading || now - refreshLockRef.current < REFRESH_LOCK_MS) return; + refreshLockRef.current = now; + void load(); + }; + + const handleSync = async () => { + if (syncing || loading) return; + setSyncing(true); + try { + await syncMainSystemBidInvitationsApi(); + await load(); + } catch (error: any) { + notify.error(error?.message || t('bids.invite.empty')); + } finally { + setSyncing(false); + } + }; + + const readonly = detail ? isReadonlyDetail(detail) : false; + + /** + * 只读时给一句原因(**只复用已批准文案**,不自造小字): + * 过了截止 → 「已超过报价截止时间」;否则用该行状态名(已中标 / 未中标 / 已截止 / 已取消)。 + */ + const readonlyReason = (() => { + if (!detail) return ''; + if (detail.deadlinePassed === true) return t('bids.invite.deadlinePassed'); + if (READONLY_LOCAL_STATUSES.includes(detail.invitation.localStatus)) { + return t(STATUS_LABEL_KEYS[detail.invitation.localStatus]); + } + if (detail.canQuote === false) return t(STATUS_LABEL_KEYS.expired); + return ''; + })(); + + const filledQuotes = useMemo(() => { + if (!detail) return []; + const quotes: BidInvitationQuoteInput[] = []; + for (const item of detail.items) { + const draft = drafts[item.skuCode]; + const rawPrice = (draft?.price ?? '').trim(); + if (!rawPrice) continue; + const remark = (draft?.remark ?? '').trim(); + quotes.push({ + skuCode: item.skuCode, + unitPrice: Number(rawPrice), + ...(remark ? { remark } : {}), + }); + } + return quotes; + }, [detail, drafts]); + + const handleSaveQuotes = async () => { + if (!detail || !activeRoundId || readonly || saving || detailLoading) return; + if (!filledQuotes.length) return; + const seq = detailSeqRef.current; + setSaving(true); + try { + const view = await submitMainSystemBidQuotesApi(activeRoundId, filledQuotes, activeSupplierCode); + if (seq !== detailSeqRef.current) return; + setDetail(view); + setDetailTitle(view.invitation.roundCode || detailTitle); + setDrafts(buildDrafts(view.items)); + setMismatchSkus([]); + mergeInvitationRow(view.invitation); + notify.success(t('bids.invite.toastSubmitted')); + } catch (error: any) { + if (seq !== detailSeqRef.current) return; + /** + * ⚠️ 契约只回 `{ error, error_description }`(没有逐行 `sku_code`),所以"该行"只能按 + * 错误文案里出现的 skuCode 反查;反查不到就不标红(其它行照旧可继续报)。 + */ + if (error?.code === 'supplier_category_mismatch') { + const message = String(error?.error_description || error?.message || ''); + const marked = filledQuotes + .map((quote) => quote.skuCode) + .filter((skuCode) => skuCode && message.includes(skuCode)); + setMismatchSkus(marked); + } + notify.error(error?.message || t('bids.invite.empty')); + } finally { + setSaving(false); + } + }; + + const formatTime = (value: string | null | undefined) => { + const raw = String(value || '').trim(); + if (!raw) return '-'; + const date = new Date(raw); + return Number.isNaN(date.getTime()) ? raw : date.toLocaleString(UI_LOCALE_BCP47[locale]); + }; + + const totalPages = Math.max(1, Math.ceil(rows.length / pageSize) || 1); + const visibleRows = useMemo(() => { + const safePage = Math.min(page, totalPages); + return rows.slice((safePage - 1) * pageSize, safePage * pageSize); + }, [rows, page, pageSize, totalPages]); + + useEffect(() => { + if (page > totalPages) setPage(totalPages); + }, [page, totalPages]); + + return ( +
+ + + + } + actions={ + <> + + + + } + /> + +
+ + + + + + + + + + + + + {loading && rows.length === 0 ? ( + + + + ) : null} + {!loading && loadError ? ( + + + + ) : null} + {!loading && !loadError && rows.length === 0 ? ( + + + + ) : null} + {visibleRows.map((row) => { + const viewOnly = VIEW_ONLY_LOCAL_STATUSES.includes(row.localStatus); + return ( + + + + + + + + + ); + })} + +
+ {t('bids.invite.colRoundNo')} + + {t('bids.invite.colTitle')} + + {t('bids.invite.colItemCount')} + + {t('bids.invite.colDeadline')} + + {t('bids.col.status')} + + {t('bids.col.actions')} +
+ +
+ void load()} /> +
+ +
{row.roundCode || '-'} +
{row.roundTitle || '-'}
+
{row.itemCount} + {formatTime(row.respondDeadline)} + + + {t(STATUS_LABEL_KEYS[row.localStatus])} + + + +
+ { + setPageSize(size); + setPage(1); + }} + /> +
+ + { + if (!saving) closeDetail(); + }} + className="max-w-4xl" + footer={ + <> + + + + } + > + {detailLoading ? : null} + {!detailLoading && detail ? ( +
+
+ + {t('bids.invite.colDeadline')}:{formatTime(detail.invitation.respondDeadline)} + + {readonly && readonlyReason ? ( + + {readonlyReason} + + ) : null} +
+
+ + + + + + + + + + + + {detail.items.map((item) => { + const label = item.skuName || item.skuCode; + const draft = drafts[item.skuCode] || { price: '', remark: '' }; + const mismatch = mismatchSkus.includes(item.skuCode); + return ( + + + + + + + + ); + })} + +
+ {t('bids.invite.colItem')} + + {t('bids.invite.colUnit')} + + {t('bids.invite.colMyPrice')} + + {t('bids.invite.colAwardPrice')} + + {t('bids.invite.colRemark')} +
+
{label}
+
+ {item.unit || '-'} + + + setDrafts((prev) => ({ + ...prev, + [item.skuCode]: { ...(prev[item.skuCode] || { remark: '' }), price: event.target.value }, + })) + } + /> + + {formatUnitPrice(item.awardPrice, locale)} + + + setDrafts((prev) => ({ + ...prev, + [item.skuCode]: { ...(prev[item.skuCode] || { price: '' }), remark: event.target.value }, + })) + } + /> +
+
+
+ ) : null} + {!detailLoading && !detail ? : null} +
+
+ ); +} + +export default BidInvitationsPage; diff --git a/src/utils/menuLayout.newMenu.test.ts b/src/utils/menuLayout.newMenu.test.ts index 7c424e0..3e1cb3d 100644 --- a/src/utils/menuLayout.newMenu.test.ts +++ b/src/utils/menuLayout.newMenu.test.ts @@ -290,6 +290,7 @@ describe('导航模板收敛:以主系统当前布局为模板', () => { 'purchase-list', 'purchase-preparations', 'orders-price-qty', + 'orders-bid-invitations', 'inspection-list', 'inspection-processing', 'picking', diff --git a/src/utils/menuLayout.ts b/src/utils/menuLayout.ts index 23b4480..6b3c78f 100644 --- a/src/utils/menuLayout.ts +++ b/src/utils/menuLayout.ts @@ -84,7 +84,8 @@ const BUSINESS_FLOW_GROUP_LABEL = '业务流程'; * * 主系统模板把**全部作业类**菜单都收在「业务流程」里(订单 / 采购 / 验收 / 分拣 / 配送 / * 售后 / 异常),顶层只剩:数据看板、订单录入 + 业务流程 / 基础数据 / 财务结算 / 系统管理。 - * 我方差异只有一条:`orders-price-qty`(跨系统改价/改量**申请**;主系统那边是「待审」)。 + * 我方差异只有两条:`orders-price-qty`(跨系统改价/改量**申请**;主系统那边是「待审」)、 + * `orders-bid-invitations`(主系统竞价「待报价」,我方只报价不定标)。 */ const BUSINESS_FLOW_CANONICAL_ITEMS: NavSecondaryItemConfig[] = [ { menuKey: 'orders-list', visible: true }, @@ -92,6 +93,8 @@ const BUSINESS_FLOW_CANONICAL_ITEMS: NavSecondaryItemConfig[] = [ { menuKey: 'purchase-preparations', visible: true }, // 跨系统改价/改量申请:用户 2026-10-11 指定排在「供应商备货表」下方(勿动位置) { menuKey: 'orders-price-qty', visible: true, afterMenuKey: 'purchase-preparations' }, + // 主系统竞价「待报价」(2026-10-17):紧跟供需变更审核,存量布局归一化时自动补上 + { menuKey: 'orders-bid-invitations', visible: true }, { menuKey: 'inspection-list', visible: true }, { menuKey: 'inspection-processing', visible: true }, { menuKey: 'picking', visible: true }, diff --git a/src/utils/workflowApi.ts b/src/utils/workflowApi.ts index 3984ae3..6a5e5ae 100644 --- a/src/utils/workflowApi.ts +++ b/src/utils/workflowApi.ts @@ -6742,3 +6742,123 @@ export async function saveAllowZeroCostConfigApi(enabled: boolean) { body: JSON.stringify({ enabled }), }); } + +/* ──────────────────────────────────────────────────────────────────────────── + * 主系统竞价「待报价」台账(镜像 + 我方报价回传) + * + * 口径(docs/design/20261017-主系统竞价待报价与报价提交.md): + * · 事实源在主系统;我方只读镜像、只报单价,不定标、不比价; + * · 全部 DTO **camelCase**(后端已在接口层映射好),不要改成 snake_case; + * · 四个接口都在 `/api/workflow/main-system/bid-invitations` 下(`workflowFetch` 已拼前缀)。 + * ──────────────────────────────────────────────────────────────────────────── */ + +/** 我方视图状态:`pending` 待报价 / `quoted` 已报价 / `expired` 已截止 / 中标结果三态 */ +export type BidLocalStatus = 'pending' | 'quoted' | 'expired' | 'won' | 'lost' | 'cancelled'; + +/** 邀约行(一个分公司 × 一个 supplier_code × 一轮竞价) */ +export interface BidInvitationDto { + roundId: string; + roundCode: string | null; + roundTitle: string | null; + orderCode: string | null; + supplierCode: string; + /** ISO 时间或 `null`(无截止时间) */ + respondDeadline: string | null; + itemCount: number; + /** 对方事实状态 */ + roundStatus: 'open' | 'closed' | 'awarded' | 'cancelled'; + /** 我方视图状态 */ + localStatus: BidLocalStatus; + quotedAt: string | null; + lastSyncedAt: string | null; +} + +/** 单轮明细行(含我方报价与中标结果,全部只读字段由对方返回覆盖) */ +export interface BidInvitationItemDto { + skuCode: string; + skuName: string | null; + unit: string | null; + unitPrice: number | null; + remark: string | null; + quotedAt: string | null; + awardPrice: number | null; + awardQty: number | null; + awardStatus: 'won' | 'lost' | null; +} + +/** 列表汇总(`closed` = 已截止 + 已定标 + 已取消,后端口径) */ +export interface BidInvitationSummary { + pending: number; + quoted: number; + expired: number; + closed: number; +} + +/** 单轮视图:`canQuote=false` / `deadlinePassed=true` ⇒ 页面置只读 */ +export interface BidInvitationDetailDto { + invitation: BidInvitationDto; + items: BidInvitationItemDto[]; + canQuote: boolean; + deadlinePassed: boolean; + syncError: string | null; +} + +/** 报价提交行:`unitPrice` 必须 > 0、最多 4 位小数(后端校验) */ +export interface BidInvitationQuoteInput { + skuCode: string; + unitPrice: number; + remark?: string; +} + +/** 待报价清单(本地镜像)。`status=history` = 已截止/已定标/已取消 */ +export async function listMainSystemBidInvitationsApi(params?: { + status?: 'all' | 'pending' | 'history'; + limit?: number; +}) { + const query = new URLSearchParams(); + if (params?.status) query.set('status', params.status); + if (params?.limit) query.set('limit', String(params.limit)); + const suffix = query.toString() ? `?${query.toString()}` : ''; + return workflowFetch<{ + data: BidInvitationDto[]; + summary: BidInvitationSummary; + error: null; + }>(`/main-system/bid-invitations${suffix}`); +} + +/** 拉取兜底:对每个生效绑定调主系统列表接口补台账(webhook 漏推时用) */ +export async function syncMainSystemBidInvitationsApi() { + return workflowFetch<{ + synced: number; + skipped: number; + unavailable: number; + enabled: boolean; + error: null; + }>('/main-system/bid-invitations/sync', { method: 'POST' }); +} + +/** 打开某一轮:拉对方 ② 刷新单轮后返回明细 + 我的报价 + 我的中标 */ +export async function getMainSystemBidInvitationApi(roundId: string, supplierCode?: string | null) { + const suffix = supplierCode ? `?supplier=${encodeURIComponent(supplierCode)}` : ''; + return workflowFetch<{ data: BidInvitationDetailDto; error: null }>( + `/main-system/bid-invitations/${encodeURIComponent(roundId)}${suffix}` + ).then((res) => res.data); +} + +/** + * 提交报价(批量 upsert,只回我自己视角)。 + * + * ⚠️ `preserveErrorBody: true`:5xx/网关错误要保留后端 `error` / `error_description` + * (如 `supplier_category_mismatch` / `bid_not_open`),否则会被统一的「保存超时」吞掉。 + */ +export async function submitMainSystemBidQuotesApi( + roundId: string, + quotes: BidInvitationQuoteInput[], + supplierCode?: string | null +) { + return workflowFetch<{ data: BidInvitationDetailDto; error?: null }>( + `/main-system/bid-invitations/${encodeURIComponent(roundId)}/quotes`, + { method: 'POST', body: JSON.stringify(supplierCode ? { quotes, supplierCode } : { quotes }) }, + { preserveErrorBody: true } + ).then((res) => res.data); +}