From a8b7351a4fc6796767a5215b32594289a611d227 Mon Sep 17 00:00:00 2001 From: shunli Date: Tue, 12 May 2026 01:30:12 +0800 Subject: [PATCH] =?UTF-8?q?PS6=20=E4=BF=AE=E5=A4=8D=E9=87=87=E8=B4=AD?= =?UTF-8?q?=E6=8F=90=E4=BA=A4=E9=A2=84=E7=AE=97=E9=A2=84=E6=A3=80=E9=98=BB?= =?UTF-8?q?=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...purchase-submit-budget-precheck-hotfix.csv | 4 +- server/src/routes/purchaseRequests.js | 14 +- .../purchase.submit-budget-precheck.test.js | 291 ++++++++++++++++++ 3 files changed, 306 insertions(+), 3 deletions(-) create mode 100644 server/tests/unit/routes/purchase.submit-budget-precheck.test.js diff --git a/issues/2026-05-12_01-12-20-r6-purchase-submit-budget-precheck-hotfix.csv b/issues/2026-05-12_01-12-20-r6-purchase-submit-budget-precheck-hotfix.csv index 56073bf2..58bfcda6 100644 --- a/issues/2026-05-12_01-12-20-r6-purchase-submit-budget-precheck-hotfix.csv +++ b/issues/2026-05-12_01-12-20-r6-purchase-submit-budget-precheck-hotfix.csv @@ -1,6 +1,6 @@ ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes PS6-1,R6 采购提交阻断建档,记录 R6-4 采购主链路在公网提交时触发服务端 500 的事实证据,并固定本热修合同范围。,"1) `docs/trialrun/manual-trialrun-report.md` 已登记 `R6-ISSUE-003`;2) R6 小范围合同 R6-4 保持未完整通过,R6-5/R6-6 不推进;3) 本合同只处理采购提交预算预检变量缺失,不扩功能、不改远端数据、不清理 smoke 数据。","流程级验证:python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-05-12_01-12-20-r6-purchase-submit-budget-precheck-hotfix.csv;rg -n 'R6-ISSUE-003|budgetPrecheckGate|ab69db11-87e3-48b0-8a8a-43324d1c70e5' docs/trialrun/manual-trialrun-report.md issues server/src/routes/purchaseRequests.js。",python3|rg|manual,DONE,DONE,DONE,issues/2026-05-12_01-12-20-r6-purchase-submit-budget-precheck-hotfix.csv|docs/trialrun/manual-trialrun-report.md,[],R6-4 已创建公网测试数据,采购草稿 `ab69db11-87e3-48b0-8a8a-43324d1c70e5` 停在 draft;不得清理或篡改历史数据,修复后新建或复用可解释测试单据复跑。 -PS6-2,修复采购提交预算预检变量,在 `server/src/routes/purchaseRequests.js` 的提交路径中正确求值或传递 `budgetPrecheckGate`,避免缺预算池分支引用未定义变量。,"1) `/api/purchase-requests/:id/submit` 不再因 `budgetPrecheckGate is not defined` 返回 500;2) 保持预算预检既有语义:开启 budget_precheck 时以 authoritative precheck 为准,未开启时走 legacy fallback control mode;3) 无 Prisma migration、无 API 契约变更、无权限模型变更。","流程级验证:cd server && npm run prisma:validate;cd server && node --check src/routes/purchaseRequests.js;补充或更新采购提交测试,覆盖无预算池、预算预检开关关闭/继承、提交进入审批或返回可解释 4xx 的路径;确认不会生成 500。",node|npm,TODO,TODO,TODO,server/src/routes/purchaseRequests.js|server/tests/**,"[""PS6-1""]","回滚路径:还原本 Issue 对 `server/src/routes/purchaseRequests.js` 和测试文件的变更后重新部署;不涉及 schema 和数据回滚。" -PS6-3,采购主链路本地回归,复跑采购业务自动化,确认员工提交采购、经理审批、历史查看不再被预算预检变量阻断。,"1) 本地采购业务流通过;2) 若缺预算池,结果必须是可解释业务校验或正常进入审批,不允许 500;3) 不要求新增预算、ERP、AI、完整差旅或复杂 BPM。","流程级验证:BUSINESS_FLOW_GROUPS=procurement bash scripts/qa/run-business-flow-gates.sh local;如该脚本不可用,则用现有 Playwright/接口脚本登录 `SMOKE002` 创建采购 -> 提交 -> `SMOKE101` 审批 -> 查询历史,并记录替代命令。",bash|playwright,TODO,TODO,TODO,scripts/qa/*|client/tests/e2e/*,"[""PS6-2""]","若本地隔离环境缺采购基础资料,可使用测试 seed 或脚本受控创建测试成本中心、供应商、法体和采购类别;不得改生产数据。" +PS6-2,修复采购提交预算预检变量,在 `server/src/routes/purchaseRequests.js` 的提交路径中正确求值或传递 `budgetPrecheckGate`,避免缺预算池分支引用未定义变量。,"1) `/api/purchase-requests/:id/submit` 不再因 `budgetPrecheckGate is not defined` 返回 500;2) 保持预算预检既有语义:开启 budget_precheck 时以 authoritative precheck 为准,未开启时走 legacy fallback control mode;3) 无 Prisma migration、无 API 契约变更、无权限模型变更。","流程级验证:cd server && npm run prisma:validate;cd server && node --check src/routes/purchaseRequests.js;补充或更新采购提交测试,覆盖无预算池、预算预检开关关闭/继承、提交进入审批或返回可解释 4xx 的路径;确认不会生成 500。",node|npm,DONE,DONE,DONE,server/src/routes/purchaseRequests.js|server/tests/**,"[""PS6-1""]","DONE:已在采购提交事务中求值 `FEATURE_FLAG_KEYS.budgetPrecheck`,预算预检关闭时使用 legacy fallback control mode,开启时沿用 authoritative precheck 结果;新增 `server/tests/unit/routes/purchase.submit-budget-precheck.test.js` 覆盖无预算池、预算预检关闭且 precheck hint=block 时仍进入审批并返回 `missing_budget_pool` warning,不再 500。验证通过:`cd server && npm run prisma:validate`;`cd server && node --check src/routes/purchaseRequests.js`;`cd server && npm test -- tests/unit/routes/purchase.submit-budget-precheck.test.js tests/unit/routes/purchase.submit-side-effects.test.js`。回滚路径:还原本 Issue 对 `server/src/routes/purchaseRequests.js` 和测试文件的变更后重新部署;不涉及 schema 和数据回滚。" +PS6-3,采购主链路本地回归,复跑采购业务自动化,确认员工提交采购、经理审批、历史查看不再被预算预检变量阻断。,"1) 本地采购业务流通过;2) 若缺预算池,结果必须是可解释业务校验或正常进入审批,不允许 500;3) 不要求新增预算、ERP、AI、完整差旅或复杂 BPM。","流程级验证:BUSINESS_FLOW_GROUPS=procurement bash scripts/qa/run-business-flow-gates.sh local;如该脚本不可用,则用现有 Playwright/接口脚本登录 `SMOKE002` 创建采购 -> 提交 -> `SMOKE101` 审批 -> 查询历史,并记录替代命令。",bash|playwright,DONE,DONE,DONE,scripts/qa/*|client/tests/e2e/*,"[""PS6-2""]","DONE:`BUSINESS_FLOW_GROUPS=procurement bash scripts/qa/run-business-flow-gates.sh local` 通过,`procurement-flow.spec.ts` 1 passed,报告 `artifacts/qa-flow/business-flow-20260512-012612/summary.txt`;本地链路覆盖员工提单、经理审批、财务归档,不新增预算、ERP、AI、完整差旅或复杂 BPM。" PS6-4,部署与公网复检,本地验证通过后受控部署到 `https://oa.hyinda.com`,复检公网健康和基础 smoke。,"1) `bash deploy/trialrun/deploy.sh` 成功,不覆盖远端 `.env`;2) `/ready` 正常;3) public bundle 扫描 findings=0;4) live smoke readiness 通过;5) 企业微信个人应用消息通道仍为 `wecom_app_message enabled=true`。","流程级验证:bash deploy/trialrun/deploy.sh;curl -fsS https://oa.hyinda.com/ready;LIVE_SMOKE_BASE_URL=https://oa.hyinda.com bash scripts/qa/run-live-smoke-readiness.sh;只读确认通知渠道和公网运行文件哈希。",bash|curl|ssh,TODO,TODO,TODO,deploy/trialrun/*|scripts/qa/*,"[""PS6-3""]","若部署失败,停止并记录错误;不手工修远端代码、不改 `.env`、不继续 R6。" PS6-5,恢复 R6-4 采购复跑与状态回填,热修部署后恢复 R6-4 的采购路径复跑,完成采购提交、审批和历史查看后再判断是否进入 R6-5。,"1) 采购从草稿提交进入审批或可解释业务状态;2) `SMOKE101` 可处理采购待办;3) 采购历史与审批中心一致;4) `docs/trialrun/manual-trialrun-report.md` 和 R6 合同已回填;5) 主 R6 仍不标 DONE,直到 R6-5/R6-6 完成。","流程级验证:公网 `SMOKE002` 创建/提交采购 -> `SMOKE101` 审批 -> 员工/管理员查看采购历史和审批日志 -> 记录到 R6 流程矩阵;必要时补企业微信消息审计。",manual|playwright|curl,TODO,TODO,TODO,docs/trialrun/manual-trialrun-report.md|issues/2026-05-11_10-23-41-r6-small-trialrun-prep.csv,"[""PS6-4""]","复跑通过后可把 R6-4 Regression_Status 置为 DONE,并进入 R6-5 每日收口;若仍失败,保持 R6-ISSUE-003 open 并暂停 R6。" diff --git a/server/src/routes/purchaseRequests.js b/server/src/routes/purchaseRequests.js index 71e95bf1..c2e42198 100644 --- a/server/src/routes/purchaseRequests.js +++ b/server/src/routes/purchaseRequests.js @@ -1612,7 +1612,19 @@ async function purchaseRequestRoutes(fastify) { } const warnings = []; - const budgetControlMode = authoritativePrecheck?.budgetHint?.controlMode ?? normalizeBudgetControlMode(fastify.config); + const budgetPrecheckGate = await evaluateFeatureFlag({ + prisma: tx, + config: fastify.config, + flagKey: FEATURE_FLAG_KEYS.budgetPrecheck, + departmentId: purchaseRequest.department_id ?? request.employee.department_id ?? null, + strictDepartment: false, + }); + const fallbackBudgetControlMode = normalizeBudgetControlMode(fastify.config); + const budgetControlMode = budgetPrecheckGate.enabled + ? authoritativePrecheck.matchedBudgetControlRule?.controlMode + ?? authoritativePrecheck?.budgetHint?.controlMode + ?? fallbackBudgetControlMode + : fallbackBudgetControlMode; if (!selectedBudgetPoolId) { if (!budgetPrecheckGate.enabled && budgetControlMode === "block") { throw buildValidationError({ budget: "missing_budget_pool" }, 409); diff --git a/server/tests/unit/routes/purchase.submit-budget-precheck.test.js b/server/tests/unit/routes/purchase.submit-budget-precheck.test.js new file mode 100644 index 00000000..3fea1d88 --- /dev/null +++ b/server/tests/unit/routes/purchase.submit-budget-precheck.test.js @@ -0,0 +1,291 @@ +const Fastify = require("fastify"); + +const { AppError } = require("../../../src/utils/AppError"); +const budgetPool = require("../../../src/services/budgetPool"); +const feeControl = require("../../../src/services/feeControl"); +const notifications = require("../../../src/services/notifications"); + +const resolveApplicableBudgetPoolByContextMock = vi.fn(); +const resolveEntityPrecheckMock = vi.fn(); +const createRiskFlagsFromPrecheckMock = vi.fn(); +const resolveRecipientsForAssigneeMock = vi.fn(); + +const originalResolveApplicableBudgetPoolByContext = budgetPool.resolveApplicableBudgetPoolByContext; +const originalResolveEntityPrecheck = feeControl.resolveEntityPrecheck; +const originalCreateRiskFlagsFromPrecheck = feeControl.createRiskFlagsFromPrecheck; +const originalResolveRecipientsForAssignee = notifications.resolveRecipientsForAssignee; + +budgetPool.resolveApplicableBudgetPoolByContext = resolveApplicableBudgetPoolByContextMock; +feeControl.resolveEntityPrecheck = resolveEntityPrecheckMock; +feeControl.createRiskFlagsFromPrecheck = createRiskFlagsFromPrecheckMock; +notifications.resolveRecipientsForAssignee = resolveRecipientsForAssigneeMock; + +delete require.cache[require.resolve("../../../src/routes/purchaseRequests")]; +const purchaseRequestRoutes = require("../../../src/routes/purchaseRequests"); + +const PURCHASE_REQUEST_ID = "11111111-1111-4111-8111-111111111111"; +const EMPLOYEE_ID = "22222222-2222-4222-8222-222222222222"; +const DEPARTMENT_ID = "33333333-3333-4333-8333-333333333333"; +const LEGAL_ENTITY_ID = "44444444-4444-4444-8444-444444444444"; +const COST_CENTER_ID = "55555555-5555-4555-8555-555555555555"; +const SUPPLIER_ID = "66666666-6666-4666-8666-666666666666"; +const DOCUMENT_CATEGORY_ID = "77777777-7777-4777-8777-777777777777"; + +function buildPrecheck(overrides = {}) { + return { + entityType: "purchase_request", + entityId: PURCHASE_REQUEST_ID, + decision: "pass", + matchedBudgetControlRule: null, + budgetHint: null, + standardChecks: [], + warnings: [], + blockingReasons: [], + riskFlags: [], + nextActions: ["可直接提交"], + ...overrides, + }; +} + +async function buildApp(options = {}) { + const app = Fastify(); + const actor = { + id: EMPLOYEE_ID, + department_id: DEPARTMENT_ID, + roleCodes: [], + permissionCodes: ["procurement.submit"], + }; + const purchaseRequest = { + id: PURCHASE_REQUEST_ID, + applicant_id: EMPLOYEE_ID, + submitter_id: null, + department_id: DEPARTMENT_ID, + legal_entity_id: LEGAL_ENTITY_ID, + cost_center_id: COST_CENTER_ID, + supplier_id: SUPPLIER_ID, + document_category_id: DOCUMENT_CATEGORY_ID, + budget_pool_id: null, + request_no: null, + title: "R6 采购提交热修测试", + reason: null, + currency_code: "CNY", + total_amount: "99.00", + expected_delivery_date: null, + status: "draft", + created_at: new Date("2026-05-12T00:00:00.000Z"), + updated_at: new Date("2026-05-12T00:00:00.000Z"), + items: [{ id: "item-1" }], + applicant: { id: EMPLOYEE_ID, name: "申请人" }, + document_category: { + id: DOCUMENT_CATEGORY_ID, + code: "PR_STANDARD", + name: "标准采购申请", + entity_type: "purchase_request", + enabled: true, + archived_at: null, + }, + }; + + const state = { + workflowInstanceCreatePayload: null, + }; + + const tx = { + $queryRaw: vi.fn(async () => [purchaseRequest]), + legalEntity: { + findUnique: vi.fn(async () => ({ + id: LEGAL_ENTITY_ID, + code: "LE", + name: "测试法体", + enabled: true, + archived_at: null, + })), + }, + costCenter: { + findUnique: vi.fn(async () => ({ + id: COST_CENTER_ID, + code: "CC", + name: "测试成本中心", + legal_entity_id: LEGAL_ENTITY_ID, + enabled: true, + archived_at: null, + })), + }, + supplier: { + findUnique: vi.fn(async () => ({ + id: SUPPLIER_ID, + code: "SUP", + name: "测试供应商", + legal_entity_id: LEGAL_ENTITY_ID, + enabled: true, + archived_at: null, + })), + }, + documentCategory: { + findUnique: vi.fn(async () => purchaseRequest.document_category), + findFirst: vi.fn(async () => purchaseRequest.document_category), + }, + documentSequence: { + findUnique: vi.fn(async () => null), + upsert: vi.fn(async () => ({ + document_type: "purchase_request", + prefix: "CG", + date_format: "YYYYMMDD", + separator: "-", + number_length: 4, + reset_period: "yearly", + current_number: 1, + last_reset_date: null, + updated_at: new Date("2026-05-12T00:00:00.000Z"), + updated_by: EMPLOYEE_ID, + })), + }, + purchaseRequestItem: { + aggregate: vi.fn(async () => ({ + _sum: { line_amount: "99.00" }, + })), + }, + purchaseRequest: { + findUnique: vi.fn(async () => purchaseRequest), + update: vi.fn(async ({ data }) => ({ + ...purchaseRequest, + ...data, + })), + }, + workflowInstance: { + create: vi.fn(async ({ data }) => { + state.workflowInstanceCreatePayload = data; + return { id: "88888888-8888-4888-8888-888888888888" }; + }), + }, + workflowTask: { + create: vi.fn(async () => ({ + id: "99999999-9999-4999-8999-999999999999", + assignee_id: null, + assignee_role: "manager", + })), + }, + workflowHistory: { + create: vi.fn(async () => ({ id: "history-1" })), + }, + auditLog: { + create: vi.fn(async () => ({ id: "audit-1" })), + }, + }; + + const prisma = { + $transaction: vi.fn(async (callback) => callback(tx)), + auditLog: { + create: vi.fn(async () => ({ id: "audit-outer" })), + }, + purchaseRequest: { + findUnique: vi.fn(async () => purchaseRequest), + }, + workflowDefinition: { + findFirst: vi.fn(async () => ({ + id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + definition_json: { + steps: [ + { + id: "approval_1_manager", + name: "主管审批", + type: "approval", + assignee_rule: { type: "role", value: "manager" }, + }, + ], + }, + })), + }, + }; + + app.decorate("prisma", prisma); + app.decorate("config", { + appTimezone: "Asia/Shanghai", + budgetControlMode: options.budgetControlMode ?? "warn", + budgetPrecheckEnabled: options.budgetPrecheckEnabled ?? false, + cutoverConsoleEnabled: false, + imNotifierEnabled: false, + emailEnabled: false, + }); + app.decorate("hasPermission", (employee, permissionCode) => { + const permissionCodes = employee?.permissionCodes ?? []; + return permissionCodes.includes("*") || permissionCodes.includes(permissionCode); + }); + app.decorate("requirePermission", (permissionCode) => async (request) => { + request.employee = actor; + if (!app.hasPermission(actor, permissionCode)) { + throw new AppError({ + code: "PERM_001", + message: "无权限", + statusCode: 403, + }); + } + }); + app.setErrorHandler((error, request, reply) => { + reply.status(error.statusCode || 500).send({ + requestId: request.id, + error: { + code: error.code || "SYS_001", + message: error.message, + details: error.details ?? null, + }, + }); + }); + + await app.register(purchaseRequestRoutes, { prefix: "/api" }); + return { app, prisma, tx, state }; +} + +describe("purchase request submit budget precheck gate", () => { + afterAll(() => { + budgetPool.resolveApplicableBudgetPoolByContext = originalResolveApplicableBudgetPoolByContext; + feeControl.resolveEntityPrecheck = originalResolveEntityPrecheck; + feeControl.createRiskFlagsFromPrecheck = originalCreateRiskFlagsFromPrecheck; + notifications.resolveRecipientsForAssignee = originalResolveRecipientsForAssignee; + }); + + beforeEach(() => { + vi.clearAllMocks(); + resolveApplicableBudgetPoolByContextMock.mockResolvedValue(null); + createRiskFlagsFromPrecheckMock.mockResolvedValue([]); + resolveRecipientsForAssigneeMock.mockResolvedValue([]); + }); + + it("does not 500 when no budget pool exists and budget precheck is disabled", async () => { + resolveEntityPrecheckMock.mockResolvedValue( + buildPrecheck({ + budgetHint: { + controlMode: "block", + }, + }), + ); + + const { app, state } = await buildApp({ + budgetControlMode: "warn", + budgetPrecheckEnabled: false, + }); + + const response = await app.inject({ + method: "POST", + url: `/api/purchase-requests/${PURCHASE_REQUEST_ID}/submit`, + }); + + expect(response.statusCode).toBe(200); + expect(response.json().data).toEqual( + expect.objectContaining({ + purchaseRequestId: PURCHASE_REQUEST_ID, + status: "reviewing", + budgetPoolId: null, + warnings: ["missing_budget_pool"], + }), + ); + expect(state.workflowInstanceCreatePayload).toEqual( + expect.objectContaining({ + entity_type: "purchase_request", + entity_id: PURCHASE_REQUEST_ID, + }), + ); + + await app.close(); + }); +});