feat: 完成P10生产硬化与矩阵收口(P10E1-P10G1)

这个提交包含在:
2026-02-10 11:25:18 +08:00
父节点 1b6e801b12
当前提交 bec21e1b38
共修改 15 个文件,包含 1718 行新增和 793 行删除
+22
查看文件
@@ -55,6 +55,14 @@ OCR_POLL_CRON="* * * * *"
OCR_MAX_ATTEMPTS="3"
OCR_TIMEOUT_MS="5000"
# ===== 发票验真(P6)=====
INVOICE_VERIFICATION_ENABLED="false"
VERIFICATION_PROVIDER="mock" # mock|tax
VERIFICATION_POLL_CRON="* * * * *"
VERIFICATION_MAX_ATTEMPTS="3"
VERIFICATION_RETRY_COOLDOWN_SECONDS="60"
VERIFICATION_TIMEOUT_MS="5000"
INVOICE_ARCHIVE_CRON="30 2 * * *"
INVOICE_ARCHIVE_UNUSED_DAYS="90"
INVOICE_ARCHIVE_BATCH_SIZE="200"
@@ -62,6 +70,20 @@ TENCENT_SECRET_ID=""
TENCENT_SECRET_KEY=""
TENCENT_OCR_REGION="ap-beijing"
# ===== 预算与集成(P7-P8)=====
BUDGET_CONTROL_MODE="warn" # warn|block
ERP_SYNC_ENABLED="false"
ERP_SYNC_PROVIDER="mock" # mock|http
ERP_SYNC_ENDPOINT=""
ERP_SYNC_TIMEOUT_MS="5000"
ERP_SYNC_AUTH_TOKEN=""
TRAVEL_SYNC_ENABLED="false"
IM_NOTIFIER_ENABLED="false"
INTEGRATION_OUTBOX_CRON="* * * * *"
INTEGRATION_OUTBOX_BATCH_SIZE="20"
INTEGRATION_OUTBOX_MAX_ATTEMPTS="5"
INTEGRATION_OUTBOX_RETRY_SECONDS="120"
# ===== 试运行引导管理员(E20,可选)=====
# TRIALRUN_ADMIN_EMAIL="[email protected]"
# TRIALRUN_ADMIN_PHONE="13800000000"
+79
查看文件
@@ -442,3 +442,82 @@ npm run job:ocr-once
### 8.2 磁盘空间不足(ENOSPC)
- 在受控环境中制造磁盘满条件后重试上传。
- 预期:错误路径可观测(日志中能定位到 I/O 错误),不要求纳入日常 CI 冒烟。
---
## 9. P6-P10 增量能力(验真 / 看板 / 预算 / 集成 / 生产硬化)
### 9.1 特性开关(默认值)
- `INVOICE_VERIFICATION_ENABLED=false`
- `VERIFICATION_PROVIDER=mock`
- `BUDGET_CONTROL_MODE=warn`
- `ERP_SYNC_ENABLED=false`
- `ERP_SYNC_PROVIDER=mock`
- `ERP_SYNC_ENDPOINT=`
- `ERP_SYNC_TIMEOUT_MS=5000`
- `ERP_SYNC_AUTH_TOKEN=`
- `TRAVEL_SYNC_ENABLED=false`
- `IM_NOTIFIER_ENABLED=false`
建议:先在测试组织灰度开启,再逐步扩大范围。
### 9.2 新增 API 摘要
- 发票验真:
- `POST /api/invoice-pool/:id/verify`
- `GET /api/invoice-pool/:id/verification`
- `POST /api/invoice-pool/:id/verification/retry`
- 看板聚合:
- `GET /api/dashboard/expense-overview`
- `GET /api/dashboard/trends`
- `GET /api/dashboard/top-categories`
- `GET /api/dashboard/approval-efficiency`
- 预算管理:
- `GET /api/budgets`
- `POST /api/budgets`
- `PATCH /api/budgets/:id`
- `POST /api/budgets/:id/archive`
- 外部集成:
- `POST /api/integrations/erp/sync/:reimbursementId`
- `POST /api/travel/orders/import`
- `GET /api/notifications/channels`
- `POST /api/notifications/channels/test`
### 9.3 新增回归脚本
```bash
cd /home/shunli/Projects/hyb-oa/server
./scripts/regression-verification.sh
./scripts/regression-dashboard.sh
./scripts/regression-budget.sh
./scripts/regression-integrations.sh
```
可通过总回归开关启用:
```bash
cd /home/shunli/Projects/hyb-oa/server
RUN_VERIFICATION_REGRESSION=1 \
RUN_DASHBOARD_REGRESSION=1 \
RUN_BUDGET_REGRESSION=1 \
RUN_INTEGRATIONS_REGRESSION=1 \
./scripts/regression-all.sh
```
### 9.4 单次任务脚本(调试)
```bash
cd /home/shunli/Projects/hyb-oa/server
VERIFICATION_RECORD_ID=<uuid> npm run job:verification-once
npm run job:integration-outbox-once
```
### 9.5 回滚建议
1. 先关闭特性开关(验真/ERP/差旅/IM)。
2. 再停止相关任务调度(verification / integration outbox)。
3. 不回滚审计与历史台账数据,保持可追溯。
### 9.6 P9/P10 维护性与硬化说明
- 票据路由拆分:验真端点已拆到 `src/routes/invoicePool/verification.js`,读路径端点已拆到 `src/routes/invoicePool/read.js`,主入口仍为 `src/routes/invoicePool.js`,API 路径不变。
- Shared 抽象:`src/routes/invoicePool/shared/{selects,mappers,schemas,helpers}.js` 统一验真映射与票据查询 `select`,避免字段漂移。
- 看板聚合:`/api/dashboard/trends` 与 `/api/dashboard/top-categories` 已改为数据库聚合(groupBy),降低大数据量下内存聚合开销。
- 看板回归:`./scripts/regression-dashboard.sh` 新增重复请求一致性断言;可通过 `DASHBOARD_PERF_CHECK=1` 打印趋势接口耗时探针。
- ERP硬化回归:`./scripts/regression-integrations.sh` 内嵌最小 Node Mock ERP 服务,覆盖 success / 4xx(dead_letter) / 5xx(retry) / timeout(retry)。
- 矩阵门禁:`scripts/validate-feature-matrix.py` 默认校验 P5 + P6-P8 + P9 + P10 四事实源;`./scripts/check-minimal.sh` 会自动执行该校验。
+375
查看文件
@@ -0,0 +1,375 @@
#!/usr/bin/env bash
set -euo pipefail
ERP_SYNC_TIMEOUT_MS="${ERP_SYNC_TIMEOUT_MS:-300}"
MOCK_ERP_PORT="${MOCK_ERP_PORT:-$((3900 + RANDOM % 500))}"
if ! command -v node >/dev/null 2>&1; then
echo "[ERROR] node not found" >&2
exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
echo "[ERROR] curl not found" >&2
exit 1
fi
if ! command -v jq >/dev/null 2>&1; then
echo "[ERROR] jq not found" >&2
exit 1
fi
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"
if [[ -z "${DATABASE_URL:-}" && -f ".env" ]]; then
set -a
# shellcheck disable=SC1091
source .env
set +a
fi
if [[ -z "${DATABASE_URL:-}" ]]; then
echo "[ERROR] DATABASE_URL is required (export it or provide server/.env)" >&2
exit 1
fi
TMP_DIR="$(mktemp -d)"
RUN_SUFFIX="$(date +%s)-$RANDOM"
MOCK_SERVER_PID=""
cleanup() {
if [[ -n "$MOCK_SERVER_PID" ]] && kill -0 "$MOCK_SERVER_PID" >/dev/null 2>&1; then
kill "$MOCK_SERVER_PID" >/dev/null 2>&1 || true
wait "$MOCK_SERVER_PID" >/dev/null 2>&1 || true
fi
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
start_mock_erp_server() {
local server_file="$TMP_DIR/mock-erp-server.js"
cat >"$server_file" <<'NODE'
const http = require("node:http");
const { URL } = require("node:url");
const port = Number(process.argv[2] || 3900);
function sendJson(res, status, payload) {
res.statusCode = status;
res.setHeader("content-type", "application/json; charset=utf-8");
res.end(JSON.stringify(payload));
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || `127.0.0.1:${port}`}`);
if (req.method === "GET" && url.pathname === "/health") {
return sendJson(res, 200, { ok: true, mode: "health" });
}
if (req.method === "POST" && url.pathname === "/erp/reimbursements/paid") {
const mode = url.searchParams.get("mode") || "success";
const chunks = [];
for await (const chunk of req) {
chunks.push(chunk);
}
let parsedBody = null;
try {
parsedBody = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
} catch {
parsedBody = null;
}
if (mode === "timeout") {
setTimeout(() => {
sendJson(res, 200, {
ok: true,
scenario: "timeout",
externalId: `ERP-TIMEOUT-${Date.now()}`,
reimbursementId: parsedBody?.reimbursementId || null,
});
}, 1500);
return;
}
if (mode === "client") {
return sendJson(res, 422, {
ok: false,
scenario: "client",
code: "invalid_payload",
message: "mock client error",
});
}
if (mode === "server") {
return sendJson(res, 503, {
ok: false,
scenario: "server",
code: "service_unavailable",
message: "mock server error",
});
}
return sendJson(res, 200, {
ok: true,
scenario: "success",
externalId: `ERP-${parsedBody?.formNumber || parsedBody?.reimbursementId || Date.now()}`,
reimbursementId: parsedBody?.reimbursementId || null,
});
}
sendJson(res, 404, { ok: false, message: "not_found" });
});
server.listen(port, "127.0.0.1", () => {
process.stdout.write(`mock-erp-listening:${port}\n`);
});
NODE
node "$server_file" "$MOCK_ERP_PORT" >"$TMP_DIR/mock-erp.log" 2>&1 &
MOCK_SERVER_PID="$!"
for _ in $(seq 1 30); do
if curl -sS "http://127.0.0.1:$MOCK_ERP_PORT/health" >/dev/null 2>&1; then
return 0
fi
sleep 0.2
done
echo "[ERROR] mock ERP server failed to start" >&2
cat "$TMP_DIR/mock-erp.log" >&2 || true
exit 1
}
create_paid_reimbursement_and_enqueue() {
local scenario="$1"
DATABASE_URL="$DATABASE_URL" RUN_SUFFIX="$RUN_SUFFIX" SCENARIO="$scenario" node <<'NODE'
require("dotenv/config");
const { createPrismaClient } = require("./src/prismaClient");
const { getConfig } = require("./src/config");
const { buildErpPayload } = require("./src/services/integrations/erp");
const { enqueueIntegrationEvent } = require("./src/services/integrations/outbox");
(async () => {
const runSuffix = process.env.RUN_SUFFIX;
const scenario = process.env.SCENARIO;
const config = getConfig();
const { prisma, pool } = createPrismaClient();
await prisma.$connect();
try {
const owner = await prisma.employee.findFirst({
where: {
email: {
in: ["[email protected]", "[email protected]"],
},
},
select: { id: true, department_id: true },
orderBy: { created_at: "asc" },
});
if (!owner) {
throw new Error("employee/finance_mgr not found");
}
const reimbursement = await prisma.reimbursementForm.create({
data: {
form_number: `BX-P10-${scenario}-${runSuffix}`.slice(0, 60),
submitter_id: owner.id,
owner_id: owner.id,
department_id: owner.department_id,
reimbursement_date: new Date("2026-02-10T00:00:00.000Z"),
total_amount: "100.00",
status: "paid",
payment_voucher_no: `PV-${scenario}-${runSuffix}`.slice(0, 60),
payment_date: new Date("2026-02-10T00:00:00.000Z"),
paid_at: new Date(),
created_by: owner.id,
updated_by: owner.id,
},
select: {
id: true,
form_number: true,
owner_id: true,
submitter_id: true,
total_amount: true,
payment_voucher_no: true,
payment_date: true,
paid_at: true,
},
});
const payload = buildErpPayload({ reimbursement });
const enqueued = await enqueueIntegrationEvent(prisma, {
eventType: "erp.reimbursement.paid",
payload,
dedupeKey: reimbursement.id,
maxAttempts: config.integrationOutboxMaxAttempts,
actorId: owner.id,
});
process.stdout.write(
JSON.stringify({
scenario,
reimbursementId: reimbursement.id,
outboxId: enqueued.id,
duplicated: enqueued.duplicated,
}),
);
} finally {
await prisma.$disconnect();
await pool.end();
}
})().catch((error) => {
console.error(error);
process.exit(1);
});
NODE
}
query_outbox_state() {
local outbox_id="$1"
DATABASE_URL="$DATABASE_URL" OUTBOX_ID="$outbox_id" node <<'NODE'
require("dotenv/config");
const { createPrismaClient } = require("./src/prismaClient");
(async () => {
const outboxId = process.env.OUTBOX_ID;
const { prisma, pool } = createPrismaClient();
await prisma.$connect();
try {
const row = await prisma.integrationOutbox.findUnique({
where: { id: outboxId },
select: {
id: true,
status: true,
attempts: true,
next_retry_at: true,
dead_letter_at: true,
last_error: true,
},
});
if (!row) {
throw new Error(`outbox not found: ${outboxId}`);
}
process.stdout.write(
JSON.stringify({
id: row.id,
status: row.status,
attempts: row.attempts,
nextRetryAt: row.next_retry_at ? row.next_retry_at.toISOString() : null,
deadLetterAt: row.dead_letter_at ? row.dead_letter_at.toISOString() : null,
lastError: row.last_error,
}),
);
} finally {
await prisma.$disconnect();
await pool.end();
}
})().catch((error) => {
console.error(error);
process.exit(1);
});
NODE
}
run_outbox_once() {
local endpoint="$1"
ERP_SYNC_ENABLED=true \
ERP_SYNC_PROVIDER=http \
ERP_SYNC_ENDPOINT="$endpoint" \
ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_SYNC_AUTH_TOKEN="" \
npm run --silent job:integration-outbox-once >"$TMP_DIR/outbox-once.log"
}
assert_mode_semantics() {
local mode="$1"
local state_json="$2"
case "$mode" in
success)
jq -e '.status == "succeeded" and .nextRetryAt == null and .deadLetterAt == null' <<<"$state_json" >/dev/null
;;
client)
jq -e '.status == "dead_letter" and .attempts == 1 and .deadLetterAt != null and .nextRetryAt == null' <<<"$state_json" >/dev/null
jq -e '.lastError | tostring | test("422|erp_sync_http_4xx")' <<<"$state_json" >/dev/null
;;
server)
jq -e '.status == "failed" and .attempts == 1 and .deadLetterAt == null and .nextRetryAt != null' <<<"$state_json" >/dev/null
jq -e '.lastError | tostring | test("503|erp_sync_http_5xx")' <<<"$state_json" >/dev/null
;;
timeout)
jq -e '.status == "failed" and .attempts == 1 and .deadLetterAt == null and .nextRetryAt != null' <<<"$state_json" >/dev/null
jq -e '.lastError | tostring | test("erp_sync_timeout|timeout")' <<<"$state_json" >/dev/null
;;
*)
echo "[ERROR] unsupported mode assertion: $mode" >&2
exit 1
;;
esac
}
run_mode_case() {
local mode="$1"
local created_json
created_json="$(create_paid_reimbursement_and_enqueue "$mode")"
local outbox_id
outbox_id="$(jq -er '.outboxId' <<<"$created_json")"
local endpoint="http://127.0.0.1:$MOCK_ERP_PORT/erp/reimbursements/paid?mode=$mode"
local state_json=""
local status=""
for _ in $(seq 1 8); do
run_outbox_once "$endpoint"
state_json="$(query_outbox_state "$outbox_id")"
status="$(jq -r '.status' <<<"$state_json")"
if [[ "$status" != "pending" && "$status" != "processing" ]]; then
break
fi
sleep 0.2
done
if [[ "$status" == "pending" || "$status" == "processing" ]]; then
echo "[ERROR] mode=$mode did not finish processing" >&2
echo "$state_json" >&2
exit 1
fi
if ! assert_mode_semantics "$mode" "$state_json"; then
echo "[ERROR] mode=$mode semantics assertion failed" >&2
echo "$state_json" >&2
exit 1
fi
echo "[OK] mode=$mode outbox_status=$status"
}
echo "[1/6] Start embedded mock ERP server"
start_mock_erp_server
echo "[2/6] ERP success path => succeeded"
run_mode_case "success"
echo "[3/6] ERP 4xx path => dead_letter"
run_mode_case "client"
echo "[4/6] ERP 5xx path => failed(retryable)"
run_mode_case "server"
echo "[5/6] ERP timeout path => failed(retryable)"
run_mode_case "timeout"
echo "[6/6] Done"
echo "[OK] Integrations regression passed"
+23
查看文件
@@ -90,6 +90,29 @@ function getConfig() {
ocrMaxAttempts: Number(process.env.OCR_MAX_ATTEMPTS ?? 3),
ocrTimeoutMs: Number(process.env.OCR_TIMEOUT_MS ?? 5000),
invoiceVerificationEnabled: process.env.INVOICE_VERIFICATION_ENABLED === "true",
verificationProvider: process.env.VERIFICATION_PROVIDER ?? "mock",
verificationPollCron: process.env.VERIFICATION_POLL_CRON ?? "* * * * *",
verificationMaxAttempts: Number(process.env.VERIFICATION_MAX_ATTEMPTS ?? 3),
verificationRetryCooldownSeconds: Number(
process.env.VERIFICATION_RETRY_COOLDOWN_SECONDS ?? 60,
),
verificationTimeoutMs: Number(process.env.VERIFICATION_TIMEOUT_MS ?? 5000),
budgetControlMode: process.env.BUDGET_CONTROL_MODE ?? "warn",
erpSyncEnabled: process.env.ERP_SYNC_ENABLED === "true",
erpSyncProvider: process.env.ERP_SYNC_PROVIDER ?? "mock",
erpSyncEndpoint: process.env.ERP_SYNC_ENDPOINT ?? "",
erpSyncTimeoutMs: Number(process.env.ERP_SYNC_TIMEOUT_MS ?? 5000),
erpSyncAuthToken: process.env.ERP_SYNC_AUTH_TOKEN ?? "",
travelSyncEnabled: process.env.TRAVEL_SYNC_ENABLED === "true",
imNotifierEnabled: process.env.IM_NOTIFIER_ENABLED === "true",
integrationOutboxCron: process.env.INTEGRATION_OUTBOX_CRON ?? "* * * * *",
integrationOutboxBatchSize: Number(process.env.INTEGRATION_OUTBOX_BATCH_SIZE ?? 20),
integrationOutboxMaxAttempts: Number(process.env.INTEGRATION_OUTBOX_MAX_ATTEMPTS ?? 5),
integrationOutboxRetrySeconds: Number(process.env.INTEGRATION_OUTBOX_RETRY_SECONDS ?? 120),
invoiceArchiveCron: process.env.INVOICE_ARCHIVE_CRON ?? "30 2 * * *",
invoiceArchiveUnusedDays: Number(process.env.INVOICE_ARCHIVE_UNUSED_DAYS ?? 90),
invoiceArchiveBatchSize: Number(process.env.INVOICE_ARCHIVE_BATCH_SIZE ?? 200),
+124
查看文件
@@ -0,0 +1,124 @@
const cron = require("node-cron");
const {
fetchPendingOutboxEvents,
markOutboxFailed,
markOutboxProcessing,
markOutboxSucceeded,
} = require("../services/integrations/outbox");
const { dispatchOutboxEvent } = require("../services/integrations/dispatcher");
async function runIntegrationOutboxOnce(prisma, config, logger) {
const items = await fetchPendingOutboxEvents(prisma, {
batchSize: config.integrationOutboxBatchSize,
});
let succeeded = 0;
let failed = 0;
for (const item of items) {
await markOutboxProcessing(prisma, item.id, null);
try {
await dispatchOutboxEvent({
config,
eventType: item.event_type,
payload: item.payload,
});
await markOutboxSucceeded(prisma, item.id, null);
succeeded += 1;
} catch (error) {
const retryable = typeof error?.retryable === "boolean" ? error.retryable : true;
await markOutboxFailed(prisma, config, item, error, null, { retryable });
failed += 1;
logger.error(
{
err: error,
retryable,
outboxId: item.id,
eventType: item.event_type,
},
"Integration outbox dispatch failed",
);
}
}
return {
total: items.length,
succeeded,
failed,
};
}
function startIntegrationOutboxJob(fastify) {
let running = false;
const task = cron.schedule(fastify.config.integrationOutboxCron, async () => {
if (running) {
return;
}
running = true;
try {
const result = await runIntegrationOutboxOnce(
fastify.prisma,
fastify.config,
fastify.log,
);
fastify.metrics?.jobRunsTotal?.inc?.({
job: "integration.outbox.dispatch",
driver: "cron",
outcome: "success",
});
if (result.succeeded > 0) {
fastify.metrics?.jobProcessedTotal?.inc?.(
{
job: "integration.outbox.dispatch",
driver: "cron",
kind: "succeeded",
},
result.succeeded,
);
}
if (result.failed > 0) {
fastify.metrics?.jobProcessedTotal?.inc?.(
{
job: "integration.outbox.dispatch",
driver: "cron",
kind: "failed",
},
result.failed,
);
}
} catch (error) {
fastify.log.error({ err: error }, "Integration outbox job failed");
fastify.metrics?.jobRunsTotal?.inc?.({
job: "integration.outbox.dispatch",
driver: "cron",
outcome: "failure",
});
} finally {
running = false;
}
});
fastify.addHook("onClose", async () => {
task.stop();
task.destroy();
});
fastify.log.info(
{
cron: fastify.config.integrationOutboxCron,
batchSize: fastify.config.integrationOutboxBatchSize,
},
"Integration outbox job scheduled",
);
return task;
}
module.exports = {
runIntegrationOutboxOnce,
startIntegrationOutboxJob,
};
+14 -790
查看文件
@@ -7,11 +7,14 @@ const { sendData } = require("../utils/reply");
const { buildAuditLogData } = require("../utils/audit");
const { compactDateString } = require("../utils/date");
const { sha256Hex } = require("../utils/crypto");
const { signPayload, verifyToken } = require("../utils/signedUrl");
const { toMoneyString } = require("../utils/workflow");
const { findActiveDelegationForDelegate } = require("../utils/delegation");
const { isOcrEnabledForType } = require("../services/ocr");
const { openReadStream, StorageNotFoundError, writeBuffer } = require("../services/storage");
const { registerInvoiceVerificationRoutes } = require("./invoicePool/verification");
const { registerInvoicePoolReadRoutes } = require("./invoicePool/read");
const { normalizeInvoiceResponse } = require("./invoicePool/shared/mappers");
const { buildInvoiceDetailSelect } = require("./invoicePool/shared/selects");
const { writeBuffer } = require("../services/storage");
const MIME_ALLOWLIST = new Set([
"application/pdf",
@@ -52,13 +55,6 @@ const overrideDuplicateBodySchema = z
})
.strict();
const invoiceListQuerySchema = z.object({
page: z.coerce.number().int().min(1).optional(),
pageSize: z.coerce.number().int().min(1).max(100).optional(),
status: z.enum(["pending_ocr", "ocr_failed", "available", "bound", "archived"]).optional(),
ownerScope: z.enum(["own", "all"]).optional(),
});
const DEDUP_CONSTRAINT_NAMES = new Set([
"invoice_pool_file_sha256_dedup_ux",
"invoice_pool_invoice_code_number_dedup_ux",
@@ -148,36 +144,6 @@ function isInvoiceDedupConflict(error) {
return isFieldBasedDedup(fieldTokens);
}
function ensureInvoiceReadableByUser(request, invoice) {
const roleCodes = request.employee.roleCodes;
if (
roleCodes.includes("admin") ||
roleCodes.includes("finance") ||
roleCodes.includes("finance_mgr")
) {
return true;
}
if (
invoice.owner_employee_id === request.employee.id ||
invoice.uploaded_by_employee_id === request.employee.id
) {
return true;
}
if (invoice.linked_reimbursement) {
const reimbursement = invoice.linked_reimbursement;
if (
reimbursement.owner_id === request.employee.id ||
reimbursement.submitter_id === request.employee.id
) {
return true;
}
}
return false;
}
function normalizeMoneyInput(value) {
if (value == null) {
return null;
@@ -218,205 +184,9 @@ function parseDateOnlyString(value) {
return new Date(`${trimmed}T00:00:00.000Z`);
}
function sanitizeFilename(fileName) {
if (!fileName) return "file";
return fileName.replace(/[\r\n"]/g, "_");
}
function parseInvoiceListQuery(query) {
const parsed = invoiceListQuerySchema.safeParse(query ?? {});
if (!parsed.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: parsed.error.flatten(),
});
}
return {
page: parsed.data.page ?? 1,
pageSize: parsed.data.pageSize ?? 20,
status: parsed.data.status,
ownerScope: parsed.data.ownerScope,
};
}
function mapInvoiceSummary(item) {
return {
id: item.id,
status: item.status,
ocrType: item.ocr_type,
ocrProvider: item.ocr_provider,
ocrAttempts: item.ocr_attempts,
ocrLastError: item.ocr_last_error,
ocrCompletedAt: item.ocr_completed_at?.toISOString?.() ?? null,
invoiceCode: item.invoice_code,
invoiceNumber: item.invoice_number,
invoiceDate: item.invoice_date?.toISOString?.()?.slice(0, 10) ?? null,
amount: toMoneyString(item.amount),
taxAmount: toMoneyString(item.tax_amount),
totalAmount: toMoneyString(item.total_amount),
linkedReimbursementId: item.linked_reimbursement_id,
linkedItemId: item.linked_item_id,
originalName: item.original_name,
mimeType: item.mime_type,
fileSize: item.file_size,
owner: item.owner_employee
? {
id: item.owner_employee.id,
employeeNo: item.owner_employee.employee_no,
name: item.owner_employee.name,
}
: null,
uploadedBy: item.uploaded_by_employee
? {
id: item.uploaded_by_employee.id,
employeeNo: item.uploaded_by_employee.employee_no,
name: item.uploaded_by_employee.name,
}
: null,
createdAt: item.created_at?.toISOString?.() ?? null,
updatedAt: item.updated_at?.toISOString?.() ?? null,
};
}
function normalizeInvoiceResponse(invoice) {
return {
id: invoice.id,
status: invoice.status,
archivedReason: invoice.archived_reason ?? null,
archivedAt: invoice.archived_at?.toISOString?.() ?? null,
ownerEmployeeId: invoice.owner_employee_id,
uploadedByEmployeeId: invoice.uploaded_by_employee_id,
originalName: invoice.original_name ?? null,
mimeType: invoice.mime_type ?? null,
fileSize: invoice.file_size ?? null,
fileSha256: invoice.file_sha256 ?? null,
remarks: invoice.remarks ?? null,
ocrType: invoice.ocr_type,
ocrProvider: invoice.ocr_provider,
ocrAttempts: invoice.ocr_attempts,
ocrLastRequestedAt: invoice.ocr_last_requested_at?.toISOString?.() ?? null,
ocrLastError: invoice.ocr_last_error,
ocrCompletedAt: invoice.ocr_completed_at?.toISOString?.() ?? null,
invoiceCode: invoice.invoice_code,
invoiceNumber: invoice.invoice_number,
invoiceDate: invoice.invoice_date ? invoice.invoice_date.toISOString().slice(0, 10) : null,
sellerName: invoice.seller_name ?? null,
buyerName: invoice.buyer_name ?? null,
amount: toMoneyString(invoice.amount),
taxAmount: toMoneyString(invoice.tax_amount),
totalAmount: toMoneyString(invoice.total_amount),
linkedReimbursementId: invoice.linked_reimbursement_id,
linkedItemId: invoice.linked_item_id,
isDuplicateOverride: invoice.is_duplicate_override ?? false,
overrideRefFormNumber: invoice.override_ref_form_number ?? null,
overrideReason: invoice.override_reason ?? null,
overriddenBy: invoice.overridden_by ?? null,
createdAt: invoice.created_at?.toISOString?.() ?? null,
updatedAt: invoice.updated_at?.toISOString?.() ?? null,
};
}
async function invoicePoolRoutes(fastify) {
fastify.get(
"/invoice-pool",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const query = parseInvoiceListQuery(request.query);
const canViewOwn = fastify.hasPermission(request.employee, "invoice.view_own");
const canManage = fastify.hasPermission(request.employee, "invoice.manage");
if (!canViewOwn && !canManage) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const ownerScope = query.ownerScope ?? (canManage ? "all" : "own");
if (ownerScope === "all" && !canManage) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const skip = (query.page - 1) * query.pageSize;
const where = {
...(query.status ? { status: query.status } : {}),
...(ownerScope === "all"
? {}
: {
OR: [
{ owner_employee_id: request.employee.id },
{ uploaded_by_employee_id: request.employee.id },
{
linked_reimbursement: {
OR: [
{ owner_id: request.employee.id },
{ submitter_id: request.employee.id },
],
},
},
],
}),
};
const [items, total] = await Promise.all([
fastify.prisma.invoicePool.findMany({
where,
orderBy: { created_at: "desc" },
skip,
take: query.pageSize,
select: {
id: true,
status: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
original_name: true,
mime_type: true,
file_size: true,
created_at: true,
updated_at: true,
owner_employee: {
select: { id: true, employee_no: true, name: true },
},
uploaded_by_employee: {
select: { id: true, employee_no: true, name: true },
},
},
}),
fastify.prisma.invoicePool.count({ where }),
]);
return sendData(reply, request, {
page: query.page,
pageSize: query.pageSize,
total,
ownerScope,
items: items.map(mapInvoiceSummary),
});
},
);
registerInvoicePoolReadRoutes(fastify);
fastify.post(
"/invoice-pool/upload",
@@ -626,107 +396,7 @@ async function invoicePoolRoutes(fastify) {
},
);
fastify.get(
"/invoice-pool/:id",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
if (!parsedInvoiceId.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
linked_reimbursement: {
select: {
owner_id: true,
submitter_id: true,
},
},
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let canAccess = ensureInvoiceReadableByUser(request, invoice);
if (!canAccess && invoice.linked_reimbursement_id) {
const pendingTask = await fastify.prisma.workflowTask.findFirst({
where: {
status: "pending",
workflow_instance: {
entity_type: "reimbursement",
entity_id: invoice.linked_reimbursement_id,
current_status: "pending",
},
OR: [
{ assignee_id: request.employee.id },
{ assignee_role: { in: request.employee.roleCodes } },
],
},
select: { id: true },
});
canAccess = Boolean(pendingTask);
}
if (!canAccess) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
return sendData(reply, request, normalizeInvoiceResponse(invoice));
},
);
registerInvoiceVerificationRoutes(fastify);
fastify.patch(
"/invoice-pool/:id",
@@ -783,41 +453,7 @@ async function invoicePoolRoutes(fastify) {
const current = await tx.invoicePool.findUnique({
where: { id: invoiceId },
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
if (!current) {
@@ -955,41 +591,7 @@ async function invoicePoolRoutes(fastify) {
const updated = await tx.invoicePool.update({
where: { id: invoiceId },
data: updateData,
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
const changes = {};
@@ -1128,41 +730,7 @@ async function invoicePoolRoutes(fastify) {
if (current.status === "archived" && current.archived_reason === "manual") {
return tx.invoicePool.findUnique({
where: { id: invoiceId },
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
}
@@ -1184,41 +752,7 @@ async function invoicePoolRoutes(fastify) {
archived_at: now,
updated_by: request.employee.id,
},
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
await tx.auditLog.create({
@@ -1330,41 +864,7 @@ async function invoicePoolRoutes(fastify) {
linked_item_id: null,
updated_by: request.employee.id,
},
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
});
@@ -1491,41 +991,7 @@ async function invoicePoolRoutes(fastify) {
ocr_lock_owner: null,
updated_by: request.employee.id,
},
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
await tx.auditLog.create({
@@ -1702,41 +1168,7 @@ async function invoicePoolRoutes(fastify) {
overridden_by: request.employee.id,
updated_by: request.employee.id,
},
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
await tx.auditLog.create({
@@ -1760,214 +1192,6 @@ async function invoicePoolRoutes(fastify) {
},
);
fastify.post(
"/invoice-pool/:id/signed-url",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
if (!parsedInvoiceId.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
id: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
linked_reimbursement_id: true,
linked_reimbursement: {
select: {
owner_id: true,
submitter_id: true,
},
},
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let canAccess = ensureInvoiceReadableByUser(request, invoice);
if (!canAccess && invoice.linked_reimbursement_id) {
const pendingTask = await fastify.prisma.workflowTask.findFirst({
where: {
status: "pending",
workflow_instance: {
entity_type: "reimbursement",
entity_id: invoice.linked_reimbursement_id,
current_status: "pending",
},
OR: [
{ assignee_id: request.employee.id },
{ assignee_role: { in: request.employee.roleCodes } },
],
},
select: { id: true },
});
canAccess = Boolean(pendingTask);
}
if (!canAccess) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const expiresAt = Date.now() + fastify.config.signedUrlTtlSeconds * 1000;
const token = signPayload(
{
invoiceId: invoice.id,
actorId: request.employee.id,
exp: expiresAt,
},
fastify.config.jwtSecret,
);
const origin =
fastify.config.appOrigin ||
`${request.protocol}://${request.headers.host ?? "localhost:3000"}`;
const signedUrl = `${origin}/api/invoice-pool/${invoice.id}/file?token=${encodeURIComponent(token)}`;
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "INVOICE_SIGNED_URL_ISSUED",
targetType: "invoice_pool",
targetId: invoice.id,
extra: {
invoiceId: invoice.id,
expiresAt,
},
}),
});
return sendData(reply, request, {
signedUrl,
expiresAt: new Date(expiresAt).toISOString(),
});
},
);
fastify.get("/invoice-pool/:id/file", async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
const token = request.query?.token;
if (!parsedInvoiceId.success || typeof token !== "string") {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const verified = verifyToken(token, fastify.config.jwtSecret);
if (!verified.ok) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const payload = verified.payload;
const parsedActorId = z.string().uuid().safeParse(payload?.actorId);
if (
payload?.invoiceId !== parsedInvoiceId.data ||
typeof payload?.exp !== "number" ||
payload.exp <= Date.now() ||
!parsedActorId.success
) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const actorId = parsedActorId.data;
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
storage_path: true,
mime_type: true,
original_name: true,
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let stream = null;
try {
const opened = await openReadStream({
config: fastify.config,
storagePath: invoice.storage_path,
});
stream = opened.stream;
} catch (error) {
if (error instanceof StorageNotFoundError) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
throw new AppError({
code: "SYS_001",
message: "服务器内部错误",
statusCode: 500,
details: {},
});
}
try {
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: "INVOICE_FILE_DOWNLOADED",
targetType: "invoice_pool",
targetId: parsedInvoiceId.data,
extra: {
invoiceId: parsedInvoiceId.data,
exp: payload.exp,
},
}),
});
} catch (error) {
fastify.log.error({ err: error, invoiceId: parsedInvoiceId.data }, "Audit log write failed");
}
reply.type(invoice.mime_type || "application/octet-stream");
reply.header(
"content-disposition",
`inline; filename=\"${sanitizeFilename(invoice.original_name)}\"`,
);
return reply.send(stream);
});
fastify.post(
"/invoice-pool/:id/bind",
{
+413
查看文件
@@ -0,0 +1,413 @@
const { z } = require("zod");
const { AppError } = require("../../utils/AppError");
const { sendData } = require("../../utils/reply");
const { buildAuditLogData } = require("../../utils/audit");
const { signPayload, verifyToken } = require("../../utils/signedUrl");
const { openReadStream, StorageNotFoundError } = require("../../services/storage");
const {
mapInvoiceSummary,
normalizeInvoiceResponse,
} = require("./shared/mappers");
const {
buildInvoiceDetailSelect,
buildInvoiceSummarySelect,
} = require("./shared/selects");
const invoiceListQuerySchema = z.object({
page: z.coerce.number().int().min(1).optional(),
pageSize: z.coerce.number().int().min(1).max(100).optional(),
status: z.enum(["pending_ocr", "ocr_failed", "available", "bound", "archived"]).optional(),
ownerScope: z.enum(["own", "all"]).optional(),
});
function sanitizeFilename(fileName) {
if (!fileName) return "file";
return fileName.replace(/[\r\n"]/g, "_");
}
function parseInvoiceListQuery(query) {
const parsed = invoiceListQuerySchema.safeParse(query ?? {});
if (!parsed.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: parsed.error.flatten(),
});
}
return {
page: parsed.data.page ?? 1,
pageSize: parsed.data.pageSize ?? 20,
status: parsed.data.status,
ownerScope: parsed.data.ownerScope,
};
}
function ensureInvoiceReadableByUser(request, invoice) {
const roleCodes = request.employee.roleCodes;
if (
roleCodes.includes("admin") ||
roleCodes.includes("finance") ||
roleCodes.includes("finance_mgr")
) {
return true;
}
if (
invoice.owner_employee_id === request.employee.id ||
invoice.uploaded_by_employee_id === request.employee.id
) {
return true;
}
if (invoice.linked_reimbursement) {
const reimbursement = invoice.linked_reimbursement;
if (
reimbursement.owner_id === request.employee.id ||
reimbursement.submitter_id === request.employee.id
) {
return true;
}
}
return false;
}
async function hasPendingTaskAccess(fastify, request, linkedReimbursementId) {
if (!linkedReimbursementId) {
return false;
}
const pendingTask = await fastify.prisma.workflowTask.findFirst({
where: {
status: "pending",
workflow_instance: {
entity_type: "reimbursement",
entity_id: linkedReimbursementId,
current_status: "pending",
},
OR: [
{ assignee_id: request.employee.id },
{ assignee_role: { in: request.employee.roleCodes } },
],
},
select: { id: true },
});
return Boolean(pendingTask);
}
function registerInvoicePoolReadRoutes(fastify) {
fastify.get(
"/invoice-pool",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const query = parseInvoiceListQuery(request.query);
const canViewOwn = fastify.hasPermission(request.employee, "invoice.view_own");
const canManage = fastify.hasPermission(request.employee, "invoice.manage");
if (!canViewOwn && !canManage) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const ownerScope = query.ownerScope ?? (canManage ? "all" : "own");
if (ownerScope === "all" && !canManage) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const skip = (query.page - 1) * query.pageSize;
const where = {
...(query.status ? { status: query.status } : {}),
...(ownerScope === "all"
? {}
: {
OR: [
{ owner_employee_id: request.employee.id },
{ uploaded_by_employee_id: request.employee.id },
{
linked_reimbursement: {
OR: [
{ owner_id: request.employee.id },
{ submitter_id: request.employee.id },
],
},
},
],
}),
};
const [items, total] = await Promise.all([
fastify.prisma.invoicePool.findMany({
where,
orderBy: { created_at: "desc" },
skip,
take: query.pageSize,
select: buildInvoiceSummarySelect(),
}),
fastify.prisma.invoicePool.count({ where }),
]);
return sendData(reply, request, {
page: query.page,
pageSize: query.pageSize,
total,
ownerScope,
items: items.map(mapInvoiceSummary),
});
},
);
fastify.get(
"/invoice-pool/:id",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
if (!parsedInvoiceId.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: buildInvoiceDetailSelect({ includeLinkedReimbursement: true }),
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let canAccess = ensureInvoiceReadableByUser(request, invoice);
if (!canAccess) {
canAccess = await hasPendingTaskAccess(fastify, request, invoice.linked_reimbursement_id);
}
if (!canAccess) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
return sendData(reply, request, normalizeInvoiceResponse(invoice));
},
);
fastify.post(
"/invoice-pool/:id/signed-url",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
if (!parsedInvoiceId.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
id: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
linked_reimbursement_id: true,
linked_reimbursement: {
select: {
owner_id: true,
submitter_id: true,
},
},
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let canAccess = ensureInvoiceReadableByUser(request, invoice);
if (!canAccess) {
canAccess = await hasPendingTaskAccess(fastify, request, invoice.linked_reimbursement_id);
}
if (!canAccess) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const expiresAt = Date.now() + fastify.config.signedUrlTtlSeconds * 1000;
const token = signPayload(
{
invoiceId: invoice.id,
actorId: request.employee.id,
exp: expiresAt,
},
fastify.config.jwtSecret,
);
const origin =
fastify.config.appOrigin ||
`${request.protocol}://${request.headers.host ?? "localhost:3000"}`;
const signedUrl = `${origin}/api/invoice-pool/${invoice.id}/file?token=${encodeURIComponent(token)}`;
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "INVOICE_SIGNED_URL_ISSUED",
targetType: "invoice_pool",
targetId: invoice.id,
extra: {
invoiceId: invoice.id,
expiresAt,
},
}),
});
return sendData(reply, request, {
signedUrl,
expiresAt: new Date(expiresAt).toISOString(),
});
},
);
fastify.get("/invoice-pool/:id/file", async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
const token = request.query?.token;
if (!parsedInvoiceId.success || typeof token !== "string") {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const verified = verifyToken(token, fastify.config.jwtSecret);
if (!verified.ok) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const payload = verified.payload;
const parsedActorId = z.string().uuid().safeParse(payload?.actorId);
if (
payload?.invoiceId !== parsedInvoiceId.data ||
typeof payload?.exp !== "number" ||
payload.exp <= Date.now() ||
!parsedActorId.success
) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const actorId = parsedActorId.data;
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
storage_path: true,
mime_type: true,
original_name: true,
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let stream = null;
try {
const opened = await openReadStream({
config: fastify.config,
storagePath: invoice.storage_path,
});
stream = opened.stream;
} catch (error) {
if (error instanceof StorageNotFoundError) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
throw new AppError({
code: "SYS_001",
message: "服务器内部错误",
statusCode: 500,
details: {},
});
}
try {
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: "INVOICE_FILE_DOWNLOADED",
targetType: "invoice_pool",
targetId: parsedInvoiceId.data,
extra: {
invoiceId: parsedInvoiceId.data,
exp: payload.exp,
},
}),
});
} catch (error) {
fastify.log.error({ err: error, invoiceId: parsedInvoiceId.data }, "Audit log write failed");
}
reply.type(invoice.mime_type || "application/octet-stream");
reply.header(
"content-disposition",
`inline; filename=\"${sanitizeFilename(invoice.original_name)}\"`,
);
return reply.send(stream);
});
}
module.exports = {
registerInvoicePoolReadRoutes,
};
@@ -0,0 +1,58 @@
const { pushPaidReimbursementToErp } = require("./erp");
class IntegrationDispatchError extends Error {
constructor({ code, message, retryable, statusCode, response }) {
super(message || code || "integration_dispatch_failed");
this.name = "IntegrationDispatchError";
this.code = code || "integration_dispatch_failed";
this.retryable = typeof retryable === "boolean" ? retryable : true;
this.statusCode = Number.isFinite(statusCode) ? Number(statusCode) : null;
this.response = response ?? null;
}
}
function toDispatchError(result) {
return new IntegrationDispatchError({
code: result?.code,
message: result?.message,
retryable: result?.retryable,
statusCode: result?.httpStatus,
response: result?.response,
});
}
async function dispatchOutboxEvent({ config, eventType, payload }) {
if (eventType === "erp.reimbursement.paid") {
const result = await pushPaidReimbursementToErp(config, payload);
if (!result.ok) {
throw toDispatchError(result);
}
return {
channel: "erp",
code: result.code,
response: result.response ?? null,
};
}
if (eventType === "notification.im") {
return {
channel: "im",
code: "mock_sent",
response: {
channelType: payload.channelType,
},
};
}
throw new IntegrationDispatchError({
code: "unsupported_outbox_event",
message: `unsupported_outbox_event:${eventType}`,
retryable: false,
});
}
module.exports = {
IntegrationDispatchError,
dispatchOutboxEvent,
};
+157
查看文件
@@ -0,0 +1,157 @@
function buildErpPayload(input) {
return {
reimbursementId: input.reimbursement.id,
formNumber: input.reimbursement.form_number,
ownerEmployeeId: input.reimbursement.owner_id,
submitterEmployeeId: input.reimbursement.submitter_id,
totalAmount: input.reimbursement.total_amount?.toString?.() ?? null,
paymentVoucherNo: input.reimbursement.payment_voucher_no ?? null,
paymentDate: input.reimbursement.payment_date
? new Date(input.reimbursement.payment_date).toISOString().slice(0, 10)
: null,
paidAt: input.reimbursement.paid_at ? new Date(input.reimbursement.paid_at).toISOString() : null,
};
}
function normalizeProvider(config) {
return String(config.erpSyncProvider ?? "mock").trim().toLowerCase() || "mock";
}
function buildAuthHeaders(config) {
const token = String(config.erpSyncAuthToken ?? "").trim();
if (!token) {
return {};
}
return {
authorization: `Bearer ${token}`,
};
}
async function postToErpHttp(config, payload) {
const endpoint = String(config.erpSyncEndpoint ?? "").trim();
if (!endpoint) {
return {
ok: false,
code: "erp_sync_endpoint_missing",
message: "ERP sync endpoint missing",
retryable: false,
};
}
const timeoutMs = Math.max(100, Number(config.erpSyncTimeoutMs ?? 5000));
const controller = new AbortController();
const timer = setTimeout(() => {
controller.abort();
}, timeoutMs);
try {
const response = await fetch(endpoint, {
method: "POST",
headers: {
"content-type": "application/json",
...buildAuthHeaders(config),
},
body: JSON.stringify(payload),
signal: controller.signal,
});
let responseBody = null;
const contentType = response.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
try {
responseBody = await response.json();
} catch {
responseBody = null;
}
} else {
try {
responseBody = await response.text();
} catch {
responseBody = null;
}
}
if (response.ok) {
return {
ok: true,
code: "http_synced",
message: "ERP synced",
response: {
status: response.status,
body: responseBody,
},
};
}
const retryable = response.status >= 500;
return {
ok: false,
code: retryable ? "erp_sync_http_5xx" : "erp_sync_http_4xx",
message: `ERP sync HTTP ${response.status}`,
retryable,
httpStatus: response.status,
response: {
status: response.status,
body: responseBody,
},
};
} catch (error) {
if (error?.name === "AbortError") {
return {
ok: false,
code: "erp_sync_timeout",
message: `ERP sync timeout (${timeoutMs}ms)`,
retryable: true,
};
}
return {
ok: false,
code: "erp_sync_network_error",
message: String(error?.message ?? error ?? "ERP sync network error"),
retryable: true,
};
} finally {
clearTimeout(timer);
}
}
async function pushPaidReimbursementToErp(config, payload) {
if (!config.erpSyncEnabled) {
return {
ok: false,
code: "erp_sync_disabled",
message: "ERP sync disabled",
retryable: false,
};
}
const provider = normalizeProvider(config);
if (provider === "mock") {
return {
ok: true,
code: "mock_synced",
message: "mock ERP synced",
response: {
externalId: `ERP-${payload.formNumber ?? payload.reimbursementId}`,
},
};
}
if (provider === "http") {
return postToErpHttp(config, payload);
}
return {
ok: false,
code: "erp_sync_provider_invalid",
message: `Unsupported ERP sync provider: ${provider}`,
retryable: false,
};
}
module.exports = {
buildErpPayload,
pushPaidReimbursementToErp,
};
+161
查看文件
@@ -0,0 +1,161 @@
const OUTBOX_STATUSES = {
pending: "pending",
processing: "processing",
succeeded: "succeeded",
failed: "failed",
dead_letter: "dead_letter",
};
function nextRetryAt(config, attempts) {
const waitSeconds = Math.max(30, Number(config.integrationOutboxRetrySeconds ?? 120));
const backoff = waitSeconds * Math.max(1, attempts);
return new Date(Date.now() + backoff * 1000);
}
function formatDispatchError(error) {
const code = error?.code ? String(error.code) : null;
const statusCode = Number.isFinite(error?.statusCode) ? Number(error.statusCode) : null;
const message = String(error?.message ?? error ?? "integration_outbox_error").trim();
const parts = [];
if (code) {
parts.push(code);
}
if (statusCode != null) {
parts.push(`HTTP ${statusCode}`);
}
if (message) {
parts.push(message);
}
if (!parts.length) {
return "integration_outbox_error";
}
return parts.join(" | ");
}
async function enqueueIntegrationEvent(prisma, input) {
const dedupeKey = input.dedupeKey ?? null;
const existed =
dedupeKey != null
? await prisma.integrationOutbox.findUnique({
where: {
event_type_dedupe_key: {
event_type: input.eventType,
dedupe_key: dedupeKey,
},
},
select: { id: true, status: true },
})
: null;
if (existed) {
return {
id: existed.id,
status: existed.status,
duplicated: true,
};
}
const created = await prisma.integrationOutbox.create({
data: {
event_type: input.eventType,
status: OUTBOX_STATUSES.pending,
payload: input.payload,
dedupe_key: dedupeKey,
max_attempts: input.maxAttempts,
created_by: input.actorId ?? null,
updated_by: input.actorId ?? null,
},
select: {
id: true,
status: true,
},
});
return {
id: created.id,
status: created.status,
duplicated: false,
};
}
async function fetchPendingOutboxEvents(prisma, options) {
const batchSize = Math.max(1, Number(options.batchSize ?? 20));
const now = new Date();
return prisma.integrationOutbox.findMany({
where: {
status: {
in: [OUTBOX_STATUSES.pending, OUTBOX_STATUSES.failed],
},
OR: [{ next_retry_at: null }, { next_retry_at: { lte: now } }],
},
orderBy: [{ created_at: "asc" }],
take: batchSize,
});
}
async function markOutboxProcessing(prisma, id, actorId) {
return prisma.integrationOutbox.update({
where: { id },
data: {
status: OUTBOX_STATUSES.processing,
updated_by: actorId ?? null,
},
});
}
async function markOutboxSucceeded(prisma, id, actorId) {
return prisma.integrationOutbox.update({
where: { id },
data: {
status: OUTBOX_STATUSES.succeeded,
processed_at: new Date(),
last_error: null,
updated_by: actorId ?? null,
},
});
}
async function markOutboxFailed(prisma, config, item, error, actorId, options = {}) {
const attempts = Number(item.attempts ?? 0) + 1;
const maxAttempts = Math.max(
1,
Number(item.max_attempts ?? config.integrationOutboxMaxAttempts ?? 5),
);
const retryable =
typeof options.retryable === "boolean"
? options.retryable
: typeof error?.retryable === "boolean"
? error.retryable
: true;
const deadByAttempts = retryable && attempts >= maxAttempts;
const deadByPolicy = !retryable;
const dead = deadByPolicy || deadByAttempts;
return prisma.integrationOutbox.update({
where: { id: item.id },
data: {
attempts,
status: dead ? OUTBOX_STATUSES.dead_letter : OUTBOX_STATUSES.failed,
dead_letter_at: dead ? new Date() : null,
next_retry_at: dead ? null : nextRetryAt(config, attempts),
last_error: formatDispatchError(error).slice(0, 500),
updated_by: actorId ?? null,
},
});
}
module.exports = {
OUTBOX_STATUSES,
enqueueIntegrationEvent,
fetchPendingOutboxEvents,
markOutboxProcessing,
markOutboxSucceeded,
markOutboxFailed,
};