const Fastify = require("fastify"); const payrollRoutes = require("../../../src/routes/payroll"); const { AppError } = require("../../../src/utils/AppError"); const ADMIN_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; const EMPLOYEE_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; const OTHER_EMPLOYEE_ID = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; function buildEmployee(overrides = {}) { return { id: EMPLOYEE_ID, employee_no: "E001", name: "Alice", title: "专员", status: "active", department: { id: "dept-1", name: "行政部" }, ...overrides, }; } function buildSalaryItem(overrides = {}) { return { id: "11111111-1111-4111-8111-111111111111", name: "基本工资", item_type: "earning", sort_order: 10, enabled: true, ...overrides, }; } function buildSalaryRow(overrides = {}) { return { id: "salary-1", employee_id: EMPLOYEE_ID, salary_item_id: "11111111-1111-4111-8111-111111111111", monthly_amount: "10000.00", effective_date: new Date("2026-04-01T00:00:00.000Z"), ...overrides, }; } const PAYSLIP_IDS = [ "dddddddd-dddd-4ddd-8ddd-dddddddddddd", "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "ffffffff-ffff-4fff-8fff-ffffffffffff", ]; async function buildApp({ actor = { id: ADMIN_ID, permissionCodes: ["payroll.manage"] }, omitProfileFor = [], } = {}) { const app = Fastify(); const state = { employees: [ buildEmployee(), buildEmployee({ id: OTHER_EMPLOYEE_ID, employee_no: "E002", name: "Bob", }), ], salaryItems: [ buildSalaryItem(), buildSalaryItem({ id: "22222222-2222-4222-8222-222222222222", name: "社保扣除", item_type: "deduction", sort_order: 20, }), ], salaryRows: [ buildSalaryRow(), buildSalaryRow({ id: "salary-2", employee_id: EMPLOYEE_ID, salary_item_id: "22222222-2222-4222-8222-222222222222", monthly_amount: "600.00", }), buildSalaryRow({ id: "salary-3", employee_id: OTHER_EMPLOYEE_ID, monthly_amount: "9000.00", }), buildSalaryRow({ id: "salary-4", employee_id: OTHER_EMPLOYEE_ID, salary_item_id: "22222222-2222-4222-8222-222222222222", monthly_amount: "500.00", }), ].filter((item) => !omitProfileFor.includes(item.employee_id)), payslips: [], payslipItems: [], }; function hydratePayslip(payslip) { return { ...payslip, employee: state.employees.find((item) => item.id === payslip.employee_id), items: state.payslipItems .filter((item) => item.payslip_id === payslip.id) .map((item) => ({ ...item, salary_item: state.salaryItems.find((salaryItem) => salaryItem.id === item.salary_item_id), })), }; } const payslip = { count: vi.fn(async ({ where }) => state.payslips.filter((item) => item.pay_month.getTime() === where.pay_month.getTime()).length), findMany: vi.fn(async ({ where, select, include }) => { const filtered = state.payslips.filter((item) => { if (where?.pay_month && item.pay_month.getTime() !== where.pay_month.getTime()) { return false; } if (where?.employee_id && item.employee_id !== where.employee_id) { return false; } if (where?.status && item.status !== where.status) { return false; } if (where?.id?.in && !where.id.in.includes(item.id)) { return false; } return true; }); if (select) { return filtered.map((item) => ({ id: item.id, status: item.status, })); } if (include) { return filtered.map(hydratePayslip); } return filtered; }), findUnique: vi.fn(async ({ where }) => { const payslipRow = state.payslips.find((item) => item.id === where.id); return payslipRow ? hydratePayslip(payslipRow) : null; }), create: vi.fn(async ({ data }) => { const row = { id: PAYSLIP_IDS[state.payslips.length] ?? PAYSLIP_IDS[0], employee_id: data.employee_id, pay_month: data.pay_month, status: data.status, gross_amount: data.gross_amount, deduction_amount: data.deduction_amount, net_amount: data.net_amount, issued_at: data.issued_at ?? null, created_at: new Date("2026-04-30T08:00:00.000Z"), created_by: data.created_by, updated_at: new Date("2026-04-30T08:00:00.000Z"), updated_by: data.updated_by, }; state.payslips.push(row); state.payslipItems.push( ...(data.items?.create ?? []).map((item, index) => ({ id: `payslip-item-${state.payslipItems.length + index + 1}`, payslip_id: row.id, salary_item_id: item.salary_item_id, amount: item.amount, })), ); return row; }), update: vi.fn(async ({ where, data }) => { const index = state.payslips.findIndex((item) => item.id === where.id); state.payslips[index] = { ...state.payslips[index], ...data, updated_at: new Date("2026-04-30T09:00:00.000Z"), }; return state.payslips[index]; }), updateMany: vi.fn(async ({ where, data }) => { let count = 0; state.payslips = state.payslips.map((item) => { if (where.id?.in && where.id.in.includes(item.id)) { count += 1; return { ...item, ...data, }; } return item; }); return { count }; }), }; const payslipItem = { deleteMany: vi.fn(async ({ where }) => { state.payslipItems = state.payslipItems.filter((item) => item.payslip_id !== where.payslip_id); return { count: 1 }; }), createMany: vi.fn(async ({ data }) => { state.payslipItems.push( ...data.map((item, index) => ({ id: `payslip-item-${state.payslipItems.length + index + 1}`, payslip_id: item.payslip_id, salary_item_id: item.salary_item_id, amount: item.amount, })), ); return { count: data.length }; }), }; app.decorate("authenticate", async (request) => { request.employee = actor; }); app.decorate("requirePermission", (permissionCode) => async (request) => { request.employee = actor; const codes = actor.permissionCodes ?? []; if (!codes.includes("*") && !codes.includes(permissionCode)) { throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 }); } }); app.decorate("hasPermission", (employee, permissionCode) => { const codes = employee.permissionCodes ?? []; return codes.includes("*") || codes.includes(permissionCode); }); app.decorate("prisma", { employee: { findMany: vi.fn(async ({ where }) => { if (where?.status === "active") { return state.employees.filter((item) => item.status === "active"); } return [...state.employees]; }), findUnique: vi.fn(async ({ where }) => state.employees.find((item) => item.id === where.id) ?? null), }, salaryItem: { findMany: vi.fn(async ({ where }) => { if (where?.enabled === true) { return state.salaryItems.filter((item) => item.enabled); } if (where?.id?.in) { return state.salaryItems.filter((item) => where.id.in.includes(item.id)); } return [...state.salaryItems]; }), }, employeeSalary: { findMany: vi.fn(async ({ where, select }) => state.salaryRows.filter((item) => { if (where.employee_id?.in && !where.employee_id.in.includes(item.employee_id)) { return false; } if (where.effective_date?.lte && item.effective_date > where.effective_date.lte) { return false; } return true; }).map((item) => (select ? { ...item } : item)), ), }, payslip, payslipItem, auditLog: { create: vi.fn().mockResolvedValue({}), }, $transaction: vi.fn(async (callback) => callback(app.prisma)), }); 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(payrollRoutes, { prefix: "/api" }); return { app, state, payslip, payslipItem }; } describe("payroll payslip routes", () => { it("generates, edits and issues payslips and limits self view to issued records", async () => { const { app, state, payslipItem } = await buildApp(); const generateResponse = await app.inject({ method: "POST", url: "/api/payroll/payslips/generate", payload: { month: "2026-04" }, }); expect(generateResponse.statusCode).toBe(200); expect(generateResponse.json().data.summary).toEqual({ total: 2, generated: 2, }); expect(state.payslips).toHaveLength(2); const patchResponse = await app.inject({ method: "PATCH", url: `/api/payroll/payslips/${state.payslips[0].id}`, payload: { items: [ { salaryItemId: state.salaryItems[0].id, amount: 11000, }, { salaryItemId: state.salaryItems[1].id, amount: 500, }, ], }, }); expect(patchResponse.statusCode).toBe(200); expect(patchResponse.json().data).toMatchObject({ grossAmount: 11000, deductionAmount: 500, netAmount: 10500, status: "draft", }); expect(payslipItem.createMany).toHaveBeenCalledTimes(1); const issueResponse = await app.inject({ method: "POST", url: "/api/payroll/payslips/issue", payload: { month: "2026-04" }, }); expect(issueResponse.statusCode).toBe(200); expect(issueResponse.json().data.summary).toEqual({ total: 2, issued: 2, }); const frozenResponse = await app.inject({ method: "PATCH", url: `/api/payroll/payslips/${state.payslips[0].id}`, payload: { items: [ { salaryItemId: state.salaryItems[0].id, amount: 12000, }, ], }, }); expect(frozenResponse.statusCode).toBe(409); expect(frozenResponse.json().error.details).toEqual({ payslip: "payslip_not_editable", reasonCode: "payroll.payslip_not_editable" }); await app.close(); const selfApp = await buildApp({ actor: { id: EMPLOYEE_ID, permissionCodes: ["employee"], }, }); selfApp.state.payslips = state.payslips; selfApp.state.payslipItems = state.payslipItems; const selfResponse = await selfApp.app.inject({ method: "GET", url: `/api/payroll/employees/${EMPLOYEE_ID}/payslips`, }); expect(selfResponse.statusCode).toBe(200); expect(selfResponse.json().data.items).toHaveLength(1); expect(selfResponse.json().data.items[0].status).toBe("issued"); await selfApp.app.close(); }); it("fails generation when an active employee has no effective salary profile", async () => { const { app, state } = await buildApp({ omitProfileFor: [OTHER_EMPLOYEE_ID], }); const response = await app.inject({ method: "POST", url: "/api/payroll/payslips/generate", payload: { month: "2026-04" }, }); expect(response.statusCode).toBe(409); expect(response.json().error.details.month).toBe("salary_profile_missing"); expect(response.json().error.details.reasonCode).toBe("payroll.profiles_missing"); expect(state.payslips).toHaveLength(0); await app.close(); }); }); describe("payroll month guards", () => { it.each(["2026-00", "2026-13", "2026-1", "invalid", ""].flatMap((month) => [ ["GET", "/api/payroll/payslips", month], ["POST", "/api/payroll/payslips/generate", month], ["POST", "/api/payroll/payslips/issue", month], ]))("rejects %s %s month=%s before business access", async (method, url, month) => { const { app } = await buildApp(); try { const response = await app.inject({ method, url: method === "GET" ? `${url}?month=${month}` : url, ...(method === "POST" ? { payload: { month } } : {}) }); expect(response.statusCode).toBe(400); expect(response.json().error.code).toBe("VALID_001"); expect(response.json().error.details.reasonCode).toBe("payroll.month_invalid"); if (["2026-00", "2026-13"].includes(month)) expect(response.json().error.details).toEqual({ month: "invalid_month", reasonCode: "payroll.month_invalid" }); for (const [key, group] of Object.entries(app.prisma)) { if (key === "$transaction") expect(group).not.toHaveBeenCalled(); else for (const fn of Object.values(group)) expect(fn).not.toHaveBeenCalled(); } } finally { await app.close(); } }); it.each(["2024-01", "2024-02", "2024-12"])("queries the exact UTC month for %s", async (month) => { const { app } = await buildApp(); try { const response = await app.inject({ method: "GET", url: `/api/payroll/payslips?month=${month}` }); expect(response.statusCode).toBe(200); expect(response.json().data.month).toBe(month); expect(app.prisma.payslip.findMany.mock.calls[0][0].where.pay_month).toEqual(new Date(`${month}-01T00:00:00.000Z`)); } finally { await app.close(); } }); }); describe("payslip operation reasons", () => { function expectNoWrites(app) { for (const fn of [app.prisma.payslip.create, app.prisma.payslip.update, app.prisma.payslip.updateMany, app.prisma.payslipItem.createMany, app.prisma.payslipItem.deleteMany, app.prisma.auditLog.create]) { expect(fn).not.toHaveBeenCalled(); } } it.each([ ["already_generated", "month_already_generated", { month: "payslips_month_exists" }], ["no_employees", "active_employees_missing", { month: "no_active_employees" }], ["no_items", "enabled_items_missing", { items: "salary_items_empty" }], ])("explains generation blocker %s before writes", async (scenario, reason, details) => { const { app, state } = await buildApp(); if (scenario === "already_generated") state.payslips.push({ pay_month: new Date("2026-04-01T00:00:00.000Z") }); if (scenario === "no_employees") state.employees.length = 0; if (scenario === "no_items") state.salaryItems.length = 0; try { const response = await app.inject({ method: "POST", url: "/api/payroll/payslips/generate", payload: { month: "2026-04" } }); expect(response.statusCode).toBe(409); expect(response.json().error.details).toEqual({ ...details, reasonCode: `payroll.${reason}` }); expectNoWrites(app); } finally { await app.close(); } }); it("explains a concurrent month uniqueness conflict without success audit", async () => { const { app } = await buildApp(); app.prisma.payslip.create.mockRejectedValueOnce(Object.assign(new Error("synthetic conflict"), { code: "P2002" })); try { const response = await app.inject({ method: "POST", url: "/api/payroll/payslips/generate", payload: { month: "2026-04" } }); expect(response.statusCode).toBe(409); expect(response.json().error.details).toEqual({ month: "payslips_month_exists", reasonCode: "payroll.month_already_generated" }); expect(app.prisma.payslipItem.createMany).not.toHaveBeenCalled(); expect(app.prisma.auditLog.create).not.toHaveBeenCalled(); } finally { await app.close(); } }); it.each([false, true])("explains issue rejection with existing issued slips=%s", async (existing) => { const { app, state } = await buildApp(); if (existing) state.payslips.push({ id: PAYSLIP_IDS[0], pay_month: new Date("2026-04-01T00:00:00.000Z"), status: "issued" }); try { const response = await app.inject({ method: "POST", url: "/api/payroll/payslips/issue", payload: { month: "2026-04" } }); expect(response.statusCode).toBe(409); expect(response.json().error.details).toEqual({ month: existing ? "payslips_already_issued" : "payslips_not_generated", reasonCode: existing ? "payroll.month_already_issued" : "payroll.month_not_generated" }); expectNoWrites(app); } finally { await app.close(); } }); it.each([ [{ items: [] }, "payroll.payslip_update_input_invalid"], [{ items: [{ salaryItemId: "11111111-1111-4111-8111-111111111111", amount: "1.234" }] }, "payroll.amount_invalid"], ])("explains invalid payslip edit %j before reads", async (payload, reasonCode) => { const { app } = await buildApp(); try { const response = await app.inject({ method: "PATCH", url: `/api/payroll/payslips/${PAYSLIP_IDS[0]}`, payload }); expect(response.statusCode).toBe(400); expect(response.json().error.details.reasonCode).toBe(reasonCode); if (reasonCode === "payroll.amount_invalid") expect(response.json().error.details).toEqual({ items: { 0: { amount: "invalid_money_amount" } }, reasonCode }); expect(app.prisma.payslip.findUnique).not.toHaveBeenCalled(); expectNoWrites(app); } finally { await app.close(); } }); it("explains an unavailable item in an editable payslip before replacement", async () => { const { app, state } = await buildApp(); state.payslips.push({ id: PAYSLIP_IDS[0], pay_month: new Date("2026-04-01T00:00:00.000Z"), employee_id: EMPLOYEE_ID, status: "draft" }); app.prisma.salaryItem.findMany.mockResolvedValueOnce([]); try { const response = await app.inject({ method: "PATCH", url: `/api/payroll/payslips/${PAYSLIP_IDS[0]}`, payload: { items: [{ salaryItemId: "11111111-1111-4111-8111-111111111111", amount: 100 }] } }); expect(response.statusCode).toBe(400); expect(response.json().error.details).toEqual({ items: "salary_item_not_found", reasonCode: "payroll.item_not_found" }); expectNoWrites(app); expect(app.prisma.$transaction).not.toHaveBeenCalled(); } finally { await app.close(); } }); });