#!/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))}" APP_PORT="${APP_PORT:-$((4300 + RANDOM % 500))}" BASE_URL="http://127.0.0.1:${APP_PORT}" DEVICE_FINGERPRINT="${DEVICE_FINGERPRINT:-regression-integrations}" EMPLOYEE_IDENTIFIER="${EMPLOYEE_IDENTIFIER:-employee@hyinda.com}" EMPLOYEE_PASSWORD="${EMPLOYEE_PASSWORD:-EmployeePassword1234}" MANAGER_IDENTIFIER="${MANAGER_IDENTIFIER:-manager@hyinda.com}" MANAGER_PASSWORD="${MANAGER_PASSWORD:-ManagerPassword1234}" 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 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" # shellcheck source=scripts/lib/load-env-defaults.sh source "$ROOT_DIR/scripts/lib/load-env-defaults.sh" load_env_defaults ".env" 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)" 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 fi rm -rf "$TMP_DIR" } 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 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.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/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/export' || 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); } 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()}`, externalCode: `ERP-TIMEOUT-${Date.now()}`, reimbursementId: parsedBody?.reimbursementId || parsedBody?.entityId || 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', }); } const documentNo = parsedBody?.documentNo || parsedBody?.formNumber || parsedBody?.entityId || Date.now(); return sendJson(res, 200, { ok: true, scenario: 'success', externalId: `ERP-${documentNo}`, externalCode: `ERP-${documentNo}`, reimbursementId: parsedBody?.reimbursementId || parsedBody?.entityId || null, }); } if (req.method === 'POST' && url.pathname === '/erp/procurement/export') { 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, externalPoId: `ERP-PO-${Date.now()}`, externalPoNo: `ERP-PO-${parsedBody?.poNo || Date.now()}`, }); }, 1500); return; } if (mode === 'client') { return sendJson(res, 422, { ok: false, code: 'invalid_payload', message: 'mock procurement client error', }); } if (mode === 'server') { return sendJson(res, 503, { ok: false, code: 'service_unavailable', message: 'mock procurement server error', }); } return sendJson(res, 200, { ok: true, externalId: `ERP-PROC-${parsedBody?.poNo || parsedBody?.entityId || Date.now()}`, externalCode: `ERP-PROC-${parsedBody?.poNo || parsedBody?.entityId || Date.now()}`, externalPoId: parsedBody?.poNo ? `ERP-PO-${parsedBody.poNo}` : null, externalPoNo: parsedBody?.poNo ? `ERP-PO-${parsedBody.poNo}` : null, externalContractId: parsedBody?.contractNo ? `ERP-CT-${parsedBody.contractNo}` : null, externalContractNo: parsedBody?.contractNo ? `ERP-CT-${parsedBody.contractNo}` : null, }); } if (req.method === 'POST' && url.pathname === '/erp/assets/export') { 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, externalAssetId: `ERP-ASSET-${Date.now()}`, externalAssetNo: `ERP-ASSET-${parsedBody?.assetNo || Date.now()}`, }); }, 1500); return; } if (mode === 'client') { return sendJson(res, 422, { ok: false, code: 'invalid_payload', message: 'mock asset client error', }); } if (mode === 'server') { return sendJson(res, 503, { ok: false, code: 'service_unavailable', message: 'mock asset server error', }); } return sendJson(res, 200, { ok: true, externalAssetId: `ERP-ASSET-${parsedBody?.assetNo || parsedBody?.entityId || Date.now()}`, externalAssetNo: `ERP-ASSET-${parsedBody?.assetNo || parsedBody?.entityId || Date.now()}`, }); } sendJson(res, 404, { ok: false, message: 'not_found' }); }); server.listen(port, '127.0.0.1', () => { process.stdout.write(`mock-erp-listening:${port}\n`); }); NODE 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 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 } 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_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/export?mode=success" \ ERP_PROCUREMENT_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/procurement/export?mode=success" \ ERP_ASSET_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/assets/export?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_PROCUREMENT_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \ ERP_ASSET_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.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_user() { local identifier="$1" local password="$2" local suffix="$3" local out_file="$TMP_DIR/login-${suffix}.json" local login_status login_status="$( curl -sS -o "$out_file" -w "%{http_code}" \ -X POST "$BASE_URL/api/auth/login" \ -H "content-type: application/json" \ -H "x-device-fingerprint: ${DEVICE_FINGERPRINT}-${suffix}" \ -d "$(jq -nc --arg identifier "$identifier" --arg password "$password" '{identifier: $identifier, password: $password}')" )" assert_status "$login_status" "200" "login ${identifier}" "$out_file" jq -er '.data.accessToken' "$out_file" } login_finance_mgr() { TOKEN="$(login_user "$FINANCE_MGR_IDENTIFIER" "$FINANCE_MGR_PASSWORD" finance)" } api_json_auth() { local method="$1" local path="$2" local token="$3" local out_file="$4" local body="${5:-}" if [[ -n "$body" ]]; then curl -sS -o "$out_file" -w "%{http_code}" \ -X "$method" "$BASE_URL$path" \ -H "authorization: Bearer $token" \ -H "content-type: application/json" \ -d "$body" else curl -sS -o "$out_file" -w "%{http_code}" \ -X "$method" "$BASE_URL$path" \ -H "authorization: Bearer $token" fi } set_erp_flag() { local mode="$1" DATABASE_URL="$DATABASE_URL" MODE="$mode" node <<'NODE' 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' }, create: { flag_key: 'erp_sync', override_mode: mode, rollout_type: 'global', department_ids: [], note: 'regression-integrations', }, update: { override_mode: mode, rollout_type: 'global', department_ids: [], note: 'regression-integrations', version: { increment: 1 }, }, }); } finally { await prisma.$disconnect(); await pool.end(); } })().catch((error) => { console.error(error); process.exit(1); }); NODE } reset_erp_integration_state() { DATABASE_URL="$DATABASE_URL" node <<'NODE' require('dotenv/config'); const { createPrismaClient } = require('./src/prismaClient'); (async () => { const { prisma, pool } = createPrismaClient(); await prisma.$connect(); try { await prisma.integrationOutbox.deleteMany({ where: { event_type: { in: ['erp.reimbursement.paid', 'erp.journal.export', 'erp.procurement.export', 'erp.asset.export'], }, }, }); await prisma.integrationBinding.deleteMany({ where: { provider: 'erp' }, }); await prisma.integrationSyncState.deleteMany({ where: { provider: 'erp' }, }); } finally { await prisma.$disconnect(); await pool.end(); } })().catch((error) => { console.error(error); process.exit(1); }); NODE } create_paid_reimbursement() { DATABASE_URL="$DATABASE_URL" RUN_SUFFIX="$RUN_SUFFIX" node <<'NODE' require('dotenv/config'); 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: ['employee@hyinda.com', 'finance_mgr@hyinda.com'], }, }, 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 } resolve_procurement_fixture_ids() { DATABASE_URL="$DATABASE_URL" node - <<'NODE' require('dotenv/config'); const { createPrismaClient } = require('./src/prismaClient'); const { resolveApplicableBudgetPoolByContext } = require('./src/services/budgetPool'); (async () => { const { prisma, pool } = createPrismaClient(); await prisma.$connect(); try { const employee = await prisma.employee.findUnique({ where: { email: process.env.SEED_EMPLOYEE_EMAIL ?? 'employee@hyinda.com' }, select: { department_id: true, legal_entity_id: true }, }); const costCenter = await prisma.costCenter.findFirst({ where: { enabled: true, archived_at: null, legal_entity_id: employee.legal_entity_id, }, orderBy: { created_at: 'asc' }, select: { id: true }, }); const supplier = await prisma.supplier.findFirst({ where: { enabled: true, archived_at: null, OR: [{ legal_entity_id: employee.legal_entity_id }, { legal_entity_id: null }], }, orderBy: { created_at: 'asc' }, select: { id: true }, }); const documentCategory = await prisma.documentCategory.findFirst({ where: { enabled: true, archived_at: null, entity_type: 'purchase_request', }, orderBy: { created_at: 'asc' }, select: { id: true }, }); const budgetPool = await resolveApplicableBudgetPoolByContext(prisma, { departmentId: employee.department_id, legalEntityId: employee.legal_entity_id, costCenterId: costCenter?.id ?? null, effectiveDate: new Date(), }); process.stdout.write( [ employee.legal_entity_id, costCenter?.id ?? '', supplier?.id ?? '', documentCategory?.id ?? '', budgetPool?.id ?? '', ].join('\n'), ); } finally { await prisma.$disconnect(); await pool.end(); } })().catch((error) => { console.error(error); process.exit(1); }); NODE } query_outbox_by_key() { local event_type="$1" local dedupe_key="$2" DATABASE_URL="$DATABASE_URL" EVENT_TYPE="$event_type" DEDUPE_KEY="$dedupe_key" node <<'NODE' require('dotenv/config'); const { createPrismaClient } = require('./src/prismaClient'); (async () => { const { prisma, pool } = createPrismaClient(); await prisma.$connect(); try { const row = await prisma.integrationOutbox.findUnique({ where: { event_type_dedupe_key: { event_type: process.env.EVENT_TYPE, dedupe_key: process.env.DEDUPE_KEY, }, }, select: { id: true, event_type: true, status: true, attempts: true, processed_at: true, next_retry_at: true, dead_letter_at: true, last_error: true, payload: true, }, }); process.stdout.write(JSON.stringify(row ? { id: row.id, eventType: row.event_type, status: row.status, attempts: row.attempts, processedAt: row.processed_at ? row.processed_at.toISOString() : null, 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, payload: row.payload, } : null)); } finally { await prisma.$disconnect(); await pool.end(); } })().catch((error) => { console.error(error); process.exit(1); }); NODE } query_binding_by_key() { local entity_type="$1" local local_id="$2" DATABASE_URL="$DATABASE_URL" ENTITY_TYPE="$entity_type" LOCAL_ID="$local_id" node <<'NODE' require('dotenv/config'); const { createPrismaClient } = require('./src/prismaClient'); (async () => { const { prisma, pool } = createPrismaClient(); await prisma.$connect(); try { const row = await prisma.integrationBinding.findUnique({ where: { provider_entity_type_local_id: { provider: 'erp', entity_type: process.env.ENTITY_TYPE, local_id: process.env.LOCAL_ID, }, }, 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_outbox_absent_by_key() { local event_type="$1" local dedupe_key="$2" local state_json state_json="$(query_outbox_by_key "$event_type" "$dedupe_key")" jq -e '. == null' <<<"$state_json" >/dev/null } 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 journal_mode="$1" local procurement_mode="${2:-$journal_mode}" local asset_mode="${3:-$journal_mode}" 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/export?mode=$journal_mode" ERP_PROCUREMENT_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/procurement/export?mode=$procurement_mode" ERP_ASSET_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/assets/export?mode=$asset_mode" ERP_SYNC_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/reimbursements/paid?mode=$journal_mode" ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" ERP_PROCUREMENT_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" ERP_ASSET_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" } create_and_approve_purchase() { local employee_token="$1" local manager_token="$2" local title_suffix="$3" local tmp_prefix="$4" local create_status create_status="$(api_json_auth POST "/api/purchase-requests" "$employee_token" "$TMP_DIR/${tmp_prefix}-create.json" '{}')" assert_status "$create_status" "200" "create purchase ${title_suffix}" "$TMP_DIR/${tmp_prefix}-create.json" local purchase_id purchase_id="$(jq -er '.data.purchaseRequest.id' "$TMP_DIR/${tmp_prefix}-create.json")" local patch_body patch_body="$({ jq -nc \ --arg title "$title_suffix" \ --arg le "$LEGAL_ENTITY_ID" \ --arg cc "$COST_CENTER_ID" \ --arg sp "$SUPPLIER_ID" \ --arg dc "$DOCUMENT_CATEGORY_ID" \ '{title:$title, legalEntityId:$le, costCenterId:$cc, supplierId:$sp, documentCategoryId:$dc, items:[{description:"Laptop", specification:"14 inch", quantity:"2.00", unitPrice:"440.00", isAssetCandidate:true}] }' })" local patch_status patch_status="$(api_json_auth PATCH "/api/purchase-requests/$purchase_id" "$employee_token" "$TMP_DIR/${tmp_prefix}-patch.json" "$patch_body")" assert_status "$patch_status" "200" "patch purchase ${title_suffix}" "$TMP_DIR/${tmp_prefix}-patch.json" local submit_status submit_status="$(api_json_auth POST "/api/purchase-requests/$purchase_id/submit" "$employee_token" "$TMP_DIR/${tmp_prefix}-submit.json" '{}')" assert_status "$submit_status" "200" "submit purchase ${title_suffix}" "$TMP_DIR/${tmp_prefix}-submit.json" local task_id task_id="$(jq -er '.data.currentTaskId' "$TMP_DIR/${tmp_prefix}-submit.json")" local approve_status approve_status="$(api_json_auth POST "/api/workflow/tasks/$task_id/approve" "$manager_token" "$TMP_DIR/${tmp_prefix}-approve.json" '{"comment":"approve procurement erp regression"}')" assert_status "$approve_status" "200" "approve purchase ${title_suffix}" "$TMP_DIR/${tmp_prefix}-approve.json" jq -e '.data.outcome == "approved" and .data.purchaseRequestStatus == "approved"' "$TMP_DIR/${tmp_prefix}-approve.json" >/dev/null printf '%s\n%s' "$purchase_id" "$task_id" } archive_purchase_order() { local finance_token="$1" local purchase_id="$2" local po_no="$3" local contract_no="$4" local tmp_prefix="$5" local archive_status archive_status="$(api_json_auth POST "/api/purchase-requests/$purchase_id/archive-order" "$finance_token" "$TMP_DIR/${tmp_prefix}-archive.json" "$(jq -nc --arg po "$po_no" --arg contract "$contract_no" '{poNo:$po, contractNo:$contract, archivedFiles:[]}')")" assert_status "$archive_status" "200" "archive purchase ${purchase_id}" "$TMP_DIR/${tmp_prefix}-archive.json" jq -e --arg po "$po_no" --arg contract "$contract_no" '.data.archiveOrder.poNo == $po and .data.archiveOrder.contractNo == $contract' "$TMP_DIR/${tmp_prefix}-archive.json" >/dev/null jq -er '.data.archiveOrder.id' "$TMP_DIR/${tmp_prefix}-archive.json" } resolve_asset_fixture_ids() { DATABASE_URL="$DATABASE_URL" LEGAL_ENTITY_CODE="$LEGAL_ENTITY_CODE" COST_CENTER_CODE="$COST_CENTER_CODE" node - <<'NODE' require('dotenv/config'); const { createPrismaClient } = require('./src/prismaClient'); (async () => { const { prisma, pool } = createPrismaClient(); await prisma.$connect(); try { const employee = await prisma.employee.findUnique({ where: { email: process.env.SEED_EMPLOYEE_EMAIL ?? 'employee@hyinda.com' }, select: { id: true, legal_entity_id: true }, }); const primaryCostCenter = await prisma.costCenter.findFirst({ where: { enabled: true, archived_at: null, legal_entity_id: employee.legal_entity_id, }, orderBy: { created_at: 'asc' }, select: { id: true }, }); const syncedLegalEntity = await prisma.legalEntity.findUnique({ where: { code: process.env.LEGAL_ENTITY_CODE }, select: { id: true }, }); const syncedCostCenter = await prisma.costCenter.findFirst({ where: { code: process.env.COST_CENTER_CODE, legal_entity_id: syncedLegalEntity?.id ?? undefined, }, select: { id: true }, }); process.stdout.write([ employee.id, employee.legal_entity_id, primaryCostCenter?.id ?? '', syncedLegalEntity?.id ?? '', syncedCostCenter?.id ?? '', ].join('\n')); } finally { await prisma.$disconnect(); await pool.end(); } })().catch((error) => { console.error(error); process.exit(1); }); NODE } create_asset_category() { local token="$1" local tmp_prefix="$2" local category_code="AST-${RUN_SUFFIX_NUMERIC:0:8}-${tmp_prefix}" local status status="$(api_json_auth POST "/api/asset-categories" "$token" "$TMP_DIR/${tmp_prefix}-asset-category.json" "$(jq -nc --arg code "$category_code" --arg name "资产分类-${tmp_prefix}" '{code:$code, name:$name, enabled:true}')")" assert_status "$status" "200" "create asset category ${tmp_prefix}" "$TMP_DIR/${tmp_prefix}-asset-category.json" jq -er '.data.assetCategory.id' "$TMP_DIR/${tmp_prefix}-asset-category.json" } create_asset_card() { local token="$1" local category_id="$2" local legal_entity_id="$3" local cost_center_id="$4" local assignee_employee_id="$5" local tmp_prefix="$6" local body body="$(jq -nc \ --arg name "资产ERP-${tmp_prefix}" \ --arg categoryId "$category_id" \ --arg legalEntityId "$legal_entity_id" \ --arg costCenterId "$cost_center_id" \ --arg assigneeEmployeeId "$assignee_employee_id" \ --arg location "上海办公室-A区-${tmp_prefix}" \ '{name:$name, categoryId:$categoryId, legalEntityId:$legalEntityId, costCenterId:$costCenterId, assigneeEmployeeId:($assigneeEmployeeId|select(length>0)), location:$location, activatedAt:"2026-03-09"}')" local status status="$(api_json_auth POST "/api/assets" "$token" "$TMP_DIR/${tmp_prefix}-asset-create.json" "$body")" assert_status "$status" "200" "create asset ${tmp_prefix}" "$TMP_DIR/${tmp_prefix}-asset-create.json" jq -er '.data.asset.id' "$TMP_DIR/${tmp_prefix}-asset-create.json" } assert_export_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_export_mode_case() { local mode="$1" local reimbursement_id reimbursement_id="$(create_paid_reimbursement)" 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 '.data.outboxId' "$export_body")" local state_json="" local status="" for _ in $(seq 1 8); do run_outbox_once "$mode" 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] export mode=$mode did not finish processing" >&2 echo "$state_json" >&2 exit 1 fi 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] export mode=$mode outbox_status=$status" >&2 printf '%s' "$reimbursement_id" } echo "[0/9] Ensure ERP feature flag force_on" set_erp_flag "force_on" echo "[0.5/9] Reset ERP integration artifacts" reset_erp_integration_state echo "[1/9] Start embedded mock ERP server" start_mock_erp_server echo "[2/9] Start isolated app server" start_app_server sleep 1 echo "[3/9] Login finance manager" login_finance_mgr 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/13] Procurement approval/archive auto export + bindings" EMPLOYEE_TOKEN="$(login_user "$EMPLOYEE_IDENTIFIER" "$EMPLOYEE_PASSWORD" employee)" MANAGER_TOKEN="$(login_user "$MANAGER_IDENTIFIER" "$MANAGER_PASSWORD" manager)" FINANCE_MGR_TOKEN="$TOKEN" mapfile -t FIXTURE_IDS < <(resolve_procurement_fixture_ids) LEGAL_ENTITY_ID="${FIXTURE_IDS[0]}" COST_CENTER_ID="${FIXTURE_IDS[1]}" SUPPLIER_ID="${FIXTURE_IDS[2]}" DOCUMENT_CATEGORY_ID="${FIXTURE_IDS[3]}" BUDGET_POOL_ID="${FIXTURE_IDS[4]}" PROC_SUCCESS_PO="PO-P19ERP2-${RUN_SUFFIX_NUMERIC}-001" PROC_SUCCESS_CONTRACT_1="CT-P19ERP2-${RUN_SUFFIX_NUMERIC}-001" PROC_SUCCESS_CONTRACT_2="CT-P19ERP2-${RUN_SUFFIX_NUMERIC}-002" PROC_SUCCESS_CONTRACT_3="CT-P19ERP2-${RUN_SUFFIX_NUMERIC}-003" PROC_SKIPPED_PO="PO-P19ERP2-${RUN_SUFFIX_NUMERIC}-101" PROC_SKIPPED_CONTRACT="CT-P19ERP2-${RUN_SUFFIX_NUMERIC}-101" mapfile -t PROCUREMENT_APPROVED < <(create_and_approve_purchase "$EMPLOYEE_TOKEN" "$MANAGER_TOKEN" "procurement erp success" "proc-success") PURCHASE_ID_APPROVED="${PROCUREMENT_APPROVED[0]}" COMMITMENT_DEDUPE="purchase_request:${PURCHASE_ID_APPROVED}:commitment" commitment_state="$(query_outbox_by_key 'erp.journal.export' "$COMMITMENT_DEDUPE")" jq -e '.status == "pending" and .payload.journalType == "purchase_request_commitment"' <<<"$commitment_state" >/dev/null run_outbox_once success success commitment_state_done="$(query_outbox_by_key 'erp.journal.export' "$COMMITMENT_DEDUPE")" jq -e '.status == "succeeded"' <<<"$commitment_state_done" >/dev/null commitment_binding="$(query_binding_by_key 'purchase_request_commitment_journal' "$PURCHASE_ID_APPROVED")" jq -e '.externalCode != null' <<<"$commitment_binding" >/dev/null ARCHIVE_ID_APPROVED="$(archive_purchase_order "$FINANCE_MGR_TOKEN" "$PURCHASE_ID_APPROVED" "$PROC_SUCCESS_PO" "$PROC_SUCCESS_CONTRACT_1" 'proc-success')" ACCRUAL_DEDUPE="purchase_order_archive:${ARCHIVE_ID_APPROVED}:accrual" SUMMARY_DEDUPE="purchase_order_archive:${ARCHIVE_ID_APPROVED}:summary" accrual_state="$(query_outbox_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE")" summary_state="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")" jq -e '.status == "pending" and .payload.journalType == "purchase_order_accrual"' <<<"$accrual_state" >/dev/null jq -e '.status == "pending" and .payload.exportType == "purchase_order_archive"' <<<"$summary_state" >/dev/null run_outbox_once success success accrual_state_done="$(query_outbox_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE")" summary_state_done="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")" jq -e '.status == "succeeded"' <<<"$accrual_state_done" >/dev/null jq -e '.status == "succeeded"' <<<"$summary_state_done" >/dev/null accrual_binding="$(query_binding_by_key 'purchase_order_accrual_journal' "$ARCHIVE_ID_APPROVED")" po_binding="$(query_binding_by_key 'purchase_order_po' "$ARCHIVE_ID_APPROVED")" contract_binding="$(query_binding_by_key 'purchase_order_contract' "$ARCHIVE_ID_APPROVED")" jq -e '.externalCode != null' <<<"$accrual_binding" >/dev/null jq -e '.externalCode != null' <<<"$po_binding" >/dev/null jq -e '.externalCode != null' <<<"$contract_binding" >/dev/null echo "[10/13] Archive update only resets summary" ARCHIVE_UPDATE_STATUS="$(api_json_auth POST "/api/purchase-requests/$PURCHASE_ID_APPROVED/archive-order" "$FINANCE_MGR_TOKEN" "$TMP_DIR/proc-success-archive-update.json" "$(jq -nc --arg po "$PROC_SUCCESS_PO" --arg contract "$PROC_SUCCESS_CONTRACT_2" '{poNo:$po, contractNo:$contract, archivedFiles:[]}')")" assert_status "$ARCHIVE_UPDATE_STATUS" "200" "archive update" "$TMP_DIR/proc-success-archive-update.json" accrual_state_after_update="$(query_outbox_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE")" summary_state_after_update="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")" ACCRUAL_OUTBOX_ID="$(jq -er '.id' <<<"$accrual_state_done")" SUMMARY_OUTBOX_ID="$(jq -er '.id' <<<"$summary_state_done")" jq -e --arg id "$ACCRUAL_OUTBOX_ID" '.id == $id and .status == "succeeded"' <<<"$accrual_state_after_update" >/dev/null jq -e --arg id "$SUMMARY_OUTBOX_ID" --arg contract "$PROC_SUCCESS_CONTRACT_2" '.id == $id and .status == "pending" and .payload.contractNo == $contract' <<<"$summary_state_after_update" >/dev/null run_outbox_once success success contract_binding_updated="$(query_binding_by_key 'purchase_order_contract' "$ARCHIVE_ID_APPROVED")" jq -e '.externalCode != null' <<<"$contract_binding_updated" >/dev/null echo "[11/13] Force-off skips auto export and manual requeue backfills historical单据" set_erp_flag "force_off" mapfile -t PROCUREMENT_SKIPPED < <(create_and_approve_purchase "$EMPLOYEE_TOKEN" "$MANAGER_TOKEN" "procurement erp skipped" "proc-skipped") PURCHASE_ID_SKIPPED="${PROCUREMENT_SKIPPED[0]}" COMMITMENT_DEDUPE_SKIPPED="purchase_request:${PURCHASE_ID_SKIPPED}:commitment" assert_outbox_absent_by_key 'erp.journal.export' "$COMMITMENT_DEDUPE_SKIPPED" ARCHIVE_ID_SKIPPED="$(archive_purchase_order "$FINANCE_MGR_TOKEN" "$PURCHASE_ID_SKIPPED" "$PROC_SKIPPED_PO" "$PROC_SKIPPED_CONTRACT" 'proc-skipped')" ACCRUAL_DEDUPE_SKIPPED="purchase_order_archive:${ARCHIVE_ID_SKIPPED}:accrual" SUMMARY_DEDUPE_SKIPPED="purchase_order_archive:${ARCHIVE_ID_SKIPPED}:summary" assert_outbox_absent_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE_SKIPPED" assert_outbox_absent_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE_SKIPPED" set_erp_flag "force_on" PROC_REQUEUE_CODE="$(api_json_auth POST "/api/integrations/erp/procurement/purchase-requests/$PURCHASE_ID_SKIPPED/requeue?runNow=0" "$FINANCE_MGR_TOKEN" "$TMP_DIR/proc-requeue.json" '{"targets":["commitment_journal","accrual_journal","archive_summary"]}')" assert_status "$PROC_REQUEUE_CODE" "200" "procurement requeue" "$TMP_DIR/proc-requeue.json" jq -e '.data.items | length == 3' "$TMP_DIR/proc-requeue.json" >/dev/null run_outbox_once success success jq -e '.status == "succeeded"' <<<"$(query_outbox_by_key 'erp.journal.export' "$COMMITMENT_DEDUPE_SKIPPED")" >/dev/null jq -e '.status == "succeeded"' <<<"$(query_outbox_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE_SKIPPED")" >/dev/null jq -e '.status == "succeeded"' <<<"$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE_SKIPPED")" >/dev/null echo "[12/13] Archive summary dead-letter can requeue same outbox" PROC_SUMMARY_FAIL_STATUS="$(api_json_auth POST "/api/purchase-requests/$PURCHASE_ID_APPROVED/archive-order" "$FINANCE_MGR_TOKEN" "$TMP_DIR/proc-summary-fail-archive.json" "$(jq -nc --arg po "$PROC_SUCCESS_PO" --arg contract "$PROC_SUCCESS_CONTRACT_3" '{poNo:$po, contractNo:$contract, archivedFiles:[]}')")" assert_status "$PROC_SUMMARY_FAIL_STATUS" "200" "archive update for summary failure" "$TMP_DIR/proc-summary-fail-archive.json" run_outbox_once success client summary_dead_state="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")" jq -e '.status == "dead_letter" and .attempts == 1' <<<"$summary_dead_state" >/dev/null SUMMARY_DEAD_ID="$(jq -er '.id' <<<"$summary_dead_state")" PROC_SUMMARY_REQUEUE_CODE="$(api_json_auth POST "/api/integrations/erp/procurement/purchase-requests/$PURCHASE_ID_APPROVED/requeue?runNow=0" "$FINANCE_MGR_TOKEN" "$TMP_DIR/proc-summary-requeue.json" '{"targets":["archive_summary"]}')" assert_status "$PROC_SUMMARY_REQUEUE_CODE" "200" "procurement summary requeue" "$TMP_DIR/proc-summary-requeue.json" jq -e --arg id "$SUMMARY_DEAD_ID" '.data.items[0].outboxId == $id and .data.items[0].requeued == true' "$TMP_DIR/proc-summary-requeue.json" >/dev/null run_outbox_once success success summary_requeue_state="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")" jq -e --arg id "$SUMMARY_DEAD_ID" '.id == $id and .status == "succeeded"' <<<"$summary_requeue_state" >/dev/null echo "[13/18] Asset ledger summary auto export + binding" mapfile -t ASSET_FIXTURE_IDS < <(resolve_asset_fixture_ids) ASSET_ASSIGNEE_ID="${ASSET_FIXTURE_IDS[0]}" ASSET_BASE_LEGAL_ENTITY_ID="${ASSET_FIXTURE_IDS[1]}" ASSET_BASE_COST_CENTER_ID="${ASSET_FIXTURE_IDS[2]}" ASSET_SYNCED_LEGAL_ENTITY_ID="${ASSET_FIXTURE_IDS[3]}" ASSET_SYNCED_COST_CENTER_ID="${ASSET_FIXTURE_IDS[4]}" ASSET_CATEGORY_ID="$(create_asset_category "$FINANCE_MGR_TOKEN" 'asset-success')" ASSET_ID_APPROVED="$(create_asset_card "$FINANCE_MGR_TOKEN" "$ASSET_CATEGORY_ID" "$ASSET_BASE_LEGAL_ENTITY_ID" "$ASSET_BASE_COST_CENTER_ID" "$ASSET_ASSIGNEE_ID" 'asset-success')" ASSET_DEDUPE="asset_card:${ASSET_ID_APPROVED}:ledger_summary" asset_state_created="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE")" jq -e '.status == "pending" and .payload.exportType == "asset_ledger_summary" and .payload.changeType == "created"' <<<"$asset_state_created" >/dev/null run_outbox_once success success success asset_state_done="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE")" jq -e '.status == "succeeded"' <<<"$asset_state_done" >/dev/null asset_binding="$(query_binding_by_key 'asset_erp_card' "$ASSET_ID_APPROVED")" jq -e '.externalCode != null and .lastSyncedAt != null' <<<"$asset_binding" >/dev/null ASSET_OUTBOX_ID="$(jq -er '.id' <<<"$asset_state_done")" ASSET_TRACK_EMPLOYEE_CODE="$(api_json_auth GET "/api/integrations/erp/assets/$ASSET_ID_APPROVED/track" "$EMPLOYEE_TOKEN" "$TMP_DIR/asset-track-employee.json")" assert_status "$ASSET_TRACK_EMPLOYEE_CODE" "200" "employee asset erp track" "$TMP_DIR/asset-track-employee.json" jq -e '.data.stage.deliveryStatus == "succeeded" and .data.stage.binding.externalCode == null and .data.permissions.canRetry == false' "$TMP_DIR/asset-track-employee.json" >/dev/null ASSET_REQUEUE_FORBIDDEN_CODE="$(api_json_auth POST "/api/integrations/erp/assets/$ASSET_ID_APPROVED/requeue?runNow=0" "$EMPLOYEE_TOKEN" "$TMP_DIR/asset-requeue-forbidden.json" '{}')" assert_status "$ASSET_REQUEUE_FORBIDDEN_CODE" "403" "asset requeue forbidden" "$TMP_DIR/asset-requeue-forbidden.json" echo "[14/18] Non-financial patch does not reset asset outbox" ASSET_PATCH_NON_FIN_CODE="$(api_json_auth PATCH "/api/assets/$ASSET_ID_APPROVED" "$FINANCE_MGR_TOKEN" "$TMP_DIR/asset-non-financial.json" '{"name":"资产ERP-asset-success-v2","location":"上海办公室-B区"}')" assert_status "$ASSET_PATCH_NON_FIN_CODE" "200" "asset non financial patch" "$TMP_DIR/asset-non-financial.json" asset_state_after_non_fin="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE")" jq -e --arg id "$ASSET_OUTBOX_ID" '.id == $id and .status == "succeeded"' <<<"$asset_state_after_non_fin" >/dev/null echo "[15/18] Financial patch resets same asset outbox" ASSET_PATCH_FIN_CODE="$(api_json_auth PATCH "/api/assets/$ASSET_ID_APPROVED" "$FINANCE_MGR_TOKEN" "$TMP_DIR/asset-financial.json" "$(jq -nc --arg le "$ASSET_SYNCED_LEGAL_ENTITY_ID" --arg cc "$ASSET_SYNCED_COST_CENTER_ID" '{legalEntityId:$le, costCenterId:$cc}')")" assert_status "$ASSET_PATCH_FIN_CODE" "200" "asset financial patch" "$TMP_DIR/asset-financial.json" asset_state_after_fin="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE")" jq -e --arg id "$ASSET_OUTBOX_ID" --arg le "$ASSET_SYNCED_LEGAL_ENTITY_ID" --arg cc "$ASSET_SYNCED_COST_CENTER_ID" '.id == $id and .status == "pending" and .payload.changeType == "financial_dimensions_changed" and .payload.legalEntity.id == $le and .payload.costCenter.id == $cc' <<<"$asset_state_after_fin" >/dev/null run_outbox_once success success success asset_state_after_fin_done="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE")" jq -e '.status == "succeeded"' <<<"$asset_state_after_fin_done" >/dev/null echo "[16/18] Retired asset dead-letter can requeue same outbox" ASSET_PATCH_RETIRED_CODE="$(api_json_auth PATCH "/api/assets/$ASSET_ID_APPROVED" "$FINANCE_MGR_TOKEN" "$TMP_DIR/asset-retired.json" '{"status":"retired","retiredAt":"2026-03-09"}')" assert_status "$ASSET_PATCH_RETIRED_CODE" "200" "asset retired patch" "$TMP_DIR/asset-retired.json" asset_state_retired_pending="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE")" jq -e --arg id "$ASSET_OUTBOX_ID" '.id == $id and .status == "pending" and .payload.changeType == "retired"' <<<"$asset_state_retired_pending" >/dev/null run_outbox_once success success client asset_state_dead="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE")" jq -e '.status == "dead_letter" and .attempts == 1 and (.lastError | tostring | test("erp_asset_http_4xx|422"))' <<<"$asset_state_dead" >/dev/null ASSET_DEAD_OUTBOX_ID="$(jq -er '.id' <<<"$asset_state_dead")" ASSET_REQUEUE_CODE="$(api_json_auth POST "/api/integrations/erp/assets/$ASSET_ID_APPROVED/requeue?runNow=0" "$FINANCE_MGR_TOKEN" "$TMP_DIR/asset-requeue.json" '{}')" assert_status "$ASSET_REQUEUE_CODE" "200" "asset requeue" "$TMP_DIR/asset-requeue.json" jq -e --arg id "$ASSET_DEAD_OUTBOX_ID" '.data.outboxId == $id and .data.requeued == true' "$TMP_DIR/asset-requeue.json" >/dev/null run_outbox_once success success success asset_state_requeued_done="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE")" jq -e --arg id "$ASSET_DEAD_OUTBOX_ID" '.id == $id and .status == "succeeded"' <<<"$asset_state_requeued_done" >/dev/null echo "[17/18] Force-off skips asset auto export and manual requeue backfills historical资产" set_erp_flag "force_off" ASSET_CATEGORY_SKIPPED_ID="$(create_asset_category "$FINANCE_MGR_TOKEN" 'asset-skipped')" ASSET_ID_SKIPPED="$(create_asset_card "$FINANCE_MGR_TOKEN" "$ASSET_CATEGORY_SKIPPED_ID" "$ASSET_BASE_LEGAL_ENTITY_ID" "$ASSET_BASE_COST_CENTER_ID" "$ASSET_ASSIGNEE_ID" 'asset-skipped')" ASSET_DEDUPE_SKIPPED="asset_card:${ASSET_ID_SKIPPED}:ledger_summary" assert_outbox_absent_by_key 'erp.asset.export' "$ASSET_DEDUPE_SKIPPED" ASSET_PATCH_SKIPPED_CODE="$(api_json_auth PATCH "/api/assets/$ASSET_ID_SKIPPED" "$FINANCE_MGR_TOKEN" "$TMP_DIR/asset-skipped-patch.json" "$(jq -nc --arg le "$ASSET_SYNCED_LEGAL_ENTITY_ID" --arg cc "$ASSET_SYNCED_COST_CENTER_ID" '{legalEntityId:$le, costCenterId:$cc}')")" assert_status "$ASSET_PATCH_SKIPPED_CODE" "200" "asset skipped patch" "$TMP_DIR/asset-skipped-patch.json" assert_outbox_absent_by_key 'erp.asset.export' "$ASSET_DEDUPE_SKIPPED" set_erp_flag "force_on" ASSET_BACKFILL_CODE="$(api_json_auth POST "/api/integrations/erp/assets/$ASSET_ID_SKIPPED/requeue?runNow=0" "$FINANCE_MGR_TOKEN" "$TMP_DIR/asset-backfill.json" '{}')" assert_status "$ASSET_BACKFILL_CODE" "200" "asset backfill" "$TMP_DIR/asset-backfill.json" jq -e '.data.duplicated == false and .data.status == "pending"' "$TMP_DIR/asset-backfill.json" >/dev/null run_outbox_once success success success asset_backfill_state="$(query_outbox_by_key 'erp.asset.export' "$ASSET_DEDUPE_SKIPPED")" jq -e '.status == "succeeded"' <<<"$asset_backfill_state" >/dev/null echo "[18/18] 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/export?mode=success" \ ERP_PROCUREMENT_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/procurement/export?mode=success" \ ERP_ASSET_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/assets/export?mode=success" \ ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \ ERP_PROCUREMENT_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \ ERP_ASSET_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 "[OK] Integrations regression passed"