docs/test(P19ERP1-5,P19ERP1-6): 收口ERP文档矩阵与回归
这个提交包含在:
@@ -3,6 +3,16 @@ set -euo pipefail
|
||||
|
||||
ERP_SYNC_TIMEOUT_MS="${ERP_SYNC_TIMEOUT_MS:-300}"
|
||||
MOCK_ERP_PORT="${MOCK_ERP_PORT:-$((3900 + RANDOM % 500))}"
|
||||
APP_PORT="${APP_PORT:-$((4300 + RANDOM % 500))}"
|
||||
BASE_URL="http://127.0.0.1:${APP_PORT}"
|
||||
DEVICE_FINGERPRINT="${DEVICE_FINGERPRINT:-regression-integrations}"
|
||||
FINANCE_MGR_IDENTIFIER="${FINANCE_MGR_IDENTIFIER:-finance_mgr@hyinda.com}"
|
||||
FINANCE_MGR_PASSWORD="${FINANCE_MGR_PASSWORD:-FinanceMgrPassword1234}"
|
||||
RUN_SUFFIX="$(date +%s)-$RANDOM"
|
||||
RUN_SUFFIX_NUMERIC="${RUN_SUFFIX//[^0-9]/}"
|
||||
LEGAL_ENTITY_CODE="LE${RUN_SUFFIX_NUMERIC}"
|
||||
COST_CENTER_CODE="CC${RUN_SUFFIX_NUMERIC}"
|
||||
SUPPLIER_CODE="SUP${RUN_SUFFIX_NUMERIC}"
|
||||
|
||||
if ! command -v node >/dev/null 2>&1; then
|
||||
echo "[ERROR] node not found" >&2
|
||||
@@ -35,10 +45,15 @@ if [[ -z "${DATABASE_URL:-}" ]]; then
|
||||
fi
|
||||
|
||||
TMP_DIR="$(mktemp -d)"
|
||||
RUN_SUFFIX="$(date +%s)-$RANDOM"
|
||||
MOCK_SERVER_PID=""
|
||||
APP_SERVER_PID=""
|
||||
TOKEN=""
|
||||
|
||||
cleanup() {
|
||||
if [[ -n "$APP_SERVER_PID" ]] && kill -0 "$APP_SERVER_PID" >/dev/null 2>&1; then
|
||||
kill "$APP_SERVER_PID" >/dev/null 2>&1 || true
|
||||
wait "$APP_SERVER_PID" >/dev/null 2>&1 || true
|
||||
fi
|
||||
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
|
||||
@@ -47,31 +62,102 @@ cleanup() {
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
assert_status() {
|
||||
local actual="$1"
|
||||
local expected="$2"
|
||||
local name="$3"
|
||||
if [[ "$actual" != "$expected" ]]; then
|
||||
echo "[ERROR] $name expected HTTP $expected but got $actual" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
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 http = require('node:http');
|
||||
const { URL } = require('node:url');
|
||||
|
||||
const port = Number(process.argv[2] || 3900);
|
||||
const runSuffix = String(process.env.RUN_SUFFIX ?? '001');
|
||||
const runDigits = runSuffix.replace(/\D+/g, '');
|
||||
const legalEntityCode = `LE${runDigits}`;
|
||||
const costCenterCode = `CC${runDigits}`;
|
||||
const supplierCode = `SUP${runDigits}`;
|
||||
|
||||
function sendJson(res, status, payload) {
|
||||
res.statusCode = status;
|
||||
res.setHeader("content-type", "application/json; charset=utf-8");
|
||||
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 === '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";
|
||||
if (req.method === 'POST' && url.pathname === '/erp/master-data/pull') {
|
||||
const mode = url.searchParams.get('mode') || 'success';
|
||||
if (mode === 'timeout') {
|
||||
setTimeout(() => {
|
||||
sendJson(res, 200, { ok: true, delayed: true });
|
||||
}, 1500);
|
||||
return;
|
||||
}
|
||||
if (mode === 'client') {
|
||||
return sendJson(res, 422, { ok: false, code: 'invalid_payload', message: 'mock client error' });
|
||||
}
|
||||
if (mode === 'server') {
|
||||
return sendJson(res, 503, { ok: false, code: 'service_unavailable', message: 'mock server error' });
|
||||
}
|
||||
|
||||
return sendJson(res, 200, {
|
||||
ok: true,
|
||||
legalEntities: [
|
||||
{
|
||||
externalId: `ERP-${legalEntityCode}`,
|
||||
code: legalEntityCode,
|
||||
name: `法体-${runSuffix}`,
|
||||
shortName: `法体-${runDigits}`,
|
||||
currencyCode: 'CNY',
|
||||
taxNo: `TAX-${runDigits}`,
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
costCenters: [
|
||||
{
|
||||
externalId: `ERP-${costCenterCode}`,
|
||||
legalEntityCode,
|
||||
code: costCenterCode,
|
||||
name: `成本中心-${runSuffix}`,
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
suppliers: [
|
||||
{
|
||||
externalId: `ERP-${supplierCode}`,
|
||||
legalEntityCode,
|
||||
code: supplierCode,
|
||||
name: `供应商-${runSuffix}`,
|
||||
shortName: `供应商-${runDigits}`,
|
||||
taxNo: `SUP-TAX-${runDigits}`,
|
||||
contactName: '张三',
|
||||
contactPhone: '13800000000',
|
||||
paymentTerms: '月结30天',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
req.method === 'POST' &&
|
||||
(url.pathname === '/erp/journals/reimbursements/paid' || url.pathname === '/erp/reimbursements/paid')
|
||||
) {
|
||||
const mode = url.searchParams.get('mode') || 'success';
|
||||
const chunks = [];
|
||||
for await (const chunk of req) {
|
||||
chunks.push(chunk);
|
||||
@@ -79,58 +165,58 @@ const server = http.createServer(async (req, res) => {
|
||||
|
||||
let parsedBody = null;
|
||||
try {
|
||||
parsedBody = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
||||
parsedBody = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||||
} catch {
|
||||
parsedBody = null;
|
||||
}
|
||||
|
||||
if (mode === "timeout") {
|
||||
if (mode === 'timeout') {
|
||||
setTimeout(() => {
|
||||
sendJson(res, 200, {
|
||||
ok: true,
|
||||
scenario: "timeout",
|
||||
scenario: 'timeout',
|
||||
externalId: `ERP-TIMEOUT-${Date.now()}`,
|
||||
reimbursementId: parsedBody?.reimbursementId || null,
|
||||
reimbursementId: parsedBody?.reimbursementId || parsedBody?.entityId || null,
|
||||
});
|
||||
}, 1500);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === "client") {
|
||||
if (mode === 'client') {
|
||||
return sendJson(res, 422, {
|
||||
ok: false,
|
||||
scenario: "client",
|
||||
code: "invalid_payload",
|
||||
message: "mock client error",
|
||||
scenario: 'client',
|
||||
code: 'invalid_payload',
|
||||
message: 'mock client error',
|
||||
});
|
||||
}
|
||||
|
||||
if (mode === "server") {
|
||||
if (mode === 'server') {
|
||||
return sendJson(res, 503, {
|
||||
ok: false,
|
||||
scenario: "server",
|
||||
code: "service_unavailable",
|
||||
message: "mock server error",
|
||||
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,
|
||||
scenario: 'success',
|
||||
externalId: `ERP-${parsedBody?.documentNo || parsedBody?.formNumber || parsedBody?.entityId || Date.now()}`,
|
||||
reimbursementId: parsedBody?.reimbursementId || parsedBody?.entityId || null,
|
||||
});
|
||||
}
|
||||
|
||||
sendJson(res, 404, { ok: false, message: "not_found" });
|
||||
sendJson(res, 404, { ok: false, message: 'not_found' });
|
||||
});
|
||||
|
||||
server.listen(port, "127.0.0.1", () => {
|
||||
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 &
|
||||
RUN_SUFFIX="$RUN_SUFFIX" node "$server_file" "$MOCK_ERP_PORT" >"$TMP_DIR/mock-erp.log" 2>&1 &
|
||||
MOCK_SERVER_PID="$!"
|
||||
|
||||
for _ in $(seq 1 30); do
|
||||
@@ -145,180 +231,71 @@ NODE
|
||||
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"
|
||||
start_app_server() {
|
||||
PORT="$APP_PORT" \
|
||||
HOST="127.0.0.1" \
|
||||
JOBS_ENABLED=false \
|
||||
OCR_PROVIDER=mock \
|
||||
ERP_SYNC_ENABLED=true \
|
||||
ERP_SYNC_PROVIDER=http \
|
||||
ERP_SYNC_ENDPOINT="$endpoint" \
|
||||
ERP_MASTER_DATA_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/master-data/pull?mode=success" \
|
||||
ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/reimbursements/paid?mode=success" \
|
||||
ERP_SYNC_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/reimbursements/paid?mode=success" \
|
||||
ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
|
||||
ERP_MASTER_DATA_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
|
||||
ERP_SYNC_AUTH_TOKEN="" \
|
||||
npm run --silent job:integration-outbox-once >"$TMP_DIR/outbox-once.log"
|
||||
node src/index.js >"$TMP_DIR/app.log" 2>&1 &
|
||||
APP_SERVER_PID="$!"
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
if curl -sS "$BASE_URL/health" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
|
||||
echo "[ERROR] app server failed to start" >&2
|
||||
cat "$TMP_DIR/app.log" >&2 || true
|
||||
exit 1
|
||||
}
|
||||
|
||||
login_finance_mgr() {
|
||||
local login_body="$TMP_DIR/login.json"
|
||||
local login_status
|
||||
login_status="$(curl -sS -o "$login_body" -w "%{http_code}" \
|
||||
-X POST "$BASE_URL/api/auth/login" \
|
||||
-H "content-type: application/json" \
|
||||
-H "x-device-fingerprint: ${DEVICE_FINGERPRINT}-finance" \
|
||||
-d "{\"identifier\":\"$FINANCE_MGR_IDENTIFIER\",\"password\":\"$FINANCE_MGR_PASSWORD\"}")"
|
||||
assert_status "$login_status" "200" "finance_mgr login"
|
||||
TOKEN="$(jq -er '.data.accessToken' "$login_body")"
|
||||
}
|
||||
|
||||
set_erp_flag() {
|
||||
local mode="$1"
|
||||
DATABASE_URL="$DATABASE_URL" MODE="$mode" node <<'NODE'
|
||||
require("dotenv/config");
|
||||
|
||||
const { createPrismaClient } = require("./src/prismaClient");
|
||||
require('dotenv/config');
|
||||
const { createPrismaClient } = require('./src/prismaClient');
|
||||
|
||||
(async () => {
|
||||
const mode = process.env.MODE;
|
||||
const { prisma, pool } = createPrismaClient();
|
||||
await prisma.$connect();
|
||||
|
||||
try {
|
||||
await prisma.featureFlag.upsert({
|
||||
where: { flag_key: "erp_sync" },
|
||||
where: { flag_key: 'erp_sync' },
|
||||
create: {
|
||||
flag_key: "erp_sync",
|
||||
flag_key: 'erp_sync',
|
||||
override_mode: mode,
|
||||
rollout_type: "global",
|
||||
rollout_type: 'global',
|
||||
department_ids: [],
|
||||
note: "regression-integrations",
|
||||
note: 'regression-integrations',
|
||||
},
|
||||
update: {
|
||||
override_mode: mode,
|
||||
rollout_type: "global",
|
||||
rollout_type: 'global',
|
||||
department_ids: [],
|
||||
note: "regression-integrations",
|
||||
note: 'regression-integrations',
|
||||
version: { increment: 1 },
|
||||
},
|
||||
});
|
||||
@@ -333,10 +310,250 @@ const { createPrismaClient } = require("./src/prismaClient");
|
||||
NODE
|
||||
}
|
||||
|
||||
echo "[0/6] Ensure ERP feature flag force_on"
|
||||
set_erp_flag "force_on"
|
||||
create_paid_reimbursement() {
|
||||
DATABASE_URL="$DATABASE_URL" RUN_SUFFIX="$RUN_SUFFIX" node <<'NODE'
|
||||
require('dotenv/config');
|
||||
|
||||
assert_mode_semantics() {
|
||||
const { createPrismaClient } = require('./src/prismaClient');
|
||||
|
||||
(async () => {
|
||||
const runSuffix = process.env.RUN_SUFFIX;
|
||||
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,
|
||||
legal_entity_id: true,
|
||||
},
|
||||
orderBy: { created_at: 'asc' },
|
||||
});
|
||||
|
||||
if (!owner) {
|
||||
throw new Error('seed employee not found');
|
||||
}
|
||||
|
||||
const uniqueSuffix = `${runSuffix}-${Date.now()}-${Math.floor(Math.random() * 1000000)}`;
|
||||
|
||||
const reimbursement = await prisma.reimbursementForm.create({
|
||||
data: {
|
||||
form_number: `BX-ERP-${uniqueSuffix}`.slice(0, 60),
|
||||
submitter_id: owner.id,
|
||||
owner_id: owner.id,
|
||||
department_id: owner.department_id,
|
||||
reimbursement_date: new Date('2026-03-08T00:00:00.000Z'),
|
||||
total_amount: '100.00',
|
||||
status: 'paid',
|
||||
payment_voucher_no: `PV-ERP-${uniqueSuffix}`.slice(0, 60),
|
||||
payment_date: new Date('2026-03-08T00:00:00.000Z'),
|
||||
paid_at: new Date(),
|
||||
created_by: owner.id,
|
||||
updated_by: owner.id,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
process.stdout.write(reimbursement.id);
|
||||
} 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,
|
||||
event_type: true,
|
||||
status: true,
|
||||
attempts: true,
|
||||
next_retry_at: true,
|
||||
processed_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,
|
||||
eventType: row.event_type,
|
||||
status: row.status,
|
||||
attempts: row.attempts,
|
||||
nextRetryAt: row.next_retry_at ? row.next_retry_at.toISOString() : null,
|
||||
processedAt: row.processed_at ? row.processed_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
|
||||
}
|
||||
|
||||
query_binding_state() {
|
||||
local reimbursement_id="$1"
|
||||
DATABASE_URL="$DATABASE_URL" REIMBURSEMENT_ID="$reimbursement_id" node <<'NODE'
|
||||
require('dotenv/config');
|
||||
const { createPrismaClient } = require('./src/prismaClient');
|
||||
|
||||
(async () => {
|
||||
const reimbursementId = process.env.REIMBURSEMENT_ID;
|
||||
const { prisma, pool } = createPrismaClient();
|
||||
await prisma.$connect();
|
||||
try {
|
||||
const row = await prisma.integrationBinding.findUnique({
|
||||
where: {
|
||||
provider_entity_type_local_id: {
|
||||
provider: 'erp',
|
||||
entity_type: 'reimbursement_journal',
|
||||
local_id: reimbursementId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
external_id: true,
|
||||
external_code: true,
|
||||
last_synced_at: true,
|
||||
},
|
||||
});
|
||||
process.stdout.write(JSON.stringify({
|
||||
externalId: row?.external_id ?? null,
|
||||
externalCode: row?.external_code ?? null,
|
||||
lastSyncedAt: row?.last_synced_at ? row.last_synced_at.toISOString() : null,
|
||||
}));
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
await pool.end();
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
NODE
|
||||
}
|
||||
|
||||
assert_master_data_seeded() {
|
||||
DATABASE_URL="$DATABASE_URL" LEGAL_ENTITY_CODE="$LEGAL_ENTITY_CODE" COST_CENTER_CODE="$COST_CENTER_CODE" SUPPLIER_CODE="$SUPPLIER_CODE" node <<'NODE'
|
||||
require('dotenv/config');
|
||||
const { createPrismaClient } = require('./src/prismaClient');
|
||||
|
||||
(async () => {
|
||||
const { prisma, pool } = createPrismaClient();
|
||||
await prisma.$connect();
|
||||
try {
|
||||
const legalEntity = await prisma.legalEntity.findUnique({
|
||||
where: { code: process.env.LEGAL_ENTITY_CODE },
|
||||
select: { id: true },
|
||||
});
|
||||
const supplier = await prisma.supplier.findUnique({
|
||||
where: { code: process.env.SUPPLIER_CODE },
|
||||
select: { id: true },
|
||||
});
|
||||
const costCenter = await prisma.costCenter.findFirst({
|
||||
where: { code: process.env.COST_CENTER_CODE },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!legalEntity || !costCenter || !supplier) {
|
||||
throw new Error('master data not synced as expected');
|
||||
}
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
await pool.end();
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
NODE
|
||||
}
|
||||
|
||||
run_outbox_once() {
|
||||
local mode="$1"
|
||||
DATABASE_URL="$DATABASE_URL" \
|
||||
INTEGRATION_OUTBOX_BATCH_SIZE=500 \
|
||||
ERP_SYNC_ENABLED=true \
|
||||
ERP_SYNC_PROVIDER=http \
|
||||
ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/reimbursements/paid?mode=$mode" \
|
||||
ERP_SYNC_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/reimbursements/paid?mode=$mode" \
|
||||
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_pull_mode() {
|
||||
local mode="$1"
|
||||
ERP_SYNC_ENABLED=true \
|
||||
ERP_SYNC_PROVIDER=http \
|
||||
ERP_MASTER_DATA_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/master-data/pull?mode=$mode" \
|
||||
ERP_MASTER_DATA_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
|
||||
ERP_SYNC_AUTH_TOKEN="" \
|
||||
node <<'NODE'
|
||||
const { pullMasterDataFromErp } = require('./src/services/integrations/erp');
|
||||
(async () => {
|
||||
const result = await pullMasterDataFromErp({
|
||||
erpSyncEnabled: true,
|
||||
erpSyncProvider: 'http',
|
||||
erpMasterDataEndpoint: process.env.ERP_MASTER_DATA_ENDPOINT,
|
||||
erpMasterDataTimeoutMs: Number(process.env.ERP_MASTER_DATA_TIMEOUT_MS ?? 300),
|
||||
erpSyncAuthToken: process.env.ERP_SYNC_AUTH_TOKEN ?? '',
|
||||
}, { resources: ['legal_entity'] });
|
||||
process.stdout.write(JSON.stringify(result));
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
NODE
|
||||
}
|
||||
|
||||
api_get() {
|
||||
local path="$1"
|
||||
local out_file="$2"
|
||||
curl -sS -o "$out_file" -w "%{http_code}" \
|
||||
-H "authorization: Bearer $TOKEN" \
|
||||
"$BASE_URL$path"
|
||||
}
|
||||
|
||||
api_post() {
|
||||
local path="$1"
|
||||
local body="$2"
|
||||
local out_file="$3"
|
||||
curl -sS -o "$out_file" -w "%{http_code}" \
|
||||
-X POST "$BASE_URL$path" \
|
||||
-H "authorization: Bearer $TOKEN" \
|
||||
-H "content-type: application/json" \
|
||||
-d "$body"
|
||||
}
|
||||
|
||||
assert_export_mode_semantics() {
|
||||
local mode="$1"
|
||||
local state_json="$2"
|
||||
|
||||
@@ -363,20 +580,22 @@ assert_mode_semantics() {
|
||||
esac
|
||||
}
|
||||
|
||||
run_mode_case() {
|
||||
run_export_mode_case() {
|
||||
local mode="$1"
|
||||
local reimbursement_id
|
||||
reimbursement_id="$(create_paid_reimbursement)"
|
||||
|
||||
local created_json
|
||||
created_json="$(create_paid_reimbursement_and_enqueue "$mode")"
|
||||
local export_body="$TMP_DIR/export-$mode.json"
|
||||
local export_status
|
||||
export_status="$(api_post "/api/integrations/erp/journals/reimbursements/${reimbursement_id}/export?runNow=0" '{}' "$export_body")"
|
||||
assert_status "$export_status" "200" "journal export 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"
|
||||
outbox_id="$(jq -er '.data.outboxId' "$export_body")"
|
||||
|
||||
local state_json=""
|
||||
local status=""
|
||||
for _ in $(seq 1 8); do
|
||||
run_outbox_once "$endpoint"
|
||||
run_outbox_once "$mode"
|
||||
state_json="$(query_outbox_state "$outbox_id")"
|
||||
status="$(jq -r '.status' <<<"$state_json")"
|
||||
if [[ "$status" != "pending" && "$status" != "processing" ]]; then
|
||||
@@ -386,37 +605,122 @@ run_mode_case() {
|
||||
done
|
||||
|
||||
if [[ "$status" == "pending" || "$status" == "processing" ]]; then
|
||||
echo "[ERROR] mode=$mode did not finish processing" >&2
|
||||
echo "[ERROR] export 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
|
||||
assert_export_mode_semantics "$mode" "$state_json"
|
||||
|
||||
if [[ "$mode" == "success" ]]; then
|
||||
local binding_json
|
||||
binding_json="$(query_binding_state "$reimbursement_id")"
|
||||
jq -e '.externalId != null and .externalCode != null' <<<"$binding_json" >/dev/null
|
||||
fi
|
||||
|
||||
echo "[OK] mode=$mode outbox_status=$status"
|
||||
echo "[OK] export mode=$mode outbox_status=$status" >&2
|
||||
printf '%s' "$reimbursement_id"
|
||||
}
|
||||
|
||||
echo "[1/6] Start embedded mock ERP server"
|
||||
echo "[0/9] Ensure ERP feature flag force_on"
|
||||
set_erp_flag "force_on"
|
||||
|
||||
echo "[1/9] Start embedded mock ERP server"
|
||||
start_mock_erp_server
|
||||
|
||||
echo "[2/6] ERP success path => succeeded"
|
||||
run_mode_case "success"
|
||||
echo "[2/9] Start isolated app server"
|
||||
start_app_server
|
||||
|
||||
echo "[3/6] ERP 4xx path => dead_letter"
|
||||
run_mode_case "client"
|
||||
sleep 1
|
||||
|
||||
echo "[4/6] ERP 5xx path => failed(retryable)"
|
||||
run_mode_case "server"
|
||||
echo "[3/9] Login finance manager"
|
||||
login_finance_mgr
|
||||
|
||||
echo "[5/6] ERP timeout path => failed(retryable)"
|
||||
run_mode_case "timeout"
|
||||
echo "[4/9] ERP status + master data sync success"
|
||||
status_body="$TMP_DIR/status.json"
|
||||
status_code="$(api_get '/api/integrations/erp/master-data/status' "$status_body")"
|
||||
assert_status "$status_code" "200" "erp status"
|
||||
jq -e '.data.gate.provider == "http" and (.data.items | length) == 3' "$status_body" >/dev/null
|
||||
|
||||
sync_body="$TMP_DIR/master-sync.json"
|
||||
sync_code="$(api_post '/api/integrations/erp/master-data/sync' '{"resources":["legal_entity","cost_center","supplier"]}' "$sync_body")"
|
||||
assert_status "$sync_code" "200" "erp master data sync"
|
||||
jq -e '.data.items | all(.status == "succeeded")' "$sync_body" >/dev/null
|
||||
assert_master_data_seeded
|
||||
|
||||
echo "[5/9] ERP master data provider error modes"
|
||||
for mode in client server timeout; do
|
||||
mode_json="$(assert_pull_mode "$mode")"
|
||||
case "$mode" in
|
||||
client) jq -e '.ok == false and .code == "erp_master_data_http_4xx"' <<<"$mode_json" >/dev/null ;;
|
||||
server) jq -e '.ok == false and .code == "erp_master_data_http_5xx"' <<<"$mode_json" >/dev/null ;;
|
||||
timeout) jq -e '.ok == false and .code == "erp_master_data_timeout"' <<<"$mode_json" >/dev/null ;;
|
||||
esac
|
||||
echo "[OK] master-data mode=$mode validated"
|
||||
done
|
||||
|
||||
echo "[6/9] Preview paid reimbursement journal"
|
||||
preview_reimbursement_id="$(create_paid_reimbursement)"
|
||||
preview_body="$TMP_DIR/preview.json"
|
||||
preview_code="$(api_get "/api/integrations/erp/journals/reimbursements/${preview_reimbursement_id}/preview" "$preview_body")"
|
||||
assert_status "$preview_code" "200" "journal preview"
|
||||
jq -e '.data.journal.journalType == "reimbursement_paid" and .data.journal.entityId != null' "$preview_body" >/dev/null
|
||||
|
||||
echo "[7/9] Export journal success / 4xx / 5xx / timeout"
|
||||
run_export_mode_case success >/dev/null
|
||||
client_reimbursement_id="$(run_export_mode_case client)"
|
||||
run_export_mode_case server >/dev/null
|
||||
run_export_mode_case timeout >/dev/null
|
||||
|
||||
echo "[8/9] Dead-letter requeue + legacy alias"
|
||||
requeue_body="$TMP_DIR/requeue.json"
|
||||
requeue_code="$(api_post "/api/integrations/erp/journals/reimbursements/${client_reimbursement_id}/export?runNow=0" '{}' "$requeue_body")"
|
||||
assert_status "$requeue_code" "200" "journal export requeue"
|
||||
jq -e '.data.requeued == true and .data.duplicated == false' "$requeue_body" >/dev/null
|
||||
requeue_outbox_id="$(jq -er '.data.outboxId' "$requeue_body")"
|
||||
requeue_state="$(query_outbox_state "$requeue_outbox_id")"
|
||||
jq -e '.status == "pending" and .attempts == 0 and .lastError == null' <<<"$requeue_state" >/dev/null
|
||||
run_outbox_once success
|
||||
requeue_state_done="$(query_outbox_state "$requeue_outbox_id")"
|
||||
jq -e '.status == "succeeded"' <<<"$requeue_state_done" >/dev/null
|
||||
|
||||
legacy_reimbursement_id="$(create_paid_reimbursement)"
|
||||
legacy_body="$TMP_DIR/legacy-export.json"
|
||||
legacy_code="$(api_post "/api/integrations/erp/sync/${legacy_reimbursement_id}?runNow=0" '{}' "$legacy_body")"
|
||||
assert_status "$legacy_code" "200" "legacy erp sync alias"
|
||||
legacy_outbox_id="$(jq -er '.data.outboxId' "$legacy_body")"
|
||||
legacy_state="$(query_outbox_state "$legacy_outbox_id")"
|
||||
jq -e '.eventType == "erp.journal.export" and .status == "pending"' <<<"$legacy_state" >/dev/null
|
||||
|
||||
echo "[9/9] ERP env gate off blocks sync"
|
||||
if kill -0 "$APP_SERVER_PID" >/dev/null 2>&1; then
|
||||
kill "$APP_SERVER_PID" >/dev/null 2>&1 || true
|
||||
wait "$APP_SERVER_PID" >/dev/null 2>&1 || true
|
||||
fi
|
||||
APP_SERVER_PID=""
|
||||
PORT="$APP_PORT" \
|
||||
HOST="127.0.0.1" \
|
||||
JOBS_ENABLED=false \
|
||||
OCR_PROVIDER=mock \
|
||||
ERP_SYNC_ENABLED=false \
|
||||
ERP_SYNC_PROVIDER=http \
|
||||
ERP_MASTER_DATA_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/master-data/pull?mode=success" \
|
||||
ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/reimbursements/paid?mode=success" \
|
||||
ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
|
||||
ERP_MASTER_DATA_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
|
||||
ERP_SYNC_AUTH_TOKEN="" \
|
||||
node src/index.js >"$TMP_DIR/app-gate-off.log" 2>&1 &
|
||||
APP_SERVER_PID="$!"
|
||||
for _ in $(seq 1 60); do
|
||||
if curl -sS "$BASE_URL/health" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
login_finance_mgr
|
||||
blocked_body="$TMP_DIR/blocked.json"
|
||||
blocked_code="$(api_post '/api/integrations/erp/master-data/sync' '{"resources":["legal_entity"]}' "$blocked_body")"
|
||||
assert_status "$blocked_code" "409" "erp gate off blocked"
|
||||
jq -e '.error.code == "VALID_001" and (.error.details.integration == "erp_sync_disabled" or .error.details.reason == "env_hard_off")' "$blocked_body" >/dev/null
|
||||
|
||||
echo "[6/6] Done"
|
||||
echo "[OK] Integrations regression passed"
|
||||
|
||||
echo "[post] Reset ERP feature flag force_off"
|
||||
set_erp_flag "force_off"
|
||||
|
||||
在新工单中引用
屏蔽一个用户