完善报销通知与付款进度(08-01-reimbursement-notification-progress-clarity)
ci-e2e / e2e (push) Canceled after 0s
ci-minimal / check-minimal (push) Canceled after 0s

这个提交包含在:
2026-08-01 21:06:31 +08:00
父节点 ca24479a44
当前提交 aa6b9bc373
共修改 23 个文件,包含 730 行新增和 88 行删除
@@ -17,6 +17,8 @@ const NOTIFICATION_TYPES = Object.freeze({
reimbursementRejected: 'reimbursement.rejected',
reimbursementReturned: 'reimbursement.returned',
reimbursementPaid: 'reimbursement.paid',
paymentBatchReviewRequested: 'payment_batch.review_requested',
paymentBatchExecutionRequested: 'payment_batch.execution_requested',
leaveApproved: 'leave.approved',
leaveRejected: 'leave.rejected',
attendanceCorrectionApproved: 'attendance_correction.approved',
@@ -39,6 +41,8 @@ const IM_SUPPORTED_NOTIFICATION_TYPES = Object.freeze([
NOTIFICATION_TYPES.reimbursementRejected,
NOTIFICATION_TYPES.reimbursementReturned,
NOTIFICATION_TYPES.reimbursementPaid,
NOTIFICATION_TYPES.paymentBatchReviewRequested,
NOTIFICATION_TYPES.paymentBatchExecutionRequested,
NOTIFICATION_TYPES.leaveApproved,
NOTIFICATION_TYPES.leaveRejected,
NOTIFICATION_TYPES.attendanceCorrectionApproved,
@@ -61,6 +65,8 @@ const NOTIFICATION_TYPE_TO_DOMAIN_SCOPE = Object.freeze({
[NOTIFICATION_TYPES.reimbursementRejected]: NOTIFICATION_DOMAIN_SCOPES.reimbursement,
[NOTIFICATION_TYPES.reimbursementReturned]: NOTIFICATION_DOMAIN_SCOPES.reimbursement,
[NOTIFICATION_TYPES.reimbursementPaid]: NOTIFICATION_DOMAIN_SCOPES.reimbursement,
[NOTIFICATION_TYPES.paymentBatchReviewRequested]: NOTIFICATION_DOMAIN_SCOPES.reimbursement,
[NOTIFICATION_TYPES.paymentBatchExecutionRequested]: NOTIFICATION_DOMAIN_SCOPES.reimbursement,
[NOTIFICATION_TYPES.leaveApproved]: NOTIFICATION_DOMAIN_SCOPES.leave,
[NOTIFICATION_TYPES.leaveRejected]: NOTIFICATION_DOMAIN_SCOPES.leave,
[NOTIFICATION_TYPES.attendanceCorrectionApproved]: NOTIFICATION_DOMAIN_SCOPES.attendance,
+150 -4
查看文件
@@ -11,6 +11,7 @@ const { parseDateOnlyString } = require("../utils/date");
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
const { createNotificationsWithRecords } = require("../services/notifications");
const { NOTIFICATION_TYPES } = require("../constants/notificationTypes");
const { resolvePermissionsForRoles, hasPermission } = require("../constants/permissions");
const { sendNotificationEmailSafe } = require("../services/email");
const { flushNotificationDispatchTasks } = require("../services/notificationDispatcher");
const { enqueueReimbursementJournalExport } = require("../services/integrations/erpJournal");
@@ -247,6 +248,118 @@ function ensureBatchReviewPermission(fastify, request) {
}
}
function roleCodesOf(employee) {
return (employee?.roles ?? []).map((role) => role.role_code).filter(Boolean);
}
function employeeHasRolePermission(employee, permissionCode) {
return hasPermission(resolvePermissionsForRoles(roleCodesOf(employee)), permissionCode);
}
async function resolvePaymentReviewRecipientIds(tx, makerId) {
const candidates = await tx.employee.findMany({
where: {
status: "active",
id: { not: makerId },
roles: { some: { role_code: { in: ["manager", "ceo"] } } },
},
orderBy: [{ employee_no: "asc" }, { id: "asc" }],
select: {
id: true,
roles: { select: { role_code: true } },
},
});
return candidates
.filter((employee) => employeeHasRolePermission(employee, "payment.batch.review"))
.map((employee) => employee.id);
}
async function resolvePaymentExecutionRecipientIds(tx, { makerId, reviewerId }) {
const candidates = await tx.employee.findMany({
where: {
status: "active",
id: { not: reviewerId },
OR: [
{ id: makerId },
{ roles: { some: { role_code: { in: ["finance", "finance_mgr"] } } } },
],
},
orderBy: [{ employee_no: "asc" }, { id: "asc" }],
select: {
id: true,
roles: { select: { role_code: true } },
},
});
const eligible = candidates.filter((employee) =>
employee.id !== reviewerId && employeeHasRolePermission(employee, "payment.batch.manage"),
);
const activeMaker = eligible.find((employee) => employee.id === makerId);
if (activeMaker) {
return [activeMaker.id];
}
return eligible
.filter((employee) => roleCodesOf(employee).some((roleCode) => ["finance", "finance_mgr"].includes(roleCode)))
.map((employee) => employee.id);
}
async function createPaymentResponsibilityNotification(tx, {
recipientEmployeeIds,
type,
title,
body,
batchId,
actorId,
}) {
const notifications = await createNotificationsWithRecords(tx, {
recipientEmployeeIds,
type,
title,
body,
targetType: "payment_batch",
targetId: batchId,
});
return {
notifications,
type,
title,
body,
targetType: "payment_batch",
targetId: batchId,
targetPath: `/payment-batches?id=${encodeURIComponent(batchId)}`,
actorId,
};
}
async function dispatchPaymentResponsibilityNotification(fastify, request, task) {
if (!task?.notifications?.length) {
return;
}
try {
await flushNotificationDispatchTasks({
prisma: fastify.prisma,
config: fastify.config,
logger: fastify.log,
requestId: request.id,
tasks: [task],
});
} catch (error) {
fastify.log.error(
{
err: error,
requestId: request.id,
notificationType: task.type,
targetType: task.targetType,
targetId: task.targetId,
},
"Failed to dispatch payment responsibility notification",
);
}
}
function buildBatchNo() {
const now = new Date();
const date = now.toISOString().slice(0, 10).replace(/-/g, "");
@@ -1057,7 +1170,7 @@ async function paymentBatchesRoutes(fastify) {
}
const entityIds = Array.from(new Set(body.entityIds)).sort();
const created = await fastify.prisma.$transaction(async (tx) => {
const { batch: created, notificationTask } = await fastify.prisma.$transaction(async (tx) => {
await lockPaymentEntities(tx, body.entityType, entityIds);
const snapshots = await loadEntitySnapshots(tx, body.entityType, entityIds);
if (snapshots.length !== entityIds.length) {
@@ -1130,9 +1243,24 @@ async function paymentBatchesRoutes(fastify) {
}),
});
return loadBatchWithItems(tx, batch.id);
const recipientEmployeeIds = await resolvePaymentReviewRecipientIds(tx, request.employee.id);
const nextNotificationTask = await createPaymentResponsibilityNotification(tx, {
recipientEmployeeIds,
type: NOTIFICATION_TYPES.paymentBatchReviewRequested,
title: "待付款复核",
body: "付款安排已创建,请完成付款复核。",
batchId: batch.id,
actorId: request.employee.id,
});
return {
batch: await loadBatchWithItems(tx, batch.id),
notificationTask: nextNotificationTask,
};
});
await dispatchPaymentResponsibilityNotification(fastify, request, notificationTask);
return reply.code(201).send({ requestId: request.id, data: { item: mapBatch(created, []) } });
});
@@ -1590,7 +1718,7 @@ async function paymentBatchesRoutes(fastify) {
const batchId = parseId(request.params?.id);
const body = parseBody(REVIEW_SCHEMA, request.body);
const result = await fastify.prisma.$transaction(async (tx) => {
const { batch: result, notificationTask } = await fastify.prisma.$transaction(async (tx) => {
const batch = await lockBatchWithItems(tx, batchId);
await ensureBatchSourceDepartmentsEnabled(fastify, tx, batch);
const batchRisk = summarizeBatchRisk(batch);
@@ -1659,9 +1787,27 @@ async function paymentBatchesRoutes(fastify) {
}),
});
return reviewed;
const recipientEmployeeIds = await resolvePaymentExecutionRecipientIds(tx, {
makerId: batch.created_by,
reviewerId: request.employee.id,
});
const nextNotificationTask = await createPaymentResponsibilityNotification(tx, {
recipientEmployeeIds,
type: NOTIFICATION_TYPES.paymentBatchExecutionRequested,
title: "待完成付款",
body: "付款复核已通过,请完成付款并登记回单。",
batchId,
actorId: request.employee.id,
});
return {
batch: reviewed,
notificationTask: nextNotificationTask,
};
});
await dispatchPaymentResponsibilityNotification(fastify, request, notificationTask);
return sendData(reply, request, { item: mapBatch(result, []) });
});
+16 -13
查看文件
@@ -333,8 +333,8 @@ const PROCESSING_STAGE_DEFINITIONS = Object.freeze([
{ key: "submitted", label: "申请提交" },
{ key: "manager_approval", label: "主管审批" },
{ key: "finance_review", label: "财务复核" },
{ key: "payment_batch_review", label: "付款批次复核" },
{ key: "payment_and_receipt", label: "付款与回单" },
{ key: "payment_batch_review", label: "付款复核" },
{ key: "payment_and_receipt", label: "付款完成" },
]);
function isoDateTimeOrNull(value) {
@@ -511,31 +511,34 @@ function buildProcessingProgress({ reimbursement, workflowInstance, paymentBatch
if (!batch) {
Object.assign(batchReviewStage, reimbursement.status === "approved"
? { state: "current", result: "待建批次", detail: "待财务创建付款批次" }
: { detail: "待财务创建付款批次" });
paymentStage.detail = "待付款批次复核后处理";
? { state: "current", result: "待安排", detail: "待财务安排付款" }
: { detail: "待财务安排付款" });
paymentStage.detail = "待付款复核后由财务登记,非审批环节";
} else if (batch.status === "draft") {
Object.assign(batchReviewStage, {
state: "current",
result: "待复核",
detail: "所在付款批次待非制单人复核",
detail: "待非制单人复核付款",
targetHref: batchTargetHref,
});
Object.assign(paymentStage, {
detail: "待付款复核通过后由财务登记,非审批环节",
targetHref: batchTargetHref,
});
Object.assign(paymentStage, { detail: "待所在付款批次复核通过", targetHref: batchTargetHref });
} else if (["reviewed", "executed", "failed"].includes(batch.status)) {
Object.assign(batchReviewStage, {
state: "completed",
actorName: paymentActorNames.get(batch.reviewed_by) ?? null,
occurredAt: isoDateTimeOrNull(batch.reviewed_at),
result: "通过",
detail: batch.status === "reviewed" ? "所在付款批次已复核,待执行付款" : null,
detail: batch.status === "reviewed" ? "付款复核已通过" : null,
targetHref: batchTargetHref,
});
if (batch.status === "reviewed") {
Object.assign(paymentStage, {
state: "current",
result: "待付款",
detail: "所在付款批次已复核,待执行付款",
detail: "待财务完成付款并登记回单,非审批环节",
targetHref: batchTargetHref,
});
} else if (batch.status === "failed") {
@@ -544,7 +547,7 @@ function buildProcessingProgress({ reimbursement, workflowInstance, paymentBatch
actorName: paymentActorNames.get(batch.executed_by) ?? null,
occurredAt: isoDateTimeOrNull(batch.executed_at),
result: "付款失败",
detail: "所在付款批次执行失败,待财务重新处理",
detail: "付款失败,待财务重新处理,非审批环节",
targetHref: batchTargetHref,
});
}
@@ -555,11 +558,11 @@ function buildProcessingProgress({ reimbursement, workflowInstance, paymentBatch
occurredAt: isoDateTimeOrNull(batch.cancelled_at),
result: "批次已取消",
comment: batch.cancelled_reason ?? null,
detail: "所在付款批次已取消,待财务重新创建",
detail: "付款安排已取消,待财务重新处理",
targetHref: batchTargetHref,
});
Object.assign(paymentStage, {
detail: "待财务重新创建付款批次",
detail: "待财务重新安排付款,非审批环节",
targetHref: batchTargetHref,
});
}
@@ -571,7 +574,7 @@ function buildProcessingProgress({ reimbursement, workflowInstance, paymentBatch
actorName: reimbursement.paid_by_employee?.name ?? paymentActorNames.get(batch?.executed_by) ?? null,
occurredAt: isoDateTimeOrNull(reimbursement.paid_at ?? batch?.executed_at),
result: "已付款",
detail: receiptCount > 0 ? "付款与回单已留存" : "付款已完成,回单待留存",
detail: receiptCount > 0 ? "付款和回单已留存" : "付款已完成,回单待留存",
targetHref: batchTargetHref,
});
}
@@ -20,4 +20,21 @@ describe("notification types", () => {
NOTIFICATION_DOMAIN_SCOPES.workflow,
);
});
it("routes payment responsibility notifications through the reimbursement IM domain", () => {
expect(IM_SUPPORTED_NOTIFICATION_TYPES).toEqual(
expect.arrayContaining([
NOTIFICATION_TYPES.paymentBatchReviewRequested,
NOTIFICATION_TYPES.paymentBatchExecutionRequested,
]),
);
expect(resolveNotificationDomainScope(
NOTIFICATION_TYPES.paymentBatchReviewRequested,
"payment_batch",
)).toBe(NOTIFICATION_DOMAIN_SCOPES.reimbursement);
expect(resolveNotificationDomainScope(
NOTIFICATION_TYPES.paymentBatchExecutionRequested,
"payment_batch",
)).toBe(NOTIFICATION_DOMAIN_SCOPES.reimbursement);
});
});
@@ -211,6 +211,10 @@ function buildPrisma(options = {}) {
},
receiptAttachments: options.receiptAttachments ?? defaultReceiptAttachments,
reservedEntityIds: options.reservedEntityIds ?? [],
employees: options.employees ?? [
{ id: MAKER_ID, employee_no: "FIN001", status: "active", roles: [{ role_code: "finance" }] },
{ id: REVIEWER_ID, employee_no: "MGR001", status: "active", roles: [{ role_code: "manager" }] },
],
invoice: {
linked_reimbursement_id: REIMBURSEMENT_ID,
status: "bound",
@@ -421,6 +425,9 @@ function buildPrisma(options = {}) {
auditLog: {
create: vi.fn(async () => ({ id: "audit-1" })),
},
employee: {
findMany: vi.fn(async () => state.employees.map((employee) => ({ ...employee }))),
},
$queryRaw: vi.fn(async () => [{ id: BATCH_ID }]),
};
@@ -657,6 +664,33 @@ describe("payment batch reimbursement routes", () => {
expect(response.statusCode).toBe(409);
expect(response.json().error.details.review).toBe("maker_checker_conflict");
expect(createNotificationsWithRecordsMock).not.toHaveBeenCalled();
expect(flushNotificationDispatchTasksMock).not.toHaveBeenCalled();
await app.close();
});
it("rejects repeated payment review without creating another responsibility notification", async () => {
const { app } = await buildApp({
actor: {
id: REVIEWER_ID,
department_id: "dept-1",
permissionCodes: ["payment.batch.review"],
roleCodes: ["manager"],
},
});
const response = await app.inject({
method: "POST",
url: `/api/payment-batches/${BATCH_ID}/review`,
headers: { authorization: "Bearer test" },
payload: {},
});
expect(response.statusCode).toBe(409);
expect(response.json().error.details.review).toBe("batch_not_reviewable");
expect(createNotificationsWithRecordsMock).not.toHaveBeenCalled();
expect(flushNotificationDispatchTasksMock).not.toHaveBeenCalled();
await app.close();
});
@@ -756,6 +790,9 @@ describe("payment batch reimbursement routes", () => {
});
it("allows one manager review for a high-amount batch and does not require a second reviewer", async () => {
createNotificationsWithRecordsMock.mockResolvedValueOnce([
{ id: "notif-execute-1", recipient_employee_id: MAKER_ID },
]);
const { app } = await buildApp({
actor: {
id: REVIEWER_ID,
@@ -783,7 +820,7 @@ describe("payment batch reimbursement routes", () => {
payload: { comment: "已核对高额付款对象和金额" },
});
expect(response.statusCode).toBe(200);
expect(response.statusCode, response.body).toBe(200);
expect(response.json().data.item).toMatchObject({
status: "reviewed",
highRisk: true,
@@ -794,6 +831,65 @@ describe("payment batch reimbursement routes", () => {
reviewerPermission: "payment.batch.review",
},
});
expect(createNotificationsWithRecordsMock).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
recipientEmployeeIds: [MAKER_ID],
type: "payment_batch.execution_requested",
targetType: "payment_batch",
targetId: BATCH_ID,
}),
);
expect(flushNotificationDispatchTasksMock).toHaveBeenCalledWith(
expect.objectContaining({
tasks: [expect.objectContaining({
type: "payment_batch.execution_requested",
targetPath: `/payment-batches?id=${BATCH_ID}`,
})],
}),
);
await app.close();
});
it("falls back to another active finance payment manager after review when the maker is unavailable", async () => {
const fallbackFinanceId = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
createNotificationsWithRecordsMock.mockResolvedValueOnce([
{ id: "notif-execute-fallback", recipient_employee_id: fallbackFinanceId },
]);
const { app } = await buildApp({
actor: {
id: REVIEWER_ID,
department_id: "dept-1",
permissionCodes: ["payment.batch.review"],
roleCodes: ["manager"],
},
batch: {
status: "draft",
reviewed_at: null,
reviewed_by: null,
},
employees: [
{ id: fallbackFinanceId, employee_no: "FIN002", status: "active", roles: [{ role_code: "finance" }] },
{ id: REVIEWER_ID, employee_no: "MGR001", status: "active", roles: [{ role_code: "manager" }] },
],
});
const response = await app.inject({
method: "POST",
url: `/api/payment-batches/${BATCH_ID}/review`,
headers: { authorization: "Bearer test" },
payload: {},
});
expect(response.statusCode, response.body).toBe(200);
expect(createNotificationsWithRecordsMock).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
recipientEmployeeIds: [fallbackFinanceId],
type: "payment_batch.execution_requested",
}),
);
await app.close();
});
@@ -898,6 +994,98 @@ describe("payment batch reimbursement routes", () => {
await app.close();
});
it("notifies active non-maker payment reviewers after creating a reimbursement batch", async () => {
createNotificationsWithRecordsMock.mockResolvedValueOnce([
{ id: "notif-review-1", recipient_employee_id: REVIEWER_ID },
]);
const { app, tx } = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/payment-batches",
headers: { authorization: "Bearer test" },
payload: {
entityType: "reimbursement",
name: "本周付款",
entityIds: [REIMBURSEMENT_ID],
},
});
expect(response.statusCode).toBe(201);
expect(createNotificationsWithRecordsMock).toHaveBeenCalledWith(
tx,
expect.objectContaining({
recipientEmployeeIds: [REVIEWER_ID],
type: "payment_batch.review_requested",
targetType: "payment_batch",
targetId: BATCH_ID,
}),
);
expect(flushNotificationDispatchTasksMock).toHaveBeenCalledWith(
expect.objectContaining({
tasks: [expect.objectContaining({
type: "payment_batch.review_requested",
targetPath: `/payment-batches?id=${BATCH_ID}`,
})],
}),
);
await app.close();
});
it("creates no payment review notification when no eligible non-maker reviewer exists", async () => {
const { app } = await buildApp({
employees: [
{ id: ACTOR_ID, employee_no: "FIN001", status: "active", roles: [{ role_code: "finance" }] },
],
});
const response = await app.inject({
method: "POST",
url: "/api/payment-batches",
headers: { authorization: "Bearer test" },
payload: {
entityType: "reimbursement",
name: "无人复核批次",
entityIds: [REIMBURSEMENT_ID],
},
});
expect(response.statusCode).toBe(201);
expect(createNotificationsWithRecordsMock).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ recipientEmployeeIds: [] }),
);
expect(flushNotificationDispatchTasksMock).not.toHaveBeenCalled();
await app.close();
});
it("keeps a created batch when payment review notification delivery fails", async () => {
createNotificationsWithRecordsMock.mockResolvedValueOnce([
{ id: "notif-review-failed", recipient_employee_id: REVIEWER_ID },
]);
flushNotificationDispatchTasksMock.mockRejectedValueOnce(new Error("synthetic dispatch failure"));
const { app, state } = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/payment-batches",
headers: { authorization: "Bearer test" },
payload: {
entityType: "reimbursement",
name: "投递失败不回滚",
entityIds: [REIMBURSEMENT_ID],
},
});
expect(response.statusCode).toBe(201);
expect(state.batch.status).toBe("draft");
expect(state.batch.items).toHaveLength(1);
await app.close();
});
it("adds a non-identifying random suffix to concurrent-style batch numbers", async () => {
const { app, tx } = await buildApp();
const payload = {
@@ -322,7 +322,7 @@ describe("GET /api/reimbursements/:id detail enhancements", () => {
expect.objectContaining({ key: "submitted", state: "completed", actorName: "李四", result: "已提交" }),
expect.objectContaining({ key: "approval_manager-task", label: "主管审批", state: "completed", actorName: "王经理", result: "通过" }),
expect.objectContaining({ key: "approval_finance-task", label: "财务审批", state: "current", actorName: "财务专员", result: "处理中" }),
expect.objectContaining({ key: "payment_batch_review", state: "pending", actorName: null, detail: "待财务创建付款批次" }),
expect.objectContaining({ key: "payment_batch_review", state: "pending", actorName: null, detail: "待财务安排付款" }),
expect.objectContaining({ key: "payment_and_receipt", state: "pending", actorName: null }),
]);
@@ -598,11 +598,11 @@ describe("GET /api/reimbursements/:id detail enhancements", () => {
});
it.each([
["draft", "current", "pending", "待所在付款批次复核通过"],
["reviewed", "completed", "current", "所在付款批次已复核,待执行付款"],
["executed", "completed", "completed", "付款与回单已留存"],
["failed", "completed", "exception", "所在付款批次执行失败,待财务重新处理"],
["cancelled", "exception", "pending", "待财务重新创建付款批次"],
["draft", "current", "pending", "待付款复核通过后由财务登记,非审批环节"],
["reviewed", "completed", "current", "待财务完成付款并登记回单,非审批环节"],
["executed", "completed", "completed", "付款和回单已留存"],
["failed", "completed", "exception", "付款失败,待财务重新处理,非审批环节"],
["cancelled", "exception", "pending", "待财务重新安排付款,非审批环节"],
])("maps %s payment batch without exposing a batch link to ordinary applicants", async (status, reviewState, paymentState, detail) => {
const paymentBatchItem = {
id: "batch-item-1",
@@ -670,7 +670,7 @@ describe("GET /api/reimbursements/:id detail enhancements", () => {
});
expect(response.statusCode).toBe(200);
expect(response.json().data.processingProgress.stages[3]).toMatchObject({
detail: "所在付款批次待非制单人复核",
detail: "待非制单人复核付款",
actorName: null,
targetHref: "/payment-batches?id=batch-1",
});
@@ -691,8 +691,8 @@ describe("GET /api/reimbursements/:id detail enhancements", () => {
expect(response.json().data.processingProgress.stages[3]).toMatchObject({
state: "current",
actorName: null,
result: "待建批次",
detail: "待财务创建付款批次",
result: "待安排",
detail: "待财务安排付款",
});
await app.close();