R52 A1-A6:完成 AP 运营深度操作
- AP 概览页 Tab 工作台化(待付款/异常付款/风险标记/对账异常) - AP 导出端点支持 CSV/XLSX 与筛选 - 风险标记 resolve/dismiss 支持说明审计留痕 - 支付批次深链、高风险复核提示、对账确认权限收口 - OpenClaw 浏览器级回归全部通过
这个提交包含在:
@@ -1,6 +1,48 @@
|
|||||||
import { apiRequestData } from "./http";
|
import { apiRequestBlob, apiRequestData } from "./http";
|
||||||
import type { RiskFlag } from "./feeControl";
|
import type { RiskFlag } from "./feeControl";
|
||||||
|
|
||||||
|
export type ApOperationsExportFormat = "csv" | "xlsx";
|
||||||
|
export type ApOperationsRiskBucket = "all" | "exception" | "budget_overspend";
|
||||||
|
export type ApOperationsPendingEntityType = "reimbursement" | "travel_order";
|
||||||
|
|
||||||
|
export type ApPendingPaymentBatchSummary = {
|
||||||
|
id: string;
|
||||||
|
batchNo: string;
|
||||||
|
entityType: string;
|
||||||
|
name: string;
|
||||||
|
status: string;
|
||||||
|
totalAmount: string;
|
||||||
|
highRisk: boolean;
|
||||||
|
createdAt: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ApFailedPaymentBatchItemSummary = {
|
||||||
|
id: string;
|
||||||
|
paymentBatchId: string;
|
||||||
|
entityId: string;
|
||||||
|
entityCode: string;
|
||||||
|
entityTitle: string;
|
||||||
|
amount: string;
|
||||||
|
currencyCode: string;
|
||||||
|
failureCode: string | null;
|
||||||
|
failureMessage: string | null;
|
||||||
|
createdAt: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ApPartialMatchItemSummary = {
|
||||||
|
id: string;
|
||||||
|
travelReconciliationBatchId: string;
|
||||||
|
travelOrderId: string | null;
|
||||||
|
travelRequestId: string | null;
|
||||||
|
matchStatus: string;
|
||||||
|
resolutionStatus: string;
|
||||||
|
anomalyCode: string | null;
|
||||||
|
orderAmount: string | null;
|
||||||
|
transactionAmount: string | null;
|
||||||
|
currency: string;
|
||||||
|
createdAt: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
export type ApOperationsSummary = {
|
export type ApOperationsSummary = {
|
||||||
summary: {
|
summary: {
|
||||||
pendingPaymentCount: number;
|
pendingPaymentCount: number;
|
||||||
@@ -8,13 +50,29 @@ export type ApOperationsSummary = {
|
|||||||
exceptionCount: number;
|
exceptionCount: number;
|
||||||
budgetOverspendCount: number;
|
budgetOverspendCount: number;
|
||||||
};
|
};
|
||||||
pendingPaymentBatches: Array<{ id: string; batchNo: string; entityType: string; name: string; status: string; totalAmount: string; highRisk: boolean; createdAt: string | null }>;
|
pendingPaymentBatches: ApPendingPaymentBatchSummary[];
|
||||||
failedPaymentBatchItems: Array<{ id: string; paymentBatchId: string; entityId: string; entityCode: string; entityTitle: string; amount: string; currencyCode: string; failureCode: string | null; failureMessage: string | null; createdAt: string | null }>;
|
failedPaymentBatchItems: ApFailedPaymentBatchItemSummary[];
|
||||||
exceptionRiskFlags: RiskFlag[];
|
exceptionRiskFlags: RiskFlag[];
|
||||||
budgetOverspendRisks: RiskFlag[];
|
budgetOverspendRisks: RiskFlag[];
|
||||||
partialMatchItems: Array<{ id: string; travelReconciliationBatchId: string; travelOrderId: string | null; travelRequestId: string | null; matchStatus: string; resolutionStatus: string; anomalyCode: string | null; orderAmount: string | null; transactionAmount: string | null; currency: string; createdAt: string | null }>;
|
partialMatchItems: ApPartialMatchItemSummary[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function fetchApOperations() {
|
export async function fetchApOperations() {
|
||||||
return apiRequestData<ApOperationsSummary>("/api/ap-operations");
|
return apiRequestData<ApOperationsSummary>("/api/ap-operations");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function exportApOperations(params: {
|
||||||
|
format: ApOperationsExportFormat;
|
||||||
|
pendingEntityType?: ApOperationsPendingEntityType;
|
||||||
|
pendingCreatedAtFrom?: string;
|
||||||
|
pendingCreatedAtTo?: string;
|
||||||
|
riskBucket?: ApOperationsRiskBucket;
|
||||||
|
}) {
|
||||||
|
return apiRequestBlob("/api/exports/ap-operations", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"content-type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(params),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -35,6 +35,25 @@ export type PrecheckResponse = {
|
|||||||
nextActions: string[];
|
nextActions: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type RiskFlagListResponse = {
|
||||||
|
items: RiskFlag[];
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildRiskFlagsSearch(query: {
|
||||||
|
entityType?: string;
|
||||||
|
entityId?: string;
|
||||||
|
status?: "open" | "resolved" | "dismissed";
|
||||||
|
source?: string;
|
||||||
|
}) {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (query.entityType) params.set("entityType", query.entityType);
|
||||||
|
if (query.entityId) params.set("entityId", query.entityId);
|
||||||
|
if (query.status) params.set("status", query.status);
|
||||||
|
if (query.source) params.set("source", query.source);
|
||||||
|
const search = params.toString();
|
||||||
|
return search ? `?${search}` : "";
|
||||||
|
}
|
||||||
|
|
||||||
export async function precheckEntity(payload: {
|
export async function precheckEntity(payload: {
|
||||||
entityType: "reimbursement" | "purchase_request" | "travel_request";
|
entityType: "reimbursement" | "purchase_request" | "travel_request";
|
||||||
entityId: string;
|
entityId: string;
|
||||||
@@ -44,3 +63,26 @@ export async function precheckEntity(payload: {
|
|||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function fetchRiskFlags(query: {
|
||||||
|
entityType?: string;
|
||||||
|
entityId?: string;
|
||||||
|
status?: "open" | "resolved" | "dismissed";
|
||||||
|
source?: string;
|
||||||
|
} = {}) {
|
||||||
|
return apiRequestData<RiskFlagListResponse>(`/api/risk-flags${buildRiskFlagsSearch(query)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveRiskFlag(riskFlagId: string, payload: { note?: string | null } = {}) {
|
||||||
|
return apiRequestData<{ item: RiskFlag }>(`/api/risk-flags/${riskFlagId}/resolve`, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function dismissRiskFlag(riskFlagId: string, payload: { note?: string | null } = {}) {
|
||||||
|
return apiRequestData<{ item: RiskFlag }>(`/api/risk-flags/${riskFlagId}/dismiss`, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
+1320
-55
文件差异内容过多而无法显示
加载差异
@@ -1,5 +1,6 @@
|
|||||||
import { useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useSearchParams } from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
cancelPaymentBatch,
|
cancelPaymentBatch,
|
||||||
createPaymentBatch,
|
createPaymentBatch,
|
||||||
@@ -35,9 +36,9 @@ function resolveError(error: unknown) {
|
|||||||
export function PaymentBatchesPage() {
|
export function PaymentBatchesPage() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { permissions } = useAuth();
|
const { permissions } = useAuth();
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
const canManageBatch = hasPermission(permissions, "payment.batch.manage");
|
const canManageBatch = hasPermission(permissions, "payment.batch.manage");
|
||||||
const canReviewBatch = hasPermission(permissions, "risk.review.manage");
|
const canReviewBatch = hasPermission(permissions, "risk.review.manage");
|
||||||
const [selectedBatchId, setSelectedBatchId] = useState("");
|
|
||||||
const [entityType, setEntityType] = useState<PaymentBatchEntityType>("reimbursement");
|
const [entityType, setEntityType] = useState<PaymentBatchEntityType>("reimbursement");
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [entityIds, setEntityIds] = useState("");
|
const [entityIds, setEntityIds] = useState("");
|
||||||
@@ -51,10 +52,24 @@ export function PaymentBatchesPage() {
|
|||||||
queryFn: () => fetchPaymentBatches(),
|
queryFn: () => fetchPaymentBatches(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const selectedBatchId = searchParams.get("id") ?? "";
|
||||||
const selectedBatch = useMemo<PaymentBatch | null>(() => {
|
const selectedBatch = useMemo<PaymentBatch | null>(() => {
|
||||||
const items = listQuery.data?.items ?? [];
|
const items = listQuery.data?.items ?? [];
|
||||||
return items.find((item) => item.id === selectedBatchId) ?? items[0] ?? null;
|
return items.find((item) => item.id === selectedBatchId) ?? items[0] ?? null;
|
||||||
}, [listQuery.data?.items, selectedBatchId]);
|
}, [listQuery.data?.items, selectedBatchId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selectedBatch) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (selectedBatch.id === selectedBatchId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const next = new URLSearchParams(searchParams);
|
||||||
|
next.set("id", selectedBatch.id);
|
||||||
|
setSearchParams(next, { replace: true });
|
||||||
|
}, [searchParams, selectedBatch, selectedBatchId, setSearchParams]);
|
||||||
|
|
||||||
const canEditSelectedBatch = canManageBatch && selectedBatch?.status === "draft";
|
const canEditSelectedBatch = canManageBatch && selectedBatch?.status === "draft";
|
||||||
const canReviewSelectedBatch =
|
const canReviewSelectedBatch =
|
||||||
canReviewBatch &&
|
canReviewBatch &&
|
||||||
@@ -90,7 +105,9 @@ export function PaymentBatchesPage() {
|
|||||||
}),
|
}),
|
||||||
onSuccess: async ({ item }) => {
|
onSuccess: async ({ item }) => {
|
||||||
setError("");
|
setError("");
|
||||||
setSelectedBatchId(item.id);
|
const next = new URLSearchParams(searchParams);
|
||||||
|
next.set("id", item.id);
|
||||||
|
setSearchParams(next, { replace: true });
|
||||||
await refresh();
|
await refresh();
|
||||||
toast.success("付款批次已创建");
|
toast.success("付款批次已创建");
|
||||||
},
|
},
|
||||||
@@ -257,7 +274,11 @@ export function PaymentBatchesPage() {
|
|||||||
key={item.id}
|
key={item.id}
|
||||||
type="button"
|
type="button"
|
||||||
className={selectedBatch?.id === item.id ? "w-full rounded-lg border border-primary bg-primary/5 px-3 py-3 text-left" : "w-full rounded-lg border border-zinc-200 px-3 py-3 text-left hover:bg-zinc-50"}
|
className={selectedBatch?.id === item.id ? "w-full rounded-lg border border-primary bg-primary/5 px-3 py-3 text-left" : "w-full rounded-lg border border-zinc-200 px-3 py-3 text-left hover:bg-zinc-50"}
|
||||||
onClick={() => setSelectedBatchId(item.id)}
|
onClick={() => {
|
||||||
|
const next = new URLSearchParams(searchParams);
|
||||||
|
next.set("id", item.id);
|
||||||
|
setSearchParams(next, { replace: true });
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
<div className="font-medium text-zinc-900">{item.batchNo}</div>
|
<div className="font-medium text-zinc-900">{item.batchNo}</div>
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
|
||||||
|
"A1","R52 执行合同建档与范围冻结","创建并校验 R52 AP 运营深度操作执行合同 CSV,冻结范围仅包含 AP 概览页工作台化、AP 导出端点、风险标记说明审计留痕、支付批次/风险标记/对账异常快捷操作接入;明确本轮不做 Prisma 迁移、不新增重复业务端点。","issues/2026-04-06_r52-ap-operations.csv 列完整、Dependencies 为 JSON 数组字符串、Test_Method 可复现;范围仅覆盖 R52,不混入 R48-R51 收尾或新的 AP 业务模型设计。","命令:python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-04-06_r52-ap-operations.csv。检查:1) 对照 AGENTS.md 与 issues/README.md 确认 12 列完整;2) A2-A6 依赖链符合 backend→frontend→reviewer→qa 收口;3) 方案明确复用现有 travel reconciliation confirm 端点,不新增 Prisma 迁移。","manual","DONE","DONE","DONE","issues/2026-04-06_r52-ap-operations.csv","[]","回滚路径:删除本次 CSV 不影响业务。2026-04-06:Issue CSV 已创建并通过 validate_issues_csv.py 校验,范围与依赖已冻结。"
|
||||||
|
"A2","AP 导出端点与风险说明审计留痕扩展","在 exports.js 新增 POST /api/exports/ap-operations,并扩展 riskFlags resolve/dismiss 接口接收可选 note,仅写入 audit extra.note,不新增数据库字段。","POST /api/exports/ap-operations 支持 csv/xlsx 与待付款筛选、风险 bucket 过滤;导出一次包含待付款批次、异常付款项、开放风险标记、对账异常四块数据;POST /api/risk-flags/:id/resolve|dismiss 保持原权限与响应结构,新增 note 能进入审计日志 extra.note。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && npx prisma validate && node --check src/routes/exports.js && node --check src/routes/riskFlags.js && npm test -- server/tests/unit/routes/exports.apOperations.test.js server/tests/unit/routes/riskFlags.test.js。业务:1) 导出 CSV/XLSX 含四块数据且应用当前筛选;2) 风险标记解决/驳回可提交 note,状态流不变且 audit extra.note 可见。","manual","DONE","DONE","DONE","server/src/routes/exports.js|server/src/routes/riskFlags.js|server/tests/unit/routes/exports.apOperations.test.js|server/tests/unit/routes/riskFlags.test.js","[""A1""]","回滚路径:移除 AP 导出端点并恢复 riskFlags resolve/dismiss 仅接收空 body 的旧行为。无 Prisma 迁移,回退仅需代码回滚。2026-04-06:npx prisma validate、node --check、exports.apOperations.test.js 与 riskFlags.test.js 通过。"
|
||||||
|
"A3","AP 概览页 Tab 化与待付款/异常付款快捷操作","重构 ApOperationsPage 为摘要卡片 + Tabs 工作台,新增刷新与导出按钮,并接入待付款批次筛选、快捷复核、快捷取消、失败付款项重试/详情/关联跳转;同时为 PaymentBatchesPage 补 ?id= 深链选中能力。","AP 页支持待付款、异常付款、风险标记、对账异常四个 Tab;待付款可按实体类型与创建时间范围本地筛选,并复用原 review/cancel/execute 接口完成操作;PaymentBatchesPage 访问 /payment-batches?id=<batchId> 时能定位到指定批次,不影响原页面交互。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) 待付款 tab 可筛选并从 AP 页直接复核/取消;2) 高风险批次快捷复核时出现“此批次为高风险,需二次复核”提示;3) 异常付款 tab 可查看失败详情、确认后重试执行、跳到报销详情或差旅申请详情。","manual","DONE","DONE","DONE","client/src/pages/ApOperationsPage.tsx|client/src/api/apOperations.ts|client/src/api/paymentBatches.ts|client/src/api/travelPayments.ts|client/src/pages/PaymentBatchesPage.tsx","[""A1""]","回滚路径:恢复 AP 页只读概览实现并移除 PaymentBatchesPage 的 ?id= 深链逻辑。2026-04-06:ApOperationsPage 与 PaymentBatchesPage 深链已实现,client typecheck/build 通过;待执行浏览器级业务回归。"
|
||||||
|
"A4","风险标记与对账异常操作接入","在 AP 工作台接入开放风险标记的 resolve/dismiss 弹窗与状态 badge,并在对账异常 Tab 复用现有 confirm 端点与详情查询,确保仅具备 travel.payment.manage 的用户可执行确认。","风险标记 Tab 支持全部/异常风险/预算超支 bucket 筛选,行内展示 open/resolved/dismissed badge,并可填写说明后解决或驳回;对账异常 Tab 可查看订单金额与交易金额差异、异常代码和快照,确认按钮仅对具备 travel.payment.manage 的用户显示/启用。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) 风险标记可解决/驳回且审计带 note;2) 对账异常详情弹窗展示快照;3) 无 travel.payment.manage 的用户只能查看、不能确认。","manual","DONE","DONE","DONE","client/src/pages/ApOperationsPage.tsx|client/src/api/feeControl.ts|client/src/api/travelReconciliation.ts","[""A2"",""A3""]","回滚路径:移除 AP 页中的风险与对账快捷操作,恢复只读展示。2026-04-06:风险/对账快捷操作已接入,client typecheck/build 通过;待执行浏览器级业务回归。"
|
||||||
|
"A5","R52 reviewer 权限与一致性复核","按 reviewer 清单复核 AP 页快捷操作是否严格复用原页面端点与权限,检查高风险提示、对账确认权限收口、导出筛选一致性与风险 note 的审计落点。","review 结论覆盖权限边界、状态流、导出一致性和高风险提示;发现的问题已修复或在 Notes 中明确留痕,无新增越权入口、重复业务端点或状态流回归。","检查:1) AP 页 review/cancel/execute/resolve/dismiss/confirm 是否分别复用原端点与同权限;2) 对账确认按钮仅在同时具备 travel.payment.manage 时可见;3) 导出筛选与页面一致;4) 风险 note 仅进入 audit extra.note,不写业务表字段。若发现问题,修复后重新执行相关 typecheck/build 与后端单测。","manual","DONE","DONE","DONE","issues/2026-04-06_r52-ap-operations.csv|server/src/routes/exports.js|server/src/routes/riskFlags.js|client/src/pages/ApOperationsPage.tsx","[""A2"",""A4""]","回滚路径:若 reviewer 发现权限或状态流问题,优先回退对应快捷操作入口,再重新发布。2026-04-06:已完成本地 reviewer 风格复核,确认 AP 页快捷操作复用原端点与权限,高风险提示、travel.payment.manage 收口、导出筛选与 risk note 审计落点符合方案。"
|
||||||
|
"A6","QA、状态回填与提交收口","执行 R52 post-check 与业务回归,回填 CSV 状态并完成提交收口,确保 AP 工作台操作、导出与深链无回归。","后端与前端校验全部通过;待付款、失败重试、风险处理、对账确认、导出、支付批次深链回归完成;issues/2026-04-06_r52-ap-operations.csv 的 Dev_Status、Review1_Status、Regression_Status 按测试结果回填。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && npx prisma validate && node --check src/routes/apOperations.js && node --check src/routes/exports.js && node --check src/routes/riskFlags.js && npm test -- server/tests/unit/routes/exports.apOperations.test.js server/tests/unit/routes/riskFlags.test.js && cd ../client && npm run typecheck && npm run build。业务:1) AP 页可完成待付款筛选、复核、取消、失败重试、风险处理、对账确认与导出;2) /payment-batches?id=<batchId> 深链可定位指定批次;3) 高风险复核提示和对账确认权限符合方案。","manual","DONE","DONE","DONE","issues/2026-04-06_r52-ap-operations.csv|server/src/routes/exports.js|server/src/routes/riskFlags.js|client/src/pages/ApOperationsPage.tsx|client/src/pages/PaymentBatchesPage.tsx","[""A5""]","回滚路径:若 QA 发现关键回归,暂停提交并回退对应代码变更。2026-04-06:本地 post-check、git diff --check、后端单测与前端 build 已通过;待执行浏览器级业务 QA 与提交收口。2026-04-06:OpenClaw 浏览器回归通过,AP 工作台四 Tab 操作、导出、深链均正常。"
|
||||||
|
@@ -17,6 +17,7 @@ const {
|
|||||||
buildEmployeeDirectoryWhere,
|
buildEmployeeDirectoryWhere,
|
||||||
parseEmployeeDirectoryFilters,
|
parseEmployeeDirectoryFilters,
|
||||||
} = require("../services/employeeDirectoryFilters");
|
} = require("../services/employeeDirectoryFilters");
|
||||||
|
const { BUDGET_RISK_CODES, toMoneyNumber, toMoneyString } = require("../services/feeControl");
|
||||||
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
|
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
|
||||||
const {
|
const {
|
||||||
HISTORY_STATUS_VALUES,
|
HISTORY_STATUS_VALUES,
|
||||||
@@ -102,8 +103,17 @@ const PRESENCE_HISTORY_EXPORT_QUERY_SCHEMA = z.object({
|
|||||||
const CONTRACT_REGISTRY_EXPORT_BODY_SCHEMA = CONTRACT_REGISTRY_FILTER_INPUT_SCHEMA.extend({
|
const CONTRACT_REGISTRY_EXPORT_BODY_SCHEMA = CONTRACT_REGISTRY_FILTER_INPUT_SCHEMA.extend({
|
||||||
format: EXPORT_FORMAT_SCHEMA.optional(),
|
format: EXPORT_FORMAT_SCHEMA.optional(),
|
||||||
});
|
});
|
||||||
|
const AP_OPERATIONS_EXPORT_BODY_SCHEMA = z.object({
|
||||||
|
format: EXPORT_FORMAT_SCHEMA.optional(),
|
||||||
|
pendingEntityType: z.enum(["reimbursement", "travel_order"]).optional(),
|
||||||
|
pendingCreatedAtFrom: DATE_ONLY_SCHEMA.optional(),
|
||||||
|
pendingCreatedAtTo: DATE_ONLY_SCHEMA.optional(),
|
||||||
|
riskBucket: z.enum(["all", "exception", "budget_overspend"]).optional(),
|
||||||
|
}).strict();
|
||||||
|
|
||||||
const PRESENCE_HISTORY_EXPORT_LIMIT = 5000;
|
const PRESENCE_HISTORY_EXPORT_LIMIT = 5000;
|
||||||
|
const AP_PENDING_BATCH_STATUSES = ["draft", "reviewed", "failed"];
|
||||||
|
const AP_OPERATIONS_PERMISSION_CODES = ["payment.batch.manage", "risk.review.manage"];
|
||||||
|
|
||||||
function csvCell(value) {
|
function csvCell(value) {
|
||||||
if (value == null) return "";
|
if (value == null) return "";
|
||||||
@@ -331,6 +341,24 @@ function setExportHeaders(reply, format, filename) {
|
|||||||
reply.header("content-disposition", `attachment; filename=\"${filename}\"`);
|
reply.header("content-disposition", `attachment; filename=\"${filename}\"`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function ensureApOperationsExportEnabled(fastify) {
|
||||||
|
const gate = await evaluateFeatureFlag({
|
||||||
|
prisma: fastify.prisma,
|
||||||
|
config: fastify.config,
|
||||||
|
flagKey: FEATURE_FLAG_KEYS.paymentBatch,
|
||||||
|
strictDepartment: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!gate.enabled) {
|
||||||
|
throw new AppError({
|
||||||
|
code: "VALID_001",
|
||||||
|
message: "参数校验失败",
|
||||||
|
statusCode: 409,
|
||||||
|
details: { featureFlag: "payment_batch_v1_disabled", reason: gate.reason },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function ensureContractsRegistryExportEnabled(fastify, request) {
|
async function ensureContractsRegistryExportEnabled(fastify, request) {
|
||||||
const gate = await evaluateFeatureFlag({
|
const gate = await evaluateFeatureFlag({
|
||||||
prisma: fastify.prisma,
|
prisma: fastify.prisma,
|
||||||
@@ -373,6 +401,377 @@ function contractRegistryStatusLabel(value) {
|
|||||||
return value ?? "";
|
return value ?? "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function paymentBatchEntityTypeLabel(value) {
|
||||||
|
if (value === "reimbursement") return "报销";
|
||||||
|
if (value === "travel_order") return "差旅";
|
||||||
|
return value ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function paymentBatchStatusLabel(value) {
|
||||||
|
if (value === "draft") return "草稿";
|
||||||
|
if (value === "reviewed") return "已复核";
|
||||||
|
if (value === "executed") return "已执行";
|
||||||
|
if (value === "failed") return "执行失败";
|
||||||
|
if (value === "cancelled") return "已取消";
|
||||||
|
return value ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function riskBucketLabel(value) {
|
||||||
|
if (value === "budget_overspend") return "预算超支";
|
||||||
|
return "异常风险";
|
||||||
|
}
|
||||||
|
|
||||||
|
function riskFlagStatusLabel(value) {
|
||||||
|
if (value === "open") return "待处理";
|
||||||
|
if (value === "resolved") return "已解决";
|
||||||
|
if (value === "dismissed") return "已驳回";
|
||||||
|
return value ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function riskLevelLabel(value) {
|
||||||
|
if (value === "high") return "高";
|
||||||
|
if (value === "medium") return "中";
|
||||||
|
if (value === "low") return "低";
|
||||||
|
return value ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function reconciliationMatchStatusLabel(value) {
|
||||||
|
if (value === "amount_mismatch") return "金额不匹配";
|
||||||
|
if (value === "currency_mismatch") return "币种不匹配";
|
||||||
|
if (value === "missing_transaction") return "缺少交易";
|
||||||
|
if (value === "duplicate_charge") return "重复扣款";
|
||||||
|
if (value === "orphan_transaction") return "孤儿交易";
|
||||||
|
if (value === "reversed_after_payment") return "付款后冲正";
|
||||||
|
if (value === "matched") return "已匹配";
|
||||||
|
return value ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function reconciliationResolutionStatusLabel(value) {
|
||||||
|
if (value === "pending") return "待确认";
|
||||||
|
if (value === "confirmed") return "已确认";
|
||||||
|
return value ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveApOperationsRiskBucket(riskCode) {
|
||||||
|
return BUDGET_RISK_CODES.includes(riskCode) ? "budget_overspend" : "exception";
|
||||||
|
}
|
||||||
|
|
||||||
|
function toDateOnlyRange(dateFrom, dateTo, fieldNames) {
|
||||||
|
const from = dateFrom ? new Date(`${dateFrom}T00:00:00.000Z`) : null;
|
||||||
|
const to = dateTo ? new Date(`${dateTo}T23:59:59.999Z`) : null;
|
||||||
|
if (from && to && from > to) {
|
||||||
|
throw new AppError({
|
||||||
|
code: "VALID_001",
|
||||||
|
message: "参数校验失败",
|
||||||
|
statusCode: 400,
|
||||||
|
details: { [fieldNames.to]: "must_be_after_or_equal_to_from" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { from, to };
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildApOperationsPendingBatchWhere(filters) {
|
||||||
|
const { from, to } = toDateOnlyRange(
|
||||||
|
filters.pendingCreatedAtFrom,
|
||||||
|
filters.pendingCreatedAtTo,
|
||||||
|
{ from: "pendingCreatedAtFrom", to: "pendingCreatedAtTo" },
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: { in: AP_PENDING_BATCH_STATUSES },
|
||||||
|
...(filters.pendingEntityType ? { entity_type: filters.pendingEntityType } : {}),
|
||||||
|
...(from || to
|
||||||
|
? {
|
||||||
|
created_at: {
|
||||||
|
...(from ? { gte: from } : {}),
|
||||||
|
...(to ? { lte: to } : {}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildApOperationsRiskWhere(filters) {
|
||||||
|
if (filters.riskBucket === "budget_overspend") {
|
||||||
|
return {
|
||||||
|
status: "open",
|
||||||
|
risk_code: { in: BUDGET_RISK_CODES },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filters.riskBucket === "exception") {
|
||||||
|
return {
|
||||||
|
status: "open",
|
||||||
|
risk_code: { notIn: BUDGET_RISK_CODES },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { status: "open" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapApPendingBatchExportRow(item) {
|
||||||
|
const totalAmount = toMoneyString((item.items ?? []).reduce((sum, entry) => sum + toMoneyNumber(entry.amount), 0));
|
||||||
|
return [
|
||||||
|
item.batch_no,
|
||||||
|
paymentBatchEntityTypeLabel(item.entity_type),
|
||||||
|
item.name,
|
||||||
|
paymentBatchStatusLabel(item.status),
|
||||||
|
totalAmount,
|
||||||
|
toMoneyNumber(totalAmount) >= 50000 ? "是" : "否",
|
||||||
|
item.created_at?.toISOString?.() ?? "",
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapApFailedPaymentItemExportRow(item) {
|
||||||
|
return [
|
||||||
|
item.payment_batch?.batch_no ?? item.payment_batch_id,
|
||||||
|
paymentBatchEntityTypeLabel(item.payment_batch?.entity_type),
|
||||||
|
item.entity_code,
|
||||||
|
item.entity_title,
|
||||||
|
toMoneyString(item.amount),
|
||||||
|
item.currency_code,
|
||||||
|
item.failure_code ?? "",
|
||||||
|
item.failure_message ?? "",
|
||||||
|
item.created_at?.toISOString?.() ?? "",
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapApRiskFlagExportRow(item) {
|
||||||
|
return [
|
||||||
|
riskBucketLabel(resolveApOperationsRiskBucket(item.risk_code)),
|
||||||
|
item.title,
|
||||||
|
item.risk_code,
|
||||||
|
riskLevelLabel(item.level),
|
||||||
|
item.entity_type,
|
||||||
|
item.entity_id,
|
||||||
|
item.source,
|
||||||
|
riskFlagStatusLabel(item.status),
|
||||||
|
item.detail ?? "",
|
||||||
|
item.created_at?.toISOString?.() ?? "",
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapApReconciliationAnomalyExportRow(item) {
|
||||||
|
return [
|
||||||
|
item.batch?.batch_no ?? item.travel_reconciliation_batch_id,
|
||||||
|
item.anomaly_code ?? "",
|
||||||
|
reconciliationMatchStatusLabel(item.match_status),
|
||||||
|
reconciliationResolutionStatusLabel(item.resolution_status),
|
||||||
|
item.travel_order_id ?? "",
|
||||||
|
item.travel_request_id ?? "",
|
||||||
|
item.order_amount != null ? toMoneyString(item.order_amount) : "",
|
||||||
|
item.transaction_amount != null ? toMoneyString(item.transaction_amount) : "",
|
||||||
|
item.currency ?? "",
|
||||||
|
item.created_at?.toISOString?.() ?? "",
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadApOperationsExportDataset(prisma, filters) {
|
||||||
|
const pendingWhere = buildApOperationsPendingBatchWhere(filters);
|
||||||
|
const riskWhere = buildApOperationsRiskWhere(filters);
|
||||||
|
const reconciliationWhere = {
|
||||||
|
resolution_status: "pending",
|
||||||
|
match_status: { not: "matched" },
|
||||||
|
};
|
||||||
|
|
||||||
|
const [pendingPaymentBatches, failedPaymentBatchItems, riskFlags, reconciliationAnomalies] = await Promise.all([
|
||||||
|
prisma.paymentBatch.findMany({
|
||||||
|
where: pendingWhere,
|
||||||
|
orderBy: [{ created_at: "desc" }, { id: "desc" }],
|
||||||
|
include: {
|
||||||
|
items: {
|
||||||
|
select: {
|
||||||
|
amount: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.paymentBatchItem.findMany({
|
||||||
|
where: { status: "failed" },
|
||||||
|
orderBy: [{ created_at: "desc" }, { id: "desc" }],
|
||||||
|
include: {
|
||||||
|
payment_batch: {
|
||||||
|
select: {
|
||||||
|
batch_no: true,
|
||||||
|
entity_type: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
prisma.entityRiskFlag.findMany({
|
||||||
|
where: riskWhere,
|
||||||
|
orderBy: [{ created_at: "desc" }, { id: "desc" }],
|
||||||
|
}),
|
||||||
|
prisma.travelReconciliationItem.findMany({
|
||||||
|
where: reconciliationWhere,
|
||||||
|
orderBy: [{ created_at: "desc" }, { id: "desc" }],
|
||||||
|
take: 50,
|
||||||
|
include: {
|
||||||
|
batch: {
|
||||||
|
select: {
|
||||||
|
batch_no: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
pendingWhere,
|
||||||
|
riskWhere,
|
||||||
|
reconciliationWhere,
|
||||||
|
pendingPaymentBatches,
|
||||||
|
failedPaymentBatchItems,
|
||||||
|
riskFlags,
|
||||||
|
reconciliationAnomalies,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function* streamApOperationsCsv(dataset) {
|
||||||
|
yield "\ufeff";
|
||||||
|
|
||||||
|
yield csvRow(["待付款批次"]);
|
||||||
|
yield csvRow(["批次编号", "实体类型", "批次名称", "状态", "总金额", "高风险", "创建时间"]);
|
||||||
|
for (const item of dataset.pendingPaymentBatches) {
|
||||||
|
yield csvRow(mapApPendingBatchExportRow(item));
|
||||||
|
}
|
||||||
|
yield csvRow([]);
|
||||||
|
|
||||||
|
yield csvRow(["异常付款项"]);
|
||||||
|
yield csvRow(["批次编号", "实体类型", "单据编号", "单据标题", "金额", "币种", "失败码", "失败原因", "创建时间"]);
|
||||||
|
for (const item of dataset.failedPaymentBatchItems) {
|
||||||
|
yield csvRow(mapApFailedPaymentItemExportRow(item));
|
||||||
|
}
|
||||||
|
yield csvRow([]);
|
||||||
|
|
||||||
|
yield csvRow(["风险标记"]);
|
||||||
|
yield csvRow(["风险分组", "标题", "风险编码", "等级", "实体类型", "实体 ID", "来源", "状态", "明细", "创建时间"]);
|
||||||
|
for (const item of dataset.riskFlags) {
|
||||||
|
yield csvRow(mapApRiskFlagExportRow(item));
|
||||||
|
}
|
||||||
|
yield csvRow([]);
|
||||||
|
|
||||||
|
yield csvRow(["对账异常"]);
|
||||||
|
yield csvRow(["批次编号", "异常编码", "匹配状态", "确认状态", "差旅订单 ID", "差旅申请 ID", "订单金额", "交易金额", "币种", "创建时间"]);
|
||||||
|
for (const item of dataset.reconciliationAnomalies) {
|
||||||
|
yield csvRow(mapApReconciliationAnomalyExportRow(item));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildApOperationsXlsx(dataset) {
|
||||||
|
const workbook = new ExcelJS.Workbook();
|
||||||
|
|
||||||
|
const pendingSheet = workbook.addWorksheet("待付款批次");
|
||||||
|
pendingSheet.columns = [
|
||||||
|
{ header: "批次编号", key: "batchNo", width: 24 },
|
||||||
|
{ header: "实体类型", key: "entityType", width: 14 },
|
||||||
|
{ header: "批次名称", key: "name", width: 30 },
|
||||||
|
{ header: "状态", key: "status", width: 14 },
|
||||||
|
{ header: "总金额", key: "totalAmount", width: 14 },
|
||||||
|
{ header: "高风险", key: "highRisk", width: 10 },
|
||||||
|
{ header: "创建时间", key: "createdAt", width: 24 },
|
||||||
|
];
|
||||||
|
for (const item of dataset.pendingPaymentBatches) {
|
||||||
|
const row = mapApPendingBatchExportRow(item);
|
||||||
|
pendingSheet.addRow({
|
||||||
|
batchNo: row[0],
|
||||||
|
entityType: row[1],
|
||||||
|
name: row[2],
|
||||||
|
status: row[3],
|
||||||
|
totalAmount: row[4],
|
||||||
|
highRisk: row[5],
|
||||||
|
createdAt: row[6],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const failedSheet = workbook.addWorksheet("异常付款项");
|
||||||
|
failedSheet.columns = [
|
||||||
|
{ header: "批次编号", key: "batchNo", width: 24 },
|
||||||
|
{ header: "实体类型", key: "entityType", width: 14 },
|
||||||
|
{ header: "单据编号", key: "entityCode", width: 24 },
|
||||||
|
{ header: "单据标题", key: "entityTitle", width: 28 },
|
||||||
|
{ header: "金额", key: "amount", width: 14 },
|
||||||
|
{ header: "币种", key: "currencyCode", width: 10 },
|
||||||
|
{ header: "失败码", key: "failureCode", width: 20 },
|
||||||
|
{ header: "失败原因", key: "failureMessage", width: 32 },
|
||||||
|
{ header: "创建时间", key: "createdAt", width: 24 },
|
||||||
|
];
|
||||||
|
for (const item of dataset.failedPaymentBatchItems) {
|
||||||
|
const row = mapApFailedPaymentItemExportRow(item);
|
||||||
|
failedSheet.addRow({
|
||||||
|
batchNo: row[0],
|
||||||
|
entityType: row[1],
|
||||||
|
entityCode: row[2],
|
||||||
|
entityTitle: row[3],
|
||||||
|
amount: row[4],
|
||||||
|
currencyCode: row[5],
|
||||||
|
failureCode: row[6],
|
||||||
|
failureMessage: row[7],
|
||||||
|
createdAt: row[8],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const riskSheet = workbook.addWorksheet("风险标记");
|
||||||
|
riskSheet.columns = [
|
||||||
|
{ header: "风险分组", key: "bucket", width: 14 },
|
||||||
|
{ header: "标题", key: "title", width: 28 },
|
||||||
|
{ header: "风险编码", key: "riskCode", width: 24 },
|
||||||
|
{ header: "等级", key: "level", width: 10 },
|
||||||
|
{ header: "实体类型", key: "entityType", width: 16 },
|
||||||
|
{ header: "实体 ID", key: "entityId", width: 38 },
|
||||||
|
{ header: "来源", key: "source", width: 14 },
|
||||||
|
{ header: "状态", key: "status", width: 12 },
|
||||||
|
{ header: "明细", key: "detail", width: 40 },
|
||||||
|
{ header: "创建时间", key: "createdAt", width: 24 },
|
||||||
|
];
|
||||||
|
for (const item of dataset.riskFlags) {
|
||||||
|
const row = mapApRiskFlagExportRow(item);
|
||||||
|
riskSheet.addRow({
|
||||||
|
bucket: row[0],
|
||||||
|
title: row[1],
|
||||||
|
riskCode: row[2],
|
||||||
|
level: row[3],
|
||||||
|
entityType: row[4],
|
||||||
|
entityId: row[5],
|
||||||
|
source: row[6],
|
||||||
|
status: row[7],
|
||||||
|
detail: row[8],
|
||||||
|
createdAt: row[9],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const reconciliationSheet = workbook.addWorksheet("对账异常");
|
||||||
|
reconciliationSheet.columns = [
|
||||||
|
{ header: "批次编号", key: "batchNo", width: 24 },
|
||||||
|
{ header: "异常编码", key: "anomalyCode", width: 20 },
|
||||||
|
{ header: "匹配状态", key: "matchStatus", width: 16 },
|
||||||
|
{ header: "确认状态", key: "resolutionStatus", width: 14 },
|
||||||
|
{ header: "差旅订单 ID", key: "travelOrderId", width: 38 },
|
||||||
|
{ header: "差旅申请 ID", key: "travelRequestId", width: 38 },
|
||||||
|
{ header: "订单金额", key: "orderAmount", width: 14 },
|
||||||
|
{ header: "交易金额", key: "transactionAmount", width: 14 },
|
||||||
|
{ header: "币种", key: "currency", width: 10 },
|
||||||
|
{ header: "创建时间", key: "createdAt", width: 24 },
|
||||||
|
];
|
||||||
|
for (const item of dataset.reconciliationAnomalies) {
|
||||||
|
const row = mapApReconciliationAnomalyExportRow(item);
|
||||||
|
reconciliationSheet.addRow({
|
||||||
|
batchNo: row[0],
|
||||||
|
anomalyCode: row[1],
|
||||||
|
matchStatus: row[2],
|
||||||
|
resolutionStatus: row[3],
|
||||||
|
travelOrderId: row[4],
|
||||||
|
travelRequestId: row[5],
|
||||||
|
orderAmount: row[6],
|
||||||
|
transactionAmount: row[7],
|
||||||
|
currency: row[8],
|
||||||
|
createdAt: row[9],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return workbook.xlsx.writeBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
function mapContractRegistryExportRow(item, today) {
|
function mapContractRegistryExportRow(item, today) {
|
||||||
const effectiveStatus = resolveContractRegistryEffectiveStatus(item, today);
|
const effectiveStatus = resolveContractRegistryEffectiveStatus(item, today);
|
||||||
return [
|
return [
|
||||||
@@ -1202,6 +1601,57 @@ async function exportsRoutes(fastify) {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
fastify.post(
|
||||||
|
"/exports/ap-operations",
|
||||||
|
{
|
||||||
|
preHandler: fastify.authenticate,
|
||||||
|
},
|
||||||
|
async (request, reply) => {
|
||||||
|
await ensureApOperationsExportEnabled(fastify);
|
||||||
|
ensureHasAnyPermission(fastify, request, AP_OPERATIONS_PERMISSION_CODES);
|
||||||
|
|
||||||
|
const parsedBody = parseBody(AP_OPERATIONS_EXPORT_BODY_SCHEMA, request.body);
|
||||||
|
const format = parsedBody.format ?? "csv";
|
||||||
|
const filters = {
|
||||||
|
pendingEntityType: parsedBody.pendingEntityType,
|
||||||
|
pendingCreatedAtFrom: parsedBody.pendingCreatedAtFrom,
|
||||||
|
pendingCreatedAtTo: parsedBody.pendingCreatedAtTo,
|
||||||
|
riskBucket: parsedBody.riskBucket ?? "all",
|
||||||
|
};
|
||||||
|
const dataset = await loadApOperationsExportDataset(fastify.prisma, filters);
|
||||||
|
|
||||||
|
await fastify.prisma.auditLog.create({
|
||||||
|
data: buildAuditLogData(request, {
|
||||||
|
actorId: request.employee.id,
|
||||||
|
action: "EXPORT_AP_OPERATIONS",
|
||||||
|
targetType: "export",
|
||||||
|
extra: {
|
||||||
|
format,
|
||||||
|
pendingEntityType: filters.pendingEntityType ?? null,
|
||||||
|
pendingCreatedAtFrom: filters.pendingCreatedAtFrom ?? null,
|
||||||
|
pendingCreatedAtTo: filters.pendingCreatedAtTo ?? null,
|
||||||
|
riskBucket: filters.riskBucket,
|
||||||
|
pendingPaymentBatchTotal: dataset.pendingPaymentBatches.length,
|
||||||
|
failedPaymentItemTotal: dataset.failedPaymentBatchItems.length,
|
||||||
|
openRiskFlagTotal: dataset.riskFlags.length,
|
||||||
|
reconciliationAnomalyTotal: dataset.reconciliationAnomalies.length,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const filename = exportFilename("ap-operations", format);
|
||||||
|
setExportHeaders(reply, format, filename);
|
||||||
|
|
||||||
|
if (format === "xlsx") {
|
||||||
|
const buffer = await buildApOperationsXlsx(dataset);
|
||||||
|
return reply.send(Buffer.from(buffer));
|
||||||
|
}
|
||||||
|
|
||||||
|
const stream = Readable.from(streamApOperationsCsv(dataset));
|
||||||
|
return reply.send(stream);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
fastify.get(
|
fastify.get(
|
||||||
"/exports/employees",
|
"/exports/employees",
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ const QUERY_SCHEMA = z.object({
|
|||||||
status: z.enum(["open", "resolved", "dismissed"]).optional(),
|
status: z.enum(["open", "resolved", "dismissed"]).optional(),
|
||||||
source: z.string().trim().max(32).optional(),
|
source: z.string().trim().max(32).optional(),
|
||||||
});
|
});
|
||||||
|
const ACTION_BODY_SCHEMA = z.object({
|
||||||
|
note: z.string().trim().max(500).nullable().optional(),
|
||||||
|
}).strict();
|
||||||
|
|
||||||
function buildValidationError(details, statusCode = 400) {
|
function buildValidationError(details, statusCode = 400) {
|
||||||
return new AppError({
|
return new AppError({
|
||||||
@@ -58,6 +61,22 @@ function parseId(value) {
|
|||||||
return parsed.data;
|
return parsed.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseBody(body) {
|
||||||
|
const parsed = ACTION_BODY_SCHEMA.safeParse(body ?? {});
|
||||||
|
if (!parsed.success) {
|
||||||
|
throw buildValidationError(parsed.error.flatten());
|
||||||
|
}
|
||||||
|
return parsed.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeNote(value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const trimmed = String(value).trim();
|
||||||
|
return trimmed || null;
|
||||||
|
}
|
||||||
|
|
||||||
async function riskFlagsRoutes(fastify) {
|
async function riskFlagsRoutes(fastify) {
|
||||||
fastify.get("/risk-flags", { preHandler: fastify.authenticate }, async (request, reply) => {
|
fastify.get("/risk-flags", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||||
ensureListPermission(fastify, request);
|
ensureListPermission(fastify, request);
|
||||||
@@ -78,6 +97,8 @@ async function riskFlagsRoutes(fastify) {
|
|||||||
fastify.post(`/risk-flags/:id/${action}`, { preHandler: fastify.authenticate }, async (request, reply) => {
|
fastify.post(`/risk-flags/:id/${action}`, { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||||
ensureManagePermission(fastify, request);
|
ensureManagePermission(fastify, request);
|
||||||
const riskFlagId = parseId(request.params?.id);
|
const riskFlagId = parseId(request.params?.id);
|
||||||
|
const body = parseBody(request.body);
|
||||||
|
const note = normalizeNote(body.note);
|
||||||
const current = await fastify.prisma.entityRiskFlag.findUnique({ where: { id: riskFlagId } });
|
const current = await fastify.prisma.entityRiskFlag.findUnique({ where: { id: riskFlagId } });
|
||||||
if (!current) {
|
if (!current) {
|
||||||
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||||
@@ -105,6 +126,7 @@ async function riskFlagsRoutes(fastify) {
|
|||||||
entityType: updated.entity_type,
|
entityType: updated.entity_type,
|
||||||
entityId: updated.entity_id,
|
entityId: updated.entity_id,
|
||||||
riskCode: updated.risk_code,
|
riskCode: updated.risk_code,
|
||||||
|
note,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,272 @@
|
|||||||
|
const Fastify = require("fastify");
|
||||||
|
|
||||||
|
const exportsRoutes = require("../../../src/routes/exports");
|
||||||
|
|
||||||
|
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
|
||||||
|
function buildFeatureFlagRecord(flagKey) {
|
||||||
|
return {
|
||||||
|
id: `flag-${flagKey}`,
|
||||||
|
flag_key: flagKey,
|
||||||
|
override_mode: "force_on",
|
||||||
|
rollout_type: "global",
|
||||||
|
department_ids: [],
|
||||||
|
note: "unit-test",
|
||||||
|
version: 1,
|
||||||
|
created_at: new Date("2026-04-06T08:00:00.000Z"),
|
||||||
|
created_by: null,
|
||||||
|
updated_at: new Date("2026-04-06T08:00:00.000Z"),
|
||||||
|
updated_by: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPendingBatch(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: "11111111-1111-4111-8111-111111111111",
|
||||||
|
batch_no: "PB-20260406-001",
|
||||||
|
entity_type: "travel_order",
|
||||||
|
name: "差旅待付款批次",
|
||||||
|
status: "reviewed",
|
||||||
|
created_at: new Date("2026-04-06T09:00:00.000Z"),
|
||||||
|
items: [{ amount: "1000.00" }, { amount: "560.50" }],
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFailedItem(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: "22222222-2222-4222-8222-222222222222",
|
||||||
|
payment_batch_id: "11111111-1111-4111-8111-111111111111",
|
||||||
|
entity_id: "33333333-3333-4333-8333-333333333333",
|
||||||
|
entity_code: "TR-001",
|
||||||
|
entity_title: "上海差旅订单",
|
||||||
|
amount: "560.50",
|
||||||
|
currency_code: "CNY",
|
||||||
|
failure_code: "BANK_TIMEOUT",
|
||||||
|
failure_message: "银行回执超时",
|
||||||
|
created_at: new Date("2026-04-06T10:00:00.000Z"),
|
||||||
|
payment_batch: {
|
||||||
|
batch_no: "PB-20260406-001",
|
||||||
|
entity_type: "travel_order",
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRiskFlag(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: "44444444-4444-4444-8444-444444444444",
|
||||||
|
entity_type: "travel_order",
|
||||||
|
entity_id: "33333333-3333-4333-8333-333333333333",
|
||||||
|
risk_code: "budget_exceeded",
|
||||||
|
level: "high",
|
||||||
|
title: "预算超支",
|
||||||
|
detail: "差旅预算已超支",
|
||||||
|
source: "budget_control",
|
||||||
|
status: "open",
|
||||||
|
created_at: new Date("2026-04-06T11:00:00.000Z"),
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildAnomaly(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: "55555555-5555-4555-8555-555555555555",
|
||||||
|
travel_reconciliation_batch_id: "66666666-6666-4666-8666-666666666666",
|
||||||
|
travel_order_id: "77777777-7777-4777-8777-777777777777",
|
||||||
|
travel_request_id: "88888888-8888-4888-8888-888888888888",
|
||||||
|
match_status: "amount_mismatch",
|
||||||
|
resolution_status: "pending",
|
||||||
|
anomaly_code: "AMOUNT_MISMATCH",
|
||||||
|
order_amount: "880.00",
|
||||||
|
transaction_amount: "860.00",
|
||||||
|
currency: "CNY",
|
||||||
|
created_at: new Date("2026-04-06T12:00:00.000Z"),
|
||||||
|
batch: {
|
||||||
|
batch_no: "TRB-20260406-001",
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildApp(options = {}) {
|
||||||
|
const app = Fastify();
|
||||||
|
const actor = options.actor ?? {
|
||||||
|
id: ACTOR_ID,
|
||||||
|
permissionCodes: ["payment.batch.manage"],
|
||||||
|
};
|
||||||
|
const paymentBatchFindMany = options.paymentBatchFindMany ?? vi.fn().mockResolvedValue([buildPendingBatch()]);
|
||||||
|
const paymentBatchItemFindMany = options.paymentBatchItemFindMany ?? vi.fn().mockResolvedValue([buildFailedItem()]);
|
||||||
|
const entityRiskFlagFindMany = options.entityRiskFlagFindMany ?? vi.fn().mockResolvedValue([buildRiskFlag()]);
|
||||||
|
const travelReconciliationItemFindMany =
|
||||||
|
options.travelReconciliationItemFindMany ?? vi.fn().mockResolvedValue([buildAnomaly()]);
|
||||||
|
const auditCreate = options.auditCreate ?? vi.fn().mockResolvedValue({});
|
||||||
|
|
||||||
|
app.decorate("authenticate", async (request) => {
|
||||||
|
request.employee = actor;
|
||||||
|
});
|
||||||
|
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||||
|
const permissionCodes = employee.permissionCodes ?? [];
|
||||||
|
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||||
|
});
|
||||||
|
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||||
|
request.employee = actor;
|
||||||
|
const permissionCodes = actor.permissionCodes ?? [];
|
||||||
|
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
|
||||||
|
throw new Error(`unexpected permission check: ${permissionCode}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
app.decorate("config", {
|
||||||
|
appTimezone: "Asia/Shanghai",
|
||||||
|
paymentBatchEnabled: true,
|
||||||
|
projectLinkingEnabled: true,
|
||||||
|
});
|
||||||
|
app.decorate("prisma", {
|
||||||
|
featureFlag: {
|
||||||
|
findUnique: vi.fn().mockImplementation(async ({ where }) => buildFeatureFlagRecord(where.flag_key)),
|
||||||
|
},
|
||||||
|
paymentBatch: {
|
||||||
|
findMany: paymentBatchFindMany,
|
||||||
|
},
|
||||||
|
paymentBatchItem: {
|
||||||
|
findMany: paymentBatchItemFindMany,
|
||||||
|
},
|
||||||
|
entityRiskFlag: {
|
||||||
|
findMany: entityRiskFlagFindMany,
|
||||||
|
},
|
||||||
|
travelReconciliationItem: {
|
||||||
|
findMany: travelReconciliationItemFindMany,
|
||||||
|
},
|
||||||
|
auditLog: {
|
||||||
|
create: auditCreate,
|
||||||
|
},
|
||||||
|
contractRegistry: {
|
||||||
|
count: vi.fn().mockResolvedValue(0),
|
||||||
|
findMany: vi.fn().mockResolvedValue([]),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.register(exportsRoutes, { prefix: "/api" });
|
||||||
|
return {
|
||||||
|
app,
|
||||||
|
paymentBatchFindMany,
|
||||||
|
paymentBatchItemFindMany,
|
||||||
|
entityRiskFlagFindMany,
|
||||||
|
travelReconciliationItemFindMany,
|
||||||
|
auditCreate,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("ap operations export route", () => {
|
||||||
|
it("exports ap operations as csv with section blocks and filters", async () => {
|
||||||
|
const {
|
||||||
|
app,
|
||||||
|
paymentBatchFindMany,
|
||||||
|
entityRiskFlagFindMany,
|
||||||
|
travelReconciliationItemFindMany,
|
||||||
|
auditCreate,
|
||||||
|
} = await buildApp();
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/exports/ap-operations",
|
||||||
|
payload: {
|
||||||
|
format: "csv",
|
||||||
|
pendingEntityType: "travel_order",
|
||||||
|
pendingCreatedAtFrom: "2026-04-01",
|
||||||
|
pendingCreatedAtTo: "2026-04-30",
|
||||||
|
riskBucket: "budget_overspend",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
expect(response.headers["content-type"]).toContain("text/csv");
|
||||||
|
expect(response.headers["content-disposition"]).toContain("ap-operations-");
|
||||||
|
expect(response.body).toContain("待付款批次");
|
||||||
|
expect(response.body).toContain("异常付款项");
|
||||||
|
expect(response.body).toContain("风险标记");
|
||||||
|
expect(response.body).toContain("对账异常");
|
||||||
|
expect(response.body).toContain("预算超支");
|
||||||
|
expect(paymentBatchFindMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: expect.objectContaining({
|
||||||
|
entity_type: "travel_order",
|
||||||
|
status: { in: ["draft", "reviewed", "failed"] },
|
||||||
|
created_at: expect.objectContaining({
|
||||||
|
gte: new Date("2026-04-01T00:00:00.000Z"),
|
||||||
|
lte: new Date("2026-04-30T23:59:59.999Z"),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(entityRiskFlagFindMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: expect.objectContaining({
|
||||||
|
status: "open",
|
||||||
|
risk_code: { in: ["budget_exceeded", "budget_threshold_exceeded"] },
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(travelReconciliationItemFindMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: expect.objectContaining({
|
||||||
|
resolution_status: "pending",
|
||||||
|
match_status: { not: "matched" },
|
||||||
|
}),
|
||||||
|
take: 50,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(auditCreate).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
data: expect.objectContaining({
|
||||||
|
action: "EXPORT_AP_OPERATIONS",
|
||||||
|
extra: expect.objectContaining({
|
||||||
|
format: "csv",
|
||||||
|
pendingEntityType: "travel_order",
|
||||||
|
pendingCreatedAtFrom: "2026-04-01",
|
||||||
|
pendingCreatedAtTo: "2026-04-30",
|
||||||
|
riskBucket: "budget_overspend",
|
||||||
|
pendingPaymentBatchTotal: 1,
|
||||||
|
failedPaymentItemTotal: 1,
|
||||||
|
openRiskFlagTotal: 1,
|
||||||
|
reconciliationAnomalyTotal: 1,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("exports ap operations as xlsx", async () => {
|
||||||
|
const { app, auditCreate } = await buildApp();
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/exports/ap-operations",
|
||||||
|
payload: {
|
||||||
|
format: "xlsx",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
expect(response.headers["content-type"]).toContain(
|
||||||
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
);
|
||||||
|
expect(response.headers["content-disposition"]).toContain("ap-operations-");
|
||||||
|
expect(Buffer.from(response.rawPayload).length).toBeGreaterThan(0);
|
||||||
|
expect(auditCreate).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
data: expect.objectContaining({
|
||||||
|
action: "EXPORT_AP_OPERATIONS",
|
||||||
|
extra: expect.objectContaining({
|
||||||
|
format: "xlsx",
|
||||||
|
riskBucket: "all",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
const Fastify = require("fastify");
|
||||||
|
|
||||||
|
const riskFlagsRoutes = require("../../../src/routes/riskFlags");
|
||||||
|
|
||||||
|
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
const RISK_FLAG_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||||
|
|
||||||
|
function buildRiskFlag(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: RISK_FLAG_ID,
|
||||||
|
entity_type: "reimbursement",
|
||||||
|
entity_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
|
||||||
|
risk_code: "budget_exceeded",
|
||||||
|
level: "high",
|
||||||
|
title: "预算已超支",
|
||||||
|
detail: "部门预算已超预算阈值",
|
||||||
|
source: "budget_control",
|
||||||
|
status: "open",
|
||||||
|
payload_json: null,
|
||||||
|
created_at: new Date("2026-04-06T08:00:00.000Z"),
|
||||||
|
created_by: null,
|
||||||
|
resolved_at: null,
|
||||||
|
resolved_by: null,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildApp(options = {}) {
|
||||||
|
const app = Fastify();
|
||||||
|
const actor = options.actor ?? {
|
||||||
|
id: ACTOR_ID,
|
||||||
|
permissionCodes: ["risk.review.manage"],
|
||||||
|
};
|
||||||
|
const currentRecord = options.currentRecord ?? buildRiskFlag();
|
||||||
|
const findUnique = options.findUnique ?? vi.fn().mockResolvedValue(currentRecord);
|
||||||
|
const update = options.update ?? vi.fn().mockImplementation(async ({ data }) => ({
|
||||||
|
...currentRecord,
|
||||||
|
status: data.status,
|
||||||
|
resolved_at: data.resolved_at,
|
||||||
|
resolved_by: data.resolved_by,
|
||||||
|
}));
|
||||||
|
const auditCreate = options.auditCreate ?? vi.fn().mockResolvedValue({});
|
||||||
|
|
||||||
|
app.decorate("authenticate", async (request) => {
|
||||||
|
request.employee = actor;
|
||||||
|
});
|
||||||
|
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||||
|
const permissionCodes = employee.permissionCodes ?? [];
|
||||||
|
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||||
|
});
|
||||||
|
app.decorate("prisma", {
|
||||||
|
entityRiskFlag: {
|
||||||
|
findMany: vi.fn().mockResolvedValue([]),
|
||||||
|
findUnique,
|
||||||
|
update,
|
||||||
|
},
|
||||||
|
auditLog: {
|
||||||
|
create: auditCreate,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.register(riskFlagsRoutes, { prefix: "/api" });
|
||||||
|
return { app, findUnique, update, auditCreate };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("risk flags routes", () => {
|
||||||
|
it("writes resolve note into audit extra while keeping response shape", async () => {
|
||||||
|
const { app, update, auditCreate } = await buildApp();
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: `/api/risk-flags/${RISK_FLAG_ID}/resolve`,
|
||||||
|
payload: {
|
||||||
|
note: "已人工核查,无需继续挂起",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
expect(update).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: { id: RISK_FLAG_ID },
|
||||||
|
data: expect.objectContaining({
|
||||||
|
status: "resolved",
|
||||||
|
resolved_by: ACTOR_ID,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(auditCreate).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
data: expect.objectContaining({
|
||||||
|
action: "ENTITY_RISK_FLAG_RESOLVED",
|
||||||
|
extra: expect.objectContaining({
|
||||||
|
riskCode: "budget_exceeded",
|
||||||
|
note: "已人工核查,无需继续挂起",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const payload = response.json();
|
||||||
|
expect(payload.data.item.status).toBe("resolved");
|
||||||
|
expect(payload.data.item.resolvedBy).toBe(ACTOR_ID);
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects unexpected fields for resolve action body", async () => {
|
||||||
|
const { app, update, auditCreate } = await buildApp();
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: `/api/risk-flags/${RISK_FLAG_ID}/resolve`,
|
||||||
|
payload: {
|
||||||
|
note: "ok",
|
||||||
|
extra: "not-allowed",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(400);
|
||||||
|
expect(update).not.toHaveBeenCalled();
|
||||||
|
expect(auditCreate).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
在新工单中引用
屏蔽一个用户