diff --git a/client/tests/e2e/r125-invoice-reupload-after-delete.spec.ts b/client/tests/e2e/r125-invoice-reupload-after-delete.spec.ts new file mode 100644 index 00000000..3bd92a51 --- /dev/null +++ b/client/tests/e2e/r125-invoice-reupload-after-delete.spec.ts @@ -0,0 +1,441 @@ +import { mkdirSync } from "node:fs"; +import path from "node:path"; +import { expect, test, type Browser, type Page, type Route } from "@playwright/test"; + +const ROOT_DIR = path.resolve(process.cwd(), ".."); +const SCREENSHOT_DIR = path.join(ROOT_DIR, "output/playwright/r125-invoice-reupload-after-delete"); +const WECOM_UA = + "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 wxwork/4.1.20 MicroMessenger/8.0.1 Language/zh_CN"; + +const reimbursementId = "12511111-1111-4111-8111-111111111111"; +const ownerId = "employee-r125"; +const reusableInvoiceId = "12522222-2222-4222-8222-222222222222"; +const archivedInvoiceId = "12533333-3333-4333-8333-333333333333"; +const newInvoiceId = "12544444-4444-4444-8444-444444444444"; + +function envelope(data: unknown) { + return { requestId: "mock-r125-invoice-reupload", data }; +} + +async function fulfillJson(route: Route, data: unknown, status = 200) { + await route.fulfill({ + status, + contentType: "application/json", + body: JSON.stringify(envelope(data)), + }); +} + +function screenshotPath(fileName: string) { + mkdirSync(SCREENSHOT_DIR, { recursive: true }); + return path.join(SCREENSHOT_DIR, fileName.endsWith(".png") ? fileName : `${fileName}.png`); +} + +function buildMe() { + return { + id: ownerId, + employeeNo: "E125", + name: "测试员工", + phone: "13800000000", + email: "employee@hyinda.com", + departmentId: "dept-r125", + directManagerId: null, + status: "active", + notificationPushEnabled: true, + roleCodes: ["employee"], + profileCompleteness: { + hasEmergencyContact: true, + hasBankAccount: true, + hasAvatar: false, + hasIdNumber: false, + score: 60, + }, + wecomBinding: { externalUserId: "wxwork-r125-user", createdAt: "2026-05-08T08:00:00.000Z" }, + }; +} + +function buildExpenseTypes() { + return { + items: [ + { + id: "expense-type-r125", + code: "business_client_meal", + name: "业务招待", + category: "expense", + enabled: true, + }, + ], + }; +} + +function buildBoundInvoice(id: string) { + return { + id, + status: "bound", + invoiceCode: "044002600125", + invoiceNumber: "12345678", + invoiceDate: "2026-05-08", + sellerName: "北京悦海堂餐饮管理有限公司", + totalAmount: "1683.00", + originalName: "北京悦海堂发票.pdf", + linkedItemId: "item-r125", + }; +} + +function buildAvailableInvoice() { + return { + id: archivedInvoiceId, + invoiceCode: "044002600125", + invoiceNumber: "87654321", + invoiceDate: "2026-05-08", + sellerName: "北京悦海堂餐饮管理有限公司", + totalAmount: "1683.00", + originalName: "已有发票.pdf", + createdAt: "2026-05-08T08:00:00.000Z", + }; +} + +function buildState() { + return { + invoices: [] as ReturnType[], + availableInvoices: [buildAvailableInvoice()], + uploadCount: 0, + }; +} + +function buildReimbursementDetail(state: ReturnType) { + return { + id: reimbursementId, + formNumber: "BX202605080125", + submitterId: ownerId, + ownerId, + departmentId: "dept-r125", + department: { id: "dept-r125", name: "研发部" }, + status: "draft", + createdAt: "2026-05-08T08:00:00.000Z", + submittedAt: null, + reimbursementDate: "2026-05-08", + totalAmount: "1683.00", + description: "R125 发票重传", + projectId: null, + linkedTravelRequestId: null, + linkedTravelRequest: null, + project: null, + owner: { id: ownerId, employee_no: "E125", name: "测试员工" }, + submitter: { id: ownerId, employee_no: "E125", name: "测试员工" }, + invoices: state.invoices, + attachments: [], + budgetHint: null, + pendingWorkflow: null, + workflowProgress: null, + approvalHistory: [], + riskFlags: [], + items: [ + { + id: "item-r125", + expenseTypeId: "expense-type-r125", + expenseDate: "2026-05-08", + amount: "1683.00", + description: "客户招待", + expenseType: { + id: "expense-type-r125", + code: "business_client_meal", + name: "业务招待", + category: "expense", + enabled: true, + }, + }, + ], + }; +} + +function navigationItem(key: string, href: string, label: string, icon: string) { + return { key, href, label, icon, placement: "main", permissionCodes: [], featureFlagKey: null }; +} + +async function mockApis(page: Page, state: ReturnType) { + await page.route((url) => url.pathname.startsWith("/api/"), async (route) => { + const request = route.request(); + const url = new URL(request.url()); + const pathName = url.pathname; + + if (pathName === "/api/auth/sso/providers") { + await fulfillJson(route, []); + return; + } + + if (pathName === "/api/auth/wecom/config") { + await fulfillJson(route, { + enabled: true, + entryEnabled: true, + oauthEnabled: true, + corpId: "ww-test", + agentId: "1000002", + loginUrl: "/api/auth/wecom/login?returnTo=%2Fmobile", + bindEnabled: true, + defaultReturnTo: "/mobile", + status: "ready", + statusReasons: [], + }); + return; + } + + if (pathName === "/api/auth/login" || pathName === "/api/auth/refresh") { + await route.fulfill({ + status: 200, + contentType: "application/json", + headers: { "set-cookie": "has_session=1; Path=/; SameSite=Lax" }, + body: JSON.stringify(envelope({ accessToken: "mock-r125-token", expiresIn: 900, mustChangePassword: false })), + }); + return; + } + + if (pathName === "/api/me") { + await fulfillJson(route, buildMe()); + return; + } + + if (pathName === "/api/system/navigation") { + await fulfillJson(route, { + workspace: { + id: "workspace-r125", + persisted: true, + profile: "small_team_internal", + orgMode: "single_company", + primaryEntryMode: "wecom", + notificationStrategy: "in_app", + devicePriority: "mobile", + moduleVisibility: {}, + createdAt: null, + updatedAt: null, + updatedBy: null, + }, + sections: { + main: [ + navigationItem("portal", "/portal", "工作台", "home_app_logo"), + navigationItem("expense", "/reimbursements", "报销", "request_quote"), + navigationItem("invoice", "/invoice-pool", "票据", "receipt_long"), + ], + admin: [], + backup: [], + }, + recommendedRolePresets: [], + }); + return; + } + + if (pathName === "/api/notifications") { + await fulfillJson(route, { page: 1, pageSize: 1, total: 0, unreadOnly: true, unreadCount: 0, items: [] }); + return; + } + + if (pathName === "/api/portal/home") { + await fulfillJson(route, { + workspace: { id: "workspace-r125", persisted: true, profile: "small_team_internal" }, + greeting: { name: "测试员工" }, + cards: [], + pendingTasks: { count: 0, href: "/workflow/tasks" }, + myApplications: [], + riskSummary: null, + announcements: [], + quickLinks: [], + todayPresence: null, + teamPresence: null, + weeklyReport: null, + weeklySummary: null, + todoSummary: null, + projectSummary: null, + peopleLifecycle: null, + adoptionSummary: null, + recentActivities: [], + teamStatusBoard: [], + }); + return; + } + + if (pathName === "/api/expense-types") { + await fulfillJson(route, buildExpenseTypes()); + return; + } + + if (pathName === "/api/projects") { + await fulfillJson(route, { page: 1, pageSize: 20, total: 0, items: [] }); + return; + } + + if (pathName === `/api/reimbursements/${reimbursementId}` && request.method() === "GET") { + await fulfillJson(route, buildReimbursementDetail(state)); + return; + } + + if (pathName === `/api/reimbursements/${reimbursementId}/precheck`) { + await fulfillJson(route, { + decision: "pass", + standardChecks: [], + budget: null, + riskFlags: [], + }); + return; + } + + if (pathName === "/api/invoice-pool/bindable") { + await fulfillJson(route, { items: state.availableInvoices }); + return; + } + + if (pathName === "/api/invoice-pool" && url.searchParams.get("status") === "ocr_failed") { + await fulfillJson(route, { page: 1, pageSize: 20, total: 0, ownerScope: "own", items: [] }); + return; + } + + if (pathName === "/api/invoice-pool/upload") { + state.uploadCount += 1; + const invoicePoolId = state.uploadCount === 1 ? reusableInvoiceId : newInvoiceId; + await fulfillJson(route, { + invoicePoolId, + status: "available", + fileSha256: "sha256-r125", + uploadAction: state.uploadCount === 1 ? "create" : "reuse_existing", + unavailableReason: null, + unavailableMessage: null, + }); + return; + } + + const bindMatch = pathName.match(/^\/api\/invoice-pool\/([^/]+)\/bind$/); + if (bindMatch) { + state.invoices = [buildBoundInvoice(bindMatch[1])]; + await fulfillJson(route, { + id: bindMatch[1], + status: "bound", + linkedReimbursementId: reimbursementId, + linkedItemId: "item-r125", + linkedTravelOrderId: null, + totalAmount: "1683.00", + }); + return; + } + + const unbindMatch = pathName.match(/^\/api\/invoice-pool\/([^/]+)\/unbind$/); + if (unbindMatch) { + state.invoices = []; + await fulfillJson(route, { + id: unbindMatch[1], + status: "available", + linkedReimbursementId: null, + linkedItemId: null, + linkedTravelOrderId: null, + totalAmount: "1683.00", + }); + return; + } + + if (pathName === `/api/invoice-pool/${archivedInvoiceId}/archive`) { + state.availableInvoices = []; + await fulfillJson(route, { + id: archivedInvoiceId, + status: "archived", + archivedReason: "manual", + archivedAt: "2026-05-08T08:20:00.000Z", + }); + return; + } + + await fulfillJson(route, {}); + }); +} + +async function login(page: Page) { + await page.goto("/login"); + const accountLogin = page.getByRole("button", { name: "使用账号密码登录" }); + if (await accountLogin.isVisible().catch(() => false)) { + await accountLogin.click(); + } + await page.getByTestId("login-identifier").fill("employee@hyinda.com"); + await page.getByTestId("login-password").fill("EmployeePassword1234"); + await page.getByTestId("login-submit").click(); + await page.waitForURL(/\/(portal|mobile)/, { timeout: 30_000 }); +} + +async function newWecomPage(browser: Browser) { + const context = await browser.newContext({ + viewport: { width: 390, height: 844 }, + isMobile: true, + hasTouch: true, + userAgent: WECOM_UA, + locale: "zh-CN", + serviceWorkers: "block", + }); + return { context, page: await context.newPage() }; +} + +test.describe("R125 发票删除后重传", () => { + test("PC 草稿移除发票后,同文件重传可重新添加", async ({ page }) => { + const state = buildState(); + await mockApis(page, state); + await login(page); + + await page.setViewportSize({ width: 1440, height: 960 }); + await page.goto(`/reimbursements/${reimbursementId}`); + await page.getByTestId("reimbursement-invoice-add").click(); + await page.getByTestId("reimbursement-invoice-upload-file").setInputFiles({ + name: "北京悦海堂发票.pdf", + mimeType: "application/pdf", + buffer: Buffer.from("%PDF r125 invoice"), + }); + await page.getByTestId("reimbursement-invoice-upload-submit").click(); + await expect(page.getByText("发票上传完成:1 张已添加")).toBeVisible({ timeout: 10_000 }); + await page.keyboard.press("Escape"); + await expect(page.getByText("北京悦海堂餐饮管理有限公司")).toBeVisible(); + + await page.getByRole("button", { name: "移除" }).first().click(); + await expect(page.getByText("北京悦海堂餐饮管理有限公司")).toHaveCount(0); + + await page.getByTestId("reimbursement-invoice-add").click(); + await page.getByTestId("reimbursement-invoice-upload-file").setInputFiles({ + name: "北京悦海堂发票.pdf", + mimeType: "application/pdf", + buffer: Buffer.from("%PDF r125 invoice"), + }); + await page.getByTestId("reimbursement-invoice-upload-submit").click(); + await expect(page.getByText("发票上传完成:1 张已添加")).toBeVisible({ timeout: 10_000 }); + await page.keyboard.press("Escape"); + await expect(page.getByText("北京悦海堂餐饮管理有限公司")).toBeVisible(); + await page.screenshot({ path: screenshotPath("pc-reupload-after-unbind.png"), fullPage: true }); + }); + + test("企业微信移动端删除已有发票后,同文件重传可重新添加", async ({ browser }) => { + const state = buildState(); + const mobile = await newWecomPage(browser); + await mockApis(mobile.page, state); + + try { + await login(mobile.page); + await mobile.page.goto(`/mobile/reimbursements/${reimbursementId}`); + await mobile.page.getByTestId("reimbursement-invoice-add").click(); + const invoiceDialog = mobile.page.getByTestId("reimbursement-invoice-dialog"); + await invoiceDialog.getByRole("button", { name: "已有发票" }).click(); + + const availableInvoiceCard = invoiceDialog.locator("article").filter({ hasText: "044002600125-87654321" }); + await expect(availableInvoiceCard).toBeVisible(); + await availableInvoiceCard.getByRole("button", { name: "删除" }).click(); + await mobile.page.getByRole("dialog").last().getByRole("button", { name: "删除" }).click(); + await expect(availableInvoiceCard).toHaveCount(0); + + await invoiceDialog.getByRole("button", { name: "上传" }).click(); + await mobile.page.getByTestId("reimbursement-invoice-upload-file").setInputFiles({ + name: "北京悦海堂发票.pdf", + mimeType: "application/pdf", + buffer: Buffer.from("%PDF r125 invoice"), + }); + await mobile.page.getByTestId("reimbursement-invoice-upload-submit").click(); + await expect( + mobile.page.getByTestId("reimbursement-invoice-dialog").getByText(/1 张已添加|已添加 1 张发票/), + ).toBeVisible({ timeout: 10_000 }); + await mobile.page.keyboard.press("Escape"); + await expect(mobile.page.getByText("北京悦海堂餐饮管理有限公司")).toBeVisible(); + await mobile.page.screenshot({ path: screenshotPath("mobile-reupload-after-archive.png"), fullPage: true }); + } finally { + await mobile.context.close(); + } + }); +}); diff --git a/issues/2026-05-08_19-41-40-r125-invoice-reupload-after-delete.csv b/issues/2026-05-08_19-41-40-r125-invoice-reupload-after-delete.csv new file mode 100644 index 00000000..c911aadd --- /dev/null +++ b/issues/2026-05-08_19-41-40-r125-invoice-reupload-after-delete.csv @@ -0,0 +1,5 @@ +ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes +A1,R125发票删除后重传执行合同,"修复报销草稿移除/删除发票后,同一发票无法重新上传或重新添加的问题。","1) Issue CSV 校验通过;2) 明确 active 发票和 archived/manual 发票查重边界;3) 不混入无关重构。","命令:python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-05-08_19-41-40-r125-invoice-reupload-after-delete.csv;业务流程:上传发票->添加到草稿->移除/删除->重新上传->重新添加。","python|manual",DONE,DONE,DONE,"issues/2026-05-08_19-41-40-r125-invoice-reupload-after-delete.csv","[]","不做破坏性数据库操作;CSV 校验通过。" +A2,修正发票查重边界,"manual archived 发票不再阻止同一文件重新上传或绑定;used_complete 仍阻止重复报销。","1) archived/manual 不参与上传和绑定查重;2) bound/used_complete 仍阻止;3) available 同 owner 可复用并重新绑定;4) 公司内其他 owner 的 active 发票仍阻止。","后端回归:构造 manual archived、available、bound、used_complete、other owner active 五类发票分别验证上传/绑定结果。","node|prisma",DONE,DONE,DONE,"server/src/services/invoiceGovernance.js|server/src/routes/invoicePool.js|server/tests","[""A1""]","不放宽已报销发票查重;unit 覆盖 manual archived、used_complete、available、other owner active。" +A3,补双端回归,"覆盖 PC 和企业微信移动端:草稿发票移除/删除后重新上传。","PC 与 mobile/wecom:上传发票->添加->移除或删除->再次上传->可重新添加;删除草稿后新草稿也可重新添加。","Playwright R125;client typecheck/build;server syntax/regression。","playwright|npm",DONE,DONE,DONE,"client/tests/e2e|server/scripts","[""A2""]","R111+R125 Playwright 共 4 条通过;截图保存在 output/playwright/r125-invoice-reupload-after-delete。" +A4,部署与公网复验,"修复后部署到试运行并验证用户可测。","1) 部署成功;2) /ready 通过;3) migrate status 通过;4) runtime smoke 通过;5) 公网资源扫描通过;6) 明确可去企业微信测试。","deploy/trialrun/deploy.sh;curl /ready;public bundle scan;runtime smoke。","bash|curl|ssh",DONE,DONE,DONE,"deploy/trialrun|issues/2026-05-08_19-41-40-r125-invoice-reupload-after-delete.csv","[""A2"",""A3""]","已部署到 https://oa.hyinda.com;LIVE_SMOKE_* 未配置因此部署脚本跳过网页 live smoke。" diff --git a/server/src/services/invoiceGovernance.js b/server/src/services/invoiceGovernance.js index 5bb0f4ef..4c6d3d3e 100644 --- a/server/src/services/invoiceGovernance.js +++ b/server/src/services/invoiceGovernance.js @@ -31,6 +31,10 @@ function isUsedInvoice(invoice) { ); } +function isInactiveArchivedInvoice(invoice) { + return Boolean(invoice?.status === "archived" && invoice?.archived_reason !== USED_COMPLETE_ARCHIVED_REASON); +} + function classifyInvoiceConflict(conflict, ownerEmployeeId) { if (!conflict) { return null; @@ -40,6 +44,10 @@ function classifyInvoiceConflict(conflict, ownerEmployeeId) { return INVOICE_UNAVAILABLE_REASONS.usedByCompany; } + if (isInactiveArchivedInvoice(conflict)) { + return null; + } + if (conflict.owner_employee_id && conflict.owner_employee_id !== ownerEmployeeId) { return INVOICE_UNAVAILABLE_REASONS.duplicateOtherOwner; } @@ -94,8 +102,15 @@ async function findInvoiceDedupConflicts(tx, input) { where: { ...(input.excludeInvoiceId ? { id: { not: input.excludeInvoiceId } } : {}), is_duplicate_override: false, - OR: filters, - status: { in: ["pending_ocr", "ocr_failed", "available", "bound", "archived"] }, + AND: [ + { OR: filters }, + { + OR: [ + { status: { in: ["pending_ocr", "ocr_failed", "available", "bound"] } }, + { status: "archived", archived_reason: USED_COMPLETE_ARCHIVED_REASON }, + ], + }, + ], }, orderBy: [{ created_at: "asc" }, { id: "asc" }], select: { diff --git a/server/tests/unit/invoiceGovernance.dedup.test.js b/server/tests/unit/invoiceGovernance.dedup.test.js new file mode 100644 index 00000000..8828f935 --- /dev/null +++ b/server/tests/unit/invoiceGovernance.dedup.test.js @@ -0,0 +1,93 @@ +const { + INVOICE_UNAVAILABLE_REASONS, + classifyInvoiceConflict, + resolveUploadDedupDecision, +} = require("../../src/services/invoiceGovernance"); + +function buildInvoice(overrides = {}) { + return { + id: overrides.id ?? "invoice-1", + owner_employee_id: overrides.owner_employee_id ?? "employee-1", + uploaded_by_employee_id: overrides.uploaded_by_employee_id ?? "employee-1", + status: overrides.status ?? "available", + archived_reason: overrides.archived_reason ?? null, + linked_reimbursement_id: overrides.linked_reimbursement_id ?? null, + linked_item_id: overrides.linked_item_id ?? null, + travel_order_id: overrides.travel_order_id ?? null, + file_sha256: overrides.file_sha256 ?? "sha256-a", + invoice_code: overrides.invoice_code ?? null, + invoice_number: overrides.invoice_number ?? null, + }; +} + +function buildTx(conflicts) { + return { + invoicePool: { + findMany: async () => conflicts, + }, + }; +} + +describe("invoiceGovernance dedup", () => { + it("ignores manually archived invoices when re-uploading the same file", async () => { + const archivedManual = buildInvoice({ + status: "archived", + archived_reason: "manual", + }); + + expect(classifyInvoiceConflict(archivedManual, "employee-1")).toBeNull(); + + const decision = await resolveUploadDedupDecision(buildTx([archivedManual]), { + fileSha256: "sha256-a", + ownerEmployeeId: "employee-1", + }); + + expect(decision).toEqual({ action: "create" }); + }); + + it("blocks invoices that have already completed reimbursement", async () => { + const usedComplete = buildInvoice({ + status: "archived", + archived_reason: "used_complete", + linked_reimbursement_id: "reimbursement-1", + }); + + expect(classifyInvoiceConflict(usedComplete, "employee-1")).toBe(INVOICE_UNAVAILABLE_REASONS.usedByCompany); + + const decision = await resolveUploadDedupDecision(buildTx([usedComplete]), { + fileSha256: "sha256-a", + ownerEmployeeId: "employee-1", + }); + + expect(decision.action).toBe("blocked"); + expect(decision.reason).toBe(INVOICE_UNAVAILABLE_REASONS.usedByCompany); + }); + + it("reuses the owner's active available invoice", async () => { + const available = buildInvoice({ status: "available" }); + + const decision = await resolveUploadDedupDecision(buildTx([available]), { + fileSha256: "sha256-a", + ownerEmployeeId: "employee-1", + }); + + expect(decision.action).toBe("reuse_existing"); + expect(decision.reason).toBe(INVOICE_UNAVAILABLE_REASONS.duplicateAvailable); + expect(decision.invoice.id).toBe("invoice-1"); + }); + + it("blocks another owner's active invoice in the same company", async () => { + const otherOwner = buildInvoice({ + owner_employee_id: "employee-2", + status: "available", + }); + + const decision = await resolveUploadDedupDecision(buildTx([otherOwner]), { + fileSha256: "sha256-a", + ownerEmployeeId: "employee-1", + }); + + expect(decision.action).toBe("blocked"); + expect(decision.reason).toBe(INVOICE_UNAVAILABLE_REASONS.duplicateOtherOwner); + }); +});