feat(竞价报价): 接主系统「待报价」推送并回传单价(我方只报价、不定标)
开发者 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 红(均基线)
This commit is contained in:
@@ -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": "<uuid>",
|
||||
"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": "<uuid>",
|
||||
"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`)。
|
||||
@@ -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)。
|
||||
|
||||
---
|
||||
|
||||
## 设计文档版本与保留策略
|
||||
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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<ReturnType<typeof getWorkflowCtx>>) {
|
||||
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, '提交报价失败');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<MainSystemResult<unknown>, { 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<T>(
|
||||
supplierCode: string,
|
||||
call: (token: string) => Promise<MainSystemResult<T>>
|
||||
): Promise<MainSystemResult<T>> {
|
||||
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<MainBidListOutcome> {
|
||||
if (!isMainSystemIntegrationEnabled()) {
|
||||
return { kind: 'not_configured', status: 0, code: 'not_configured', reason: '主系统对接未配置' };
|
||||
}
|
||||
const result = await callWithToken<any>(supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
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<MainBidDetailOutcome> {
|
||||
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<any>(supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
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<MainBidDetailOutcome> {
|
||||
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<any>(input.supplierCode, (token) =>
|
||||
requestMainSystem<any>({
|
||||
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)),
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -57,6 +57,20 @@ export function mainSystemLookupPath(): string {
|
||||
|
||||
export type MainSystemQuery = Record<string, string | number | boolean | null | undefined>;
|
||||
|
||||
/**
|
||||
* 竞价的**子路径**:`{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();
|
||||
|
||||
@@ -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<T>(fn: (client: any) => Promise<T>): Promise<T> {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await fn(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
try {
|
||||
await client.query('ROLLBACK');
|
||||
} catch {
|
||||
/* 回滚失败不掩盖原始异常 */
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重算 `local_status`(唯一写入口:所有会改变事实的路径写完都调它一次)。
|
||||
*
|
||||
* 为什么不写在 SQL 里:派生口径要与页面/测试**同一份实现**,写进 SQL 就等于藏了第二份口径。
|
||||
*/
|
||||
async function recomputeLocalStatus(client: any, invitationId: string): Promise<BidLocalStatus> {
|
||||
const { rows } = await client.query(
|
||||
`SELECT i.round_status,
|
||||
i.main_invitation_status,
|
||||
i.respond_deadline,
|
||||
i.item_count,
|
||||
(SELECT COUNT(*)::int FROM public.main_system_bid_invitation_items it
|
||||
WHERE it.invitation_id = i.id AND it.unit_price IS NOT NULL) AS quoted_count,
|
||||
EXISTS (SELECT 1 FROM public.main_system_bid_invitation_items it
|
||||
WHERE it.invitation_id = i.id AND it.award_status = 'won') AS has_award,
|
||||
(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<string> {
|
||||
const { rows } = await client.query(
|
||||
`INSERT INTO public.main_system_bid_invitations AS i
|
||||
(branch_code, supplier_code, round_id, round_code, round_title, order_code,
|
||||
respond_deadline, item_count, round_status, main_invitation_status,
|
||||
webhook_received_at, last_synced_at, sync_error, payload)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, 0), COALESCE($9, 'open'), $10,
|
||||
CASE WHEN $11::boolean THEN NOW() ELSE NULL END,
|
||||
CASE WHEN $12::boolean THEN NOW() ELSE NULL END,
|
||||
NULL, $14::jsonb)
|
||||
ON CONFLICT (branch_code, round_id, supplier_code) DO UPDATE SET
|
||||
round_code = COALESCE(EXCLUDED.round_code, i.round_code),
|
||||
round_title = COALESCE(EXCLUDED.round_title, i.round_title),
|
||||
order_code = COALESCE(EXCLUDED.order_code, i.order_code),
|
||||
respond_deadline = COALESCE(EXCLUDED.respond_deadline, i.respond_deadline),
|
||||
-- 权威来源(拉详情 / 带明细的推送)按实际行数覆盖;退化载荷(无明细)只增不减
|
||||
item_count = CASE
|
||||
WHEN $12::boolean OR $13::boolean THEN EXCLUDED.item_count
|
||||
ELSE GREATEST(i.item_count, EXCLUDED.item_count)
|
||||
END,
|
||||
-- 已截标/已定标/已取消是**终态事实**:迟到的补投(含 webhook 硬编码的 open)
|
||||
-- 不得把它们改回 open —— 否则 canQuote 会误判为"还能报"
|
||||
round_status = CASE
|
||||
WHEN i.round_status IN ('closed', 'awarded', 'cancelled') THEN i.round_status
|
||||
ELSE COALESCE(EXCLUDED.round_status, i.round_status)
|
||||
END,
|
||||
main_invitation_status = COALESCE(EXCLUDED.main_invitation_status, i.main_invitation_status),
|
||||
webhook_received_at = CASE WHEN $11::boolean THEN NOW() ELSE i.webhook_received_at END,
|
||||
last_synced_at = CASE WHEN $12::boolean THEN NOW() ELSE i.last_synced_at END,
|
||||
-- 同步/刷新成功 ⇒ 清掉历史失败原因(失败原因不清就等于"没同步成功过"永远留着)
|
||||
sync_error = CASE WHEN $12::boolean THEN NULL ELSE i.sync_error END,
|
||||
payload = COALESCE(EXCLUDED.payload, i.payload),
|
||||
updated_at = NOW()
|
||||
RETURNING i.id`,
|
||||
[
|
||||
input.branchCode,
|
||||
input.supplierCode,
|
||||
input.roundId,
|
||||
input.roundCode ?? null,
|
||||
input.roundTitle ?? null,
|
||||
input.orderCode ?? null,
|
||||
input.respondDeadline ?? null,
|
||||
input.itemCount ?? 0,
|
||||
input.roundStatus ?? 'open',
|
||||
input.mainInvitationStatus ?? null,
|
||||
input.fromWebhook === true,
|
||||
input.fromSync === true,
|
||||
input.fromDetailItems === true,
|
||||
input.payload === undefined || input.payload === null ? null : JSON.stringify(input.payload),
|
||||
]
|
||||
);
|
||||
return String(rows[0]?.id || '');
|
||||
}
|
||||
|
||||
async function upsertItemIdentity(
|
||||
client: any,
|
||||
input: {
|
||||
invitationId: string;
|
||||
branchCode: string;
|
||||
roundId: string;
|
||||
skuCode: string;
|
||||
skuName?: string | null;
|
||||
unit?: string | null;
|
||||
}
|
||||
): Promise<void> {
|
||||
await client.query(
|
||||
`INSERT INTO public.main_system_bid_invitation_items AS it
|
||||
(invitation_id, branch_code, round_id, sku_code, sku_name, unit)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT (invitation_id, sku_code) DO UPDATE SET
|
||||
sku_name = COALESCE(EXCLUDED.sku_name, it.sku_name),
|
||||
unit = COALESCE(EXCLUDED.unit, it.unit),
|
||||
updated_at = NOW()`,
|
||||
[input.invitationId, input.branchCode, input.roundId, input.skuCode, input.skuName ?? null, input.unit ?? null]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收 `bid.opened`:落邀约头 + 商品名(**不写价格**)。
|
||||
*
|
||||
* 幂等:同一 `(branch, round, supplier)` 重复推送只更新一行;商品行按 `(invitation_id, sku_code)` upsert。
|
||||
* 退化载荷(`items: []`,对方读明细失败时只推轮次头)也照常落头 —— 页面点开时会再拉详情补齐。
|
||||
*/
|
||||
export async function recordBidOpened(input: {
|
||||
branchCode: string;
|
||||
supplierCode: string;
|
||||
payload: BidOpenedPayload;
|
||||
}): Promise<{
|
||||
status: 'recorded' | 'ignored';
|
||||
roundId?: string;
|
||||
roundCode?: string | null;
|
||||
itemCount?: number;
|
||||
localStatus?: BidLocalStatus;
|
||||
reason?: string;
|
||||
}> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const declaredSupplier = String(input.supplierCode || '').trim();
|
||||
const roundId = toText(input.payload?.round_id, 128);
|
||||
if (!branchCode || !declaredSupplier) return { status: 'ignored', reason: 'missing_branch_or_supplier' };
|
||||
if (!roundId) return { status: 'ignored', reason: 'missing_round_id' };
|
||||
// 形态与查询/提交侧同一口径(`[0-9A-Za-z_-]{1,64}`):不合约的 round_id 落进来只会变成
|
||||
// 一行"点不开、提交不了"的僵尸台账,因此入口就忽略(tester F3)。
|
||||
if (!/^[0-9A-Za-z_-]{1,64}$/.test(roundId)) return { status: 'ignored', reason: 'invalid_round_id' };
|
||||
|
||||
/**
|
||||
* **编码校验 + 规范化**(2026-10-17 红队 #10):
|
||||
* 推送只认该分公司**生效绑定**里的 supplier_code(大小写不敏感匹配,存绑定里的写法)。
|
||||
* 为什么:`bid_invitations` 是按 `(轮次 × supplier_code)` 的,若把 `sup123` 与 `SUP123` 当成两个键,
|
||||
* 同一轮会裂成两行、页面出现重复待办;而完全不校验则任何签名齐全的载荷都能落一行陌生编码。
|
||||
* ⚠️ 读不到绑定(空列表 = 未绑定/查询失败)时**不拦**:那是环境的已知状态,不是本事件的错。
|
||||
*/
|
||||
let supplierCode = declaredSupplier;
|
||||
try {
|
||||
const bound = await listSupplierCodesForBranch(branchCode);
|
||||
if (bound.length) {
|
||||
const canonical = bound.find(
|
||||
(code) => String(code).trim().toUpperCase() === declaredSupplier.toUpperCase()
|
||||
);
|
||||
if (!canonical) {
|
||||
return { status: 'ignored', reason: 'supplier_not_bound' };
|
||||
}
|
||||
supplierCode = String(canonical).trim();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[bid] 校验 supplier_code 绑定失败(不阻断落库):', (error as Error)?.message || error);
|
||||
}
|
||||
|
||||
const rawItems = Array.isArray(input.payload?.items) ? (input.payload?.items as any[]) : [];
|
||||
const items: Array<{ skuCode: string; skuName: string | null; unit: string | null }> = [];
|
||||
const seenSkus = new Set<string>();
|
||||
for (const row of rawItems) {
|
||||
const skuCode = toText(row?.sku_code, 120) || '';
|
||||
if (!skuCode || seenSkus.has(skuCode)) continue; // 去重:同一 SKU 重复出现只算一行(红队 #7)
|
||||
seenSkus.add(skuCode);
|
||||
items.push({
|
||||
skuCode,
|
||||
skuName: toText(row?.sku_name, 255),
|
||||
unit: toText(row?.unit, 32),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 数量口径(红队 #7):**只认去重后的实际明细行数**。
|
||||
*
|
||||
* 为什么不采信载荷里的 `item_count`:① 它可能含重复 SKU/对方已删的行,
|
||||
* 会让"列表显示 3 件、点开只有 2 件";② 对方读明细失败时退化推送的 `items` 是空数组,
|
||||
* 此时按声明值写就把一个不可信的数字记成了事实。退化推送一律按 0 写(`GREATEST` 保住旧值)。
|
||||
*/
|
||||
const itemCount = items.length;
|
||||
|
||||
return withTransaction(async (client) => {
|
||||
const invitationId = await upsertInvitationHeader(client, {
|
||||
branchCode,
|
||||
supplierCode,
|
||||
roundId,
|
||||
roundCode: toText(input.payload?.round_code, 128),
|
||||
// 载荷里没有标题(对方只给 round_code);标题留空,等拉详情补
|
||||
orderCode: toText(input.payload?.order_code, 128),
|
||||
respondDeadline: toIso(input.payload?.respond_deadline as any),
|
||||
itemCount,
|
||||
roundStatus: 'open',
|
||||
fromWebhook: true,
|
||||
fromDetailItems: items.length > 0,
|
||||
payload: input.payload,
|
||||
});
|
||||
for (const item of items) {
|
||||
await upsertItemIdentity(client, {
|
||||
invitationId,
|
||||
branchCode,
|
||||
roundId,
|
||||
skuCode: item.skuCode,
|
||||
skuName: item.skuName,
|
||||
unit: item.unit,
|
||||
});
|
||||
}
|
||||
const localStatus = await recomputeLocalStatus(client, invitationId);
|
||||
return {
|
||||
status: 'recorded' as const,
|
||||
roundId,
|
||||
roundCode: toText(input.payload?.round_code, 128),
|
||||
itemCount,
|
||||
localStatus,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** 拉列表兜底能提供的字段(对方 `bid_invitations` ⋈ `bid_rounds` 的行) */
|
||||
export type BidListHeaderInput = {
|
||||
roundId: string;
|
||||
roundCode?: string | null;
|
||||
roundTitle?: string | null;
|
||||
orderCode?: string | null;
|
||||
respondDeadline?: string | null;
|
||||
itemCount?: number | null;
|
||||
roundStatus?: string | null;
|
||||
invitationStatus?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取兜底:只 upsert **邀约头**(对方列表接口不发明细)。
|
||||
* 明细/报价/中标由 `applyBidDetail()` 在"打开某一轮"时整轮对齐。
|
||||
*/
|
||||
export async function upsertInvitationHeaders(input: {
|
||||
branchCode: string;
|
||||
supplierCode: string;
|
||||
rows: BidListHeaderInput[];
|
||||
payload?: unknown;
|
||||
}): Promise<{ upserted: number }> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
if (!branchCode || !supplierCode) return { upserted: 0 };
|
||||
const rows = (input.rows || []).filter((row) => String(row?.roundId || '').trim());
|
||||
if (!rows.length) return { upserted: 0 };
|
||||
|
||||
return withTransaction(async (client) => {
|
||||
let upserted = 0;
|
||||
for (const row of rows) {
|
||||
const invitationId = await upsertInvitationHeader(client, {
|
||||
branchCode,
|
||||
supplierCode,
|
||||
roundId: String(row.roundId).trim(),
|
||||
roundCode: row.roundCode ?? null,
|
||||
roundTitle: row.roundTitle ?? null,
|
||||
orderCode: row.orderCode ?? null,
|
||||
respondDeadline: row.respondDeadline ?? null,
|
||||
itemCount: row.itemCount ?? 0,
|
||||
roundStatus: row.roundStatus ?? 'open',
|
||||
mainInvitationStatus: row.invitationStatus ?? null,
|
||||
fromSync: true,
|
||||
});
|
||||
if (invitationId) {
|
||||
await recomputeLocalStatus(client, invitationId);
|
||||
upserted += 1;
|
||||
}
|
||||
}
|
||||
return { upserted };
|
||||
});
|
||||
}
|
||||
|
||||
/** 对方详情视图(`GET /api/supplier/bids/:id` 的 `data`)—— 本文件只做落库,不做 HTTP */
|
||||
export type BidDetailInput = {
|
||||
round: {
|
||||
id?: unknown;
|
||||
round_code?: unknown;
|
||||
title?: unknown;
|
||||
order_code?: unknown;
|
||||
status?: unknown;
|
||||
respond_deadline?: unknown;
|
||||
} | null;
|
||||
invitation: { status?: unknown; respond_deadline?: unknown; quoted_at?: unknown } | null;
|
||||
items: Array<{ sku_code?: unknown; sku_name?: unknown; unit?: unknown }>;
|
||||
myQuotes: Array<{ sku_code?: unknown; unit_price?: unknown; remark?: unknown; updated_at?: unknown; created_at?: unknown }>;
|
||||
myAwards: Array<{ sku_code?: unknown; unit_price?: unknown }>;
|
||||
};
|
||||
|
||||
/**
|
||||
* **整轮对齐**(打开某一轮 / 提交成功后的返回都用它):
|
||||
* 明细、我方报价、我方中标一律「先清空再按对方返回重写」——
|
||||
* 否则对方撤回一条报价、或改判中标后,我方镜像会留着旧值(假事实)。
|
||||
*/
|
||||
export async function applyBidDetail(input: {
|
||||
branchCode: string;
|
||||
supplierCode: string;
|
||||
roundId: string;
|
||||
detail: BidDetailInput;
|
||||
payload?: unknown;
|
||||
}): Promise<{ invitationId: string; localStatus: BidLocalStatus }> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
const roundId = String(input.roundId || '').trim();
|
||||
if (!branchCode || !supplierCode || !roundId) {
|
||||
throw new Error('applyBidDetail 缺少 branchCode/supplierCode/roundId');
|
||||
}
|
||||
const round = input.detail?.round || {};
|
||||
const invitation = input.detail?.invitation || {};
|
||||
const items = (Array.isArray(input.detail?.items) ? input.detail.items : [])
|
||||
.map((row) => ({
|
||||
skuCode: toText(row?.sku_code, 120) || '',
|
||||
skuName: toText(row?.sku_name, 255),
|
||||
unit: toText(row?.unit, 32),
|
||||
}))
|
||||
.filter((row) => Boolean(row.skuCode));
|
||||
const quotes = (Array.isArray(input.detail?.myQuotes) ? input.detail.myQuotes : [])
|
||||
.map((row) => ({
|
||||
skuCode: toText(row?.sku_code, 120) || '',
|
||||
unitPrice: toNumber(row?.unit_price),
|
||||
remark: toText(row?.remark),
|
||||
quotedAt: toIso((row?.updated_at as any) || (row?.created_at as any)),
|
||||
}))
|
||||
.filter((row) => Boolean(row.skuCode) && row.unitPrice !== null);
|
||||
const awards = (Array.isArray(input.detail?.myAwards) ? input.detail.myAwards : [])
|
||||
.map((row) => ({
|
||||
skuCode: toText(row?.sku_code, 120) || '',
|
||||
unitPrice: toNumber(row?.unit_price),
|
||||
}))
|
||||
.filter((row) => Boolean(row.skuCode));
|
||||
|
||||
return withTransaction(async (client) => {
|
||||
const invitationId = await upsertInvitationHeader(client, {
|
||||
branchCode,
|
||||
supplierCode,
|
||||
roundId,
|
||||
roundCode: toText(round.round_code, 128),
|
||||
roundTitle: toText(round.title, 255),
|
||||
orderCode: toText(round.order_code, 128),
|
||||
respondDeadline: toIso((round.respond_deadline as any) || (invitation.respond_deadline as any)),
|
||||
itemCount: items.length,
|
||||
roundStatus: toText(round.status, 20) || 'open',
|
||||
mainInvitationStatus: toText(invitation.status, 20),
|
||||
fromSync: true,
|
||||
fromDetailItems: true,
|
||||
payload: input.payload ?? input.detail,
|
||||
});
|
||||
|
||||
/**
|
||||
* 对方视图里已不存在的商品行 ⇒ 删掉(避免页面出现"对方已经没有的行")。
|
||||
* ⚠️ **即使 `items` 是空数组也要删**:能走到这里说明响应是**可识别**的
|
||||
* (`isDegenerateDetail` 已在 api 层挡掉"既无轮次又无明细"的那种),
|
||||
* 此时"0 行明细"本身就是事实;若跳过删除,头会写 0 行而明细还留着旧行/旧价,
|
||||
* 页面又按明细行数展示 ⇒ 显示的是对方已经删掉的东西(tester F2)。
|
||||
*/
|
||||
await client.query(
|
||||
`DELETE FROM public.main_system_bid_invitation_items
|
||||
WHERE invitation_id = $1 AND NOT (sku_code = ANY($2::text[]))`,
|
||||
[invitationId, items.map((row) => row.skuCode)]
|
||||
);
|
||||
|
||||
for (const item of items) {
|
||||
await upsertItemIdentity(client, {
|
||||
invitationId,
|
||||
branchCode,
|
||||
roundId,
|
||||
skuCode: item.skuCode,
|
||||
skuName: item.skuName,
|
||||
unit: item.unit,
|
||||
});
|
||||
}
|
||||
|
||||
// 报价与中标:先清空再写(对方撤回/改判要能体现)
|
||||
await client.query(
|
||||
`UPDATE public.main_system_bid_invitation_items
|
||||
SET unit_price = NULL, remark = NULL, quoted_at = NULL, updated_at = NOW()
|
||||
WHERE invitation_id = $1 AND unit_price IS NOT NULL`,
|
||||
[invitationId]
|
||||
);
|
||||
for (const quote of quotes) {
|
||||
await client.query(
|
||||
`UPDATE public.main_system_bid_invitation_items AS it
|
||||
SET unit_price = $3, remark = $4, quoted_at = COALESCE($5, it.quoted_at), updated_at = NOW()
|
||||
WHERE it.invitation_id = $1 AND it.sku_code = $2`,
|
||||
[invitationId, quote.skuCode, quote.unitPrice, quote.remark, quote.quotedAt]
|
||||
);
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`UPDATE public.main_system_bid_invitation_items
|
||||
SET award_price = NULL, award_qty = NULL, award_status = NULL, updated_at = NOW()
|
||||
WHERE invitation_id = $1 AND (award_price IS NOT NULL OR award_status IS NOT NULL)`,
|
||||
[invitationId]
|
||||
);
|
||||
for (const award of awards) {
|
||||
await client.query(
|
||||
`UPDATE public.main_system_bid_invitation_items AS it
|
||||
SET award_price = $3, award_status = 'won', updated_at = NOW()
|
||||
WHERE it.invitation_id = $1 AND it.sku_code = $2`,
|
||||
[invitationId, award.skuCode, award.unitPrice]
|
||||
);
|
||||
}
|
||||
|
||||
const localStatus = await recomputeLocalStatus(client, invitationId);
|
||||
return { invitationId, localStatus };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按轮次定位台账行。
|
||||
*
|
||||
* ⚠️ 一个分公司可能绑**多个 supplier_code**,同一轮可能同时邀请两个编码 ⇒ `(branch, round)` 可能命中多行。
|
||||
* 因此:
|
||||
* · 调用方带了 `supplierCode` ⇒ 精确匹配该行(前端列表里每行都带它,正常路径都走这条);
|
||||
* · 没带且只有一行 ⇒ 就用它(单绑定的常见情况);
|
||||
* · 没带且多行 ⇒ 返回 `ambiguous`,由调用方提示"请从清单里点具体那条",**绝不猜**(猜错会以另一家身份报价)。
|
||||
*/
|
||||
export async function findInvitationByRound(input: {
|
||||
branchCode: string;
|
||||
roundId: string;
|
||||
supplierCode?: string | null;
|
||||
}): Promise<
|
||||
| { kind: 'found'; row: BidInvitationRow }
|
||||
| { kind: 'missing' }
|
||||
| { kind: 'ambiguous'; supplierCodes: string[] }
|
||||
> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const roundId = String(input.roundId || '').trim();
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
if (!branchCode || !roundId) return { kind: 'missing' };
|
||||
if (supplierCode) {
|
||||
const { rows } = await pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 AND round_id = $2 AND upper(supplier_code) = upper($3)
|
||||
LIMIT 1`,
|
||||
[branchCode, roundId, supplierCode]
|
||||
);
|
||||
return rows[0] ? { kind: 'found', row: rows[0] } : { kind: 'missing' };
|
||||
}
|
||||
const { rows } = await pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 AND round_id = $2
|
||||
ORDER BY created_at DESC`,
|
||||
[branchCode, roundId]
|
||||
);
|
||||
if (!rows.length) return { kind: 'missing' };
|
||||
if (rows.length > 1) {
|
||||
return { kind: 'ambiguous', supplierCodes: rows.map((row) => String(row.supplier_code || '')) };
|
||||
}
|
||||
return { kind: 'found', row: rows[0] };
|
||||
}
|
||||
|
||||
export async function listInvitationRows(input: {
|
||||
branchCode: string;
|
||||
status?: 'all' | 'pending' | 'history' | null;
|
||||
limit?: number;
|
||||
}): Promise<{ rows: BidInvitationRow[]; counts: Record<string, number> }> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
if (!branchCode) return { rows: [], counts: {} };
|
||||
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
|
||||
const status = input.status === 'pending' || input.status === 'history' ? input.status : null;
|
||||
const statusSql =
|
||||
status === 'pending'
|
||||
? `AND local_status = 'pending'`
|
||||
: status === 'history'
|
||||
? `AND local_status IN ('quoted', 'expired', 'won', 'lost', 'cancelled')`
|
||||
: '';
|
||||
|
||||
const [rows, counts] = await Promise.all([
|
||||
pool.query<BidInvitationRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitations
|
||||
WHERE branch_code = $1 ${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<string, number> = {};
|
||||
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<BidInvitationItemRow[]> {
|
||||
const { rows } = await pool.query<BidInvitationItemRow>(
|
||||
`SELECT * FROM public.main_system_bid_invitation_items
|
||||
WHERE invitation_id = $1
|
||||
ORDER BY sku_name NULLS LAST, sku_code`,
|
||||
[invitationId]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 详情 DTO(含 `canQuote` / `deadlinePassed`,页面只读判断全用它) */
|
||||
export async function getBidInvitationDetail(input: {
|
||||
branchCode: string;
|
||||
roundId: string;
|
||||
supplierCode?: string | null;
|
||||
}): Promise<BidInvitationDetailDto | null> {
|
||||
const found = await findInvitationByRound(input);
|
||||
if (found.kind !== 'found') return null;
|
||||
const row = found.row;
|
||||
const itemRows = await listInvitationItems(row.id);
|
||||
const itemCount = itemRows.length || Number(row.item_count) || 0;
|
||||
const deadlineMs = row.respond_deadline ? new Date(row.respond_deadline).getTime() : NaN;
|
||||
const deadlinePassed = Number.isFinite(deadlineMs) && deadlineMs < Date.now();
|
||||
// 「轮次还在报价中」是对方的事实(`open`);`closed`/`awarded`/`cancelled` 一律不可提交。
|
||||
// 另外派生状态已是终态(expired/won/lost/cancelled)也不可提交:对方说邀约过期时,
|
||||
// 即便本地时钟还没到截止,也不该再发出一次注定被拒的请求。
|
||||
const canQuote =
|
||||
!deadlinePassed &&
|
||||
row.round_status === 'open' &&
|
||||
row.local_status !== 'expired' &&
|
||||
row.local_status !== 'won' &&
|
||||
row.local_status !== 'lost' &&
|
||||
row.local_status !== 'cancelled';
|
||||
const items = itemRows.map((item) => toBidInvitationItemDto(item, row.round_status));
|
||||
return {
|
||||
invitation: { ...toBidInvitationDto(row), itemCount },
|
||||
items,
|
||||
myAwards: items
|
||||
.filter((item) => item.awardStatus === 'won')
|
||||
.map((item) => ({ skuCode: item.skuCode, unitPrice: item.awardPrice })),
|
||||
canQuote,
|
||||
deadlinePassed,
|
||||
syncError: row.sync_error ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 记一次同步/提交失败(页面标题上要能看到"为什么这轮没刷新成功") */
|
||||
/** 按 `(branch, round[, supplier])` 更新;给了 supplier 就只动那一行(多绑定时不误伤) */
|
||||
function invitationScopeSql(input: { supplierCode?: string | null }): { sql: string; params: unknown[] } {
|
||||
const supplierCode = String(input.supplierCode || '').trim();
|
||||
return supplierCode
|
||||
? { sql: `AND upper(supplier_code) = upper($4)`, params: [supplierCode] }
|
||||
: { sql: '', params: [] };
|
||||
}
|
||||
|
||||
export async function markInvitationSyncError(input: {
|
||||
branchCode: string;
|
||||
roundId: string;
|
||||
supplierCode?: string | null;
|
||||
reason: string;
|
||||
}): Promise<void> {
|
||||
const reason = String(input.reason || '').slice(0, 500);
|
||||
const scope = invitationScopeSql(input);
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_bid_invitations
|
||||
SET sync_error = $3, updated_at = NOW()
|
||||
WHERE branch_code = $1 AND round_id = $2 ${scope.sql}`,
|
||||
[String(input.branchCode || '').trim(), String(input.roundId || '').trim(), reason || null, ...scope.params]
|
||||
);
|
||||
}
|
||||
|
||||
/** 对方明确说这一轮不存在/无权查看 ⇒ 我方停用该行(不删,留痕) */
|
||||
export async function markInvitationCancelled(input: {
|
||||
branchCode: string;
|
||||
roundId: string;
|
||||
supplierCode?: string | null;
|
||||
reason: string;
|
||||
}): Promise<void> {
|
||||
const scope = invitationScopeSql(input);
|
||||
await pool.query(
|
||||
`UPDATE public.main_system_bid_invitations
|
||||
SET round_status = 'cancelled',
|
||||
local_status = 'cancelled',
|
||||
sync_error = $3,
|
||||
updated_at = NOW()
|
||||
WHERE branch_code = $1 AND round_id = $2 ${scope.sql}`,
|
||||
[
|
||||
String(input.branchCode || '').trim(),
|
||||
String(input.roundId || '').trim(),
|
||||
String(input.reason || '').slice(0, 500) || null,
|
||||
...scope.params,
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
// ── 对方错误码(契约 §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<typeof toBidInvitationDto>[];
|
||||
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<BidListOutcome> {
|
||||
const { rows, counts } = await listInvitationRows(input);
|
||||
const summary = emptySummary();
|
||||
for (const [key, value] of Object.entries(counts)) {
|
||||
if (key in summary) (summary as Record<string, number>)[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<BidSyncOutcome> {
|
||||
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<BidDetailOutcome> {
|
||||
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<BidDetailOutcome> {
|
||||
/**
|
||||
* ⚠️ 这里**不要**先 `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 };
|
||||
}
|
||||
@@ -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<typeof import('../src/services/mainSystem/config')>();
|
||||
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<string, unknown>) => ({
|
||||
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();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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': '暂无待报价的竞价单',
|
||||
};
|
||||
|
||||
@@ -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': '分类管理',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -28,6 +28,10 @@ const PAGE_LOADERS: Record<string, ReturnType<typeof lazyPage>> = {
|
||||
() => 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'),
|
||||
|
||||
@@ -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<string, string>,
|
||||
common: Record<string, string>
|
||||
): Record<string, string> {
|
||||
const dict: Record<string, string> = {};
|
||||
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<string, string>;
|
||||
};
|
||||
const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as {
|
||||
common: Record<string, string>;
|
||||
};
|
||||
const dict = buildDict(bids, common);
|
||||
// ⚠️ `t` 只建一次:页面把 `t` 放进 useCallback/useEffect 依赖,每渲染换新函数会无限重渲染
|
||||
const t = (key: string, vars?: Record<string, unknown>) => {
|
||||
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 }) => <span>{fallback}</span>,
|
||||
}));
|
||||
|
||||
// `TablePaginationBar` 从 i18n 桶文件取 `useTOrDefault` ⇒ 一并 mock 成同一份字典
|
||||
vi.mock('../../i18n', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../i18n')>('../../i18n');
|
||||
const { bids } = (await import('../../i18n/locales/zh-CN/bids')) as unknown as {
|
||||
bids: Record<string, string>;
|
||||
};
|
||||
const { common } = (await import('../../i18n/locales/zh-CN/common')) as unknown as {
|
||||
common: Record<string, string>;
|
||||
};
|
||||
const dict = buildDict(bids, common);
|
||||
const t = (key: string, vars?: Record<string, unknown>) => {
|
||||
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(<BidInvitationsPage />);
|
||||
|
||||
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('已超过报价截止时间');
|
||||
});
|
||||
});
|
||||
@@ -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<BidLocalStatus, string> = {
|
||||
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<BidLocalStatus, string> = {
|
||||
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<BidInvitationDto[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadError, setLoadError] = useState<string | null>(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<string | null>(null);
|
||||
/** 该轮属于哪个主系统供应商编码(一个分公司可绑多个;同一轮可能有两行邀约) */
|
||||
const [activeSupplierCode, setActiveSupplierCode] = useState<string | null>(null);
|
||||
const [detailTitle, setDetailTitle] = useState('');
|
||||
const [detail, setDetail] = useState<BidInvitationDetailDto | null>(null);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const [drafts, setDrafts] = useState<Record<string, BidDraft>>({});
|
||||
/** `supplier_category_mismatch` 要标红的行(其余行保留可继续报) */
|
||||
const [mismatchSkus, setMismatchSkus] = useState<readonly string[]>([]);
|
||||
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<string, BidDraft> => {
|
||||
const next: Record<string, BidDraft> = {};
|
||||
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<BidInvitationQuoteInput[]>(() => {
|
||||
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 (
|
||||
<div className="p-4 md:p-6 space-y-4">
|
||||
<PageHeader
|
||||
title={
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<MenuLabel menuKey="orders-bid-invitations" fallback={t('bids.invite.pageTitle')} />
|
||||
</span>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={syncing || loading}
|
||||
onClick={() => void handleSync()}
|
||||
>
|
||||
<RefreshCcw className={`w-4 h-4 ${syncing ? 'animate-spin' : ''}`} />
|
||||
{t('bids.invite.btnSync')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" disabled={loading} onClick={handleRefresh}>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
{t('bids.invite.btnRefresh')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="app-surface app-border rounded-xl border overflow-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="app-foreground-muted bg-black/[0.03]">
|
||||
<tr>
|
||||
<th className="text-left px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colRoundNo')}
|
||||
</th>
|
||||
<th className="text-left px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colTitle')}
|
||||
</th>
|
||||
<th className="text-center px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colItemCount')}
|
||||
</th>
|
||||
<th className="text-center px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colDeadline')}
|
||||
</th>
|
||||
<th className="text-center px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.col.status')}
|
||||
</th>
|
||||
<th className="text-center px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.col.actions')}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading && rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6}>
|
||||
<ListState loading />
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{!loading && loadError ? (
|
||||
<tr>
|
||||
<td colSpan={6}>
|
||||
<ListState error={loadError} onRetry={() => void load()} />
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{!loading && !loadError && rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6}>
|
||||
<ListState empty emptyText={t('bids.invite.empty')} />
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{visibleRows.map((row) => {
|
||||
const viewOnly = VIEW_ONLY_LOCAL_STATUSES.includes(row.localStatus);
|
||||
return (
|
||||
<tr key={`${row.roundId}::${row.supplierCode}`} className="border-t app-border align-middle hover:bg-black/[0.02]">
|
||||
<td className="px-3 py-2.5 font-medium whitespace-nowrap">{row.roundCode || '-'}</td>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="truncate max-w-[18rem]">{row.roundTitle || '-'}</div>
|
||||
</td>
|
||||
<td className="px-3 py-2.5 text-center tabular-nums">{row.itemCount}</td>
|
||||
<td className="px-3 py-2.5 text-center whitespace-nowrap app-foreground-muted">
|
||||
{formatTime(row.respondDeadline)}
|
||||
</td>
|
||||
<td className="px-3 py-2.5 text-center whitespace-nowrap">
|
||||
<span
|
||||
className={`inline-flex px-2 py-0.5 rounded-full text-xs ${
|
||||
STATUS_CLASS[row.localStatus] || 'app-status-neutral'
|
||||
}`}
|
||||
>
|
||||
{t(STATUS_LABEL_KEYS[row.localStatus])}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2.5 text-center whitespace-nowrap">
|
||||
<button
|
||||
type="button"
|
||||
className="app-button-secondary app-border px-3 py-1 rounded-lg text-xs"
|
||||
onClick={() => void openDetail(row)}
|
||||
>
|
||||
{viewOnly ? t('bids.invite.actView') : t('bids.invite.actQuote')}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
<TablePaginationBar
|
||||
total={rows.length}
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(size) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
open={Boolean(activeRoundId)}
|
||||
title={detailTitle}
|
||||
onClose={() => {
|
||||
if (!saving) closeDetail();
|
||||
}}
|
||||
className="max-w-4xl"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={saving}
|
||||
onClick={closeDetail}
|
||||
>
|
||||
{t('bids.btn.close')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={readonly || saving || detailLoading}
|
||||
onClick={() => void handleSaveQuotes()}
|
||||
>
|
||||
{saving ? t('common.saving') : t('bids.invite.btnSaveQuotes')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{detailLoading ? <ListState loading /> : null}
|
||||
{!detailLoading && detail ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm app-foreground-muted">
|
||||
<span>
|
||||
{t('bids.invite.colDeadline')}:{formatTime(detail.invitation.respondDeadline)}
|
||||
</span>
|
||||
{readonly && readonlyReason ? (
|
||||
<span role="note" className="app-status-warning rounded-full px-2 py-0.5 text-xs">
|
||||
{readonlyReason}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="app-border border rounded-xl overflow-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="app-foreground-muted bg-black/[0.03]">
|
||||
<tr>
|
||||
<th className="text-left px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colItem')}
|
||||
</th>
|
||||
<th className="text-center px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colUnit')}
|
||||
</th>
|
||||
<th className="text-center px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colMyPrice')}
|
||||
</th>
|
||||
<th className="text-center px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colAwardPrice')}
|
||||
</th>
|
||||
<th className="text-left px-3 py-2.5 font-semibold whitespace-nowrap">
|
||||
{t('bids.invite.colRemark')}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{detail.items.map((item) => {
|
||||
const label = item.skuName || item.skuCode;
|
||||
const draft = drafts[item.skuCode] || { price: '', remark: '' };
|
||||
const mismatch = mismatchSkus.includes(item.skuCode);
|
||||
return (
|
||||
<tr
|
||||
key={item.skuCode}
|
||||
className={`border-t app-border align-middle ${
|
||||
mismatch ? 'bg-red-50' : ''
|
||||
}`}
|
||||
>
|
||||
<td className={`px-3 py-2.5 ${mismatch ? 'text-red-600' : ''}`}>
|
||||
<div className="truncate max-w-[16rem]">{label}</div>
|
||||
</td>
|
||||
<td className="px-3 py-2.5 text-center whitespace-nowrap app-foreground-muted">
|
||||
{item.unit || '-'}
|
||||
</td>
|
||||
<td className="px-3 py-2.5 text-center whitespace-nowrap">
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
step="0.0001"
|
||||
min="0"
|
||||
className={`app-input w-32 px-2 py-1.5 border rounded-lg text-sm text-right ${
|
||||
mismatch ? 'border-red-500' : ''
|
||||
}`}
|
||||
aria-label={`${t('bids.invite.colMyPrice')} ${label}`}
|
||||
disabled={readonly || saving}
|
||||
value={draft.price}
|
||||
onChange={(event) =>
|
||||
setDrafts((prev) => ({
|
||||
...prev,
|
||||
[item.skuCode]: { ...(prev[item.skuCode] || { remark: '' }), price: event.target.value },
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-2.5 text-center whitespace-nowrap app-foreground-muted tabular-nums">
|
||||
{formatUnitPrice(item.awardPrice, locale)}
|
||||
</td>
|
||||
<td className="px-3 py-2.5">
|
||||
<input
|
||||
type="text"
|
||||
className="app-input w-full px-2 py-1.5 border rounded-lg text-sm"
|
||||
aria-label={`${t('bids.invite.colRemark')} ${label}`}
|
||||
disabled={readonly || saving}
|
||||
value={draft.remark}
|
||||
onChange={(event) =>
|
||||
setDrafts((prev) => ({
|
||||
...prev,
|
||||
[item.skuCode]: { ...(prev[item.skuCode] || { price: '' }), remark: event.target.value },
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{!detailLoading && !detail ? <ListState empty emptyText={t('bids.invite.empty')} /> : null}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default BidInvitationsPage;
|
||||
@@ -290,6 +290,7 @@ describe('导航模板收敛:以主系统当前布局为模板', () => {
|
||||
'purchase-list',
|
||||
'purchase-preparations',
|
||||
'orders-price-qty',
|
||||
'orders-bid-invitations',
|
||||
'inspection-list',
|
||||
'inspection-processing',
|
||||
'picking',
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user