Files
order_site/apps/backend/src/services/finance/finance-reconciliation-service.ts
T
yml2213 62763ddf0c feat(finance): 支持代录指定客服账户,并上线影子总账/对账/关账/快手平台退款
- 人工确认履约:管理员/财务/运营可传 fundAccountId / creditOwnerAdminUserId
  指定客服备用金/积分账户;客服仍强制本人账户
- 新增迁移 112:finance_accounts / journal_entries / journal_lines /
  periods / reconciliations / reconciliation_items,种子 11 个科目
- 影子总账:销售事实按日生成收入/退款/成本凭证,支持手工凭证、试算平衡;
  不接管钱包余额;总账同步接入定时任务与退款重算
- 期间关账/反关账:关账先补凭证并校验试算平衡,closed 期间禁止新增凭证
- 平台对账:JSON 账单导入,按 provider + platform_order_id 匹配订单/退款,
  标记 matched/amount_mismatch/missing_order/missing_refund/duplicate
- 平台退款:快手行业(91)同意退款 API 接入,成功后落 source=platform;
  抖音/拼多多返回 501,保留手工退款
- 新增后台「财务 → 总账与对账」页面(总账/期间/对账三个 Tab)
- 集成测试扩展到代录、总账平衡、关账阻断、手工凭证、对账匹配

验证:backend check 844(840 pass / 4 skip);frontend check 172 + build;
迁移 112 在 scratch 库全量执行并重跑幂等;本地生产副本已升级到 112,
销售事实同步 56 条凭证,借贷合计 1,885,351,864 = 1,885,351,864。
2026-10-26 13:32:47 +08:00

414 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { PoolClient } from 'pg'
import { query, withTransaction } from '../../db/client.js'
import type { JsonObject } from '../../types/json.js'
import { createHttpError } from '../../utils/http.js'
import { nowIso } from '../../utils/time.js'
import type { AdminSession } from '../admin/admin-auth-service.js'
/**
* 平台对账:
* 导入平台账单行(销售/退款)→ 与 orders / order_refunds 匹配 →
* 标记 matched / amount_mismatch / missing_order / missing_refund / duplicate。
* 这是「手工账单导入」先行;平台 API 自动拉单后续可复用同一匹配器。
*/
type ReconciliationRowInput = {
platformOrderId?: unknown
platform_order_id?: unknown
entryType?: unknown
entry_type?: unknown
amountFen?: unknown
amount_fen?: unknown
externalRef?: unknown
external_ref?: unknown
occurredAt?: unknown
occurred_at?: unknown
}
export async function importFinanceReconciliation(payload: JsonObject, session: AdminSession) {
const provider = String(payload.provider || '').trim()
if (!provider) {
throw createHttpError('请选择平台', {
statusCode: 400,
errorCode: 'finance_reconciliation_provider_required',
})
}
const periodFrom = normalizeDate(payload.periodFrom ?? payload.period_from, '开始日期')
const periodTo = normalizeDate(payload.periodTo ?? payload.period_to, '结束日期')
if (periodFrom > periodTo) {
throw createHttpError('开始日期不能晚于结束日期', {
statusCode: 400,
errorCode: 'finance_reconciliation_period_invalid',
})
}
const rawRows = Array.isArray(payload.rows) ? (payload.rows as ReconciliationRowInput[]) : []
if (rawRows.length === 0 || rawRows.length > 5000) {
throw createHttpError('对账明细需为 1–5000 行', {
statusCode: 400,
errorCode: 'finance_reconciliation_rows_invalid',
})
}
const rows = rawRows.map((row, index) => normalizeRow(row, provider, index))
const now = nowIso()
return withTransaction(async (client) => {
const batch = await client.query<{ id: number }>(
`
INSERT INTO finance_reconciliations (
provider, period_from, period_to, source, status,
expected_fen, actual_fen, diff_fen, summary_json,
imported_by_admin_user_id, created_at, updated_at
) VALUES ($1, $2::date, $3::date, 'manual_import', 'imported', 0, 0, 0, '{}'::jsonb, $4, $5, $5)
RETURNING id
`,
[provider, periodFrom, periodTo, Number(session.userId || 0) || null, now],
)
const reconciliationId = Number(batch.rows[0]?.id || 0)
let expectedFen = 0
let actualFen = 0
let matchedCount = 0
let mismatchCount = 0
const seen = new Set<string>()
for (const [index, row] of rows.entries()) {
const duplicateKey =
row.entryType === 'sale'
? `${row.platformOrderId}|sale`
: `${row.platformOrderId}|refund|${row.externalRef || row.amountFen}`
const isDuplicate = seen.has(duplicateKey)
seen.add(duplicateKey)
const match = isDuplicate
? { status: 'duplicate' as const, orderId: null, refundId: null, expected: null }
: await matchRow(client, provider, row)
const expected = match.expected
const diff = expected === null ? null : row.amountFen - expected
if (match.status === 'matched') matchedCount += 1
else mismatchCount += 1
actualFen += row.amountFen
expectedFen += expected ?? 0
await client.query(
`
INSERT INTO finance_reconciliation_items (
reconciliation_id, line_no, provider, platform_order_id, external_ref,
entry_type, amount_fen, occurred_at, matched_order_id, matched_refund_id,
expected_fen, diff_fen, match_status, detail_json, created_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8::timestamptz, $9, $10,
$11, $12, $13, $14::jsonb, $15
)
`,
[
reconciliationId,
index + 1,
provider,
row.platformOrderId,
row.externalRef,
row.entryType,
row.amountFen,
row.occurredAt,
match.orderId,
match.refundId,
expected,
diff,
match.status,
JSON.stringify({
message:
match.status === 'matched'
? '金额与系统一致'
: match.status === 'duplicate'
? '同一批次内重复行'
: match.status === 'missing_order'
? '平台账单有销售单,系统无对应订单'
: match.status === 'missing_refund'
? '平台账单有退款,系统无对应退款记录'
: '金额与系统不一致',
}),
now,
],
)
}
const status = mismatchCount === 0 ? 'matched' : 'differences'
await client.query(
`
UPDATE finance_reconciliations
SET status = $2,
expected_fen = $3,
actual_fen = $4,
diff_fen = $4::bigint - $3::bigint,
summary_json = $5::jsonb,
updated_at = $6
WHERE id = $1
`,
[
reconciliationId,
status,
expectedFen,
actualFen,
JSON.stringify({ rows: rows.length, matched: matchedCount, mismatched: mismatchCount }),
now,
],
)
return {
reconciliationId,
status,
rows: rows.length,
matched: matchedCount,
mismatched: mismatchCount,
expectedFen,
actualFen,
diffFen: actualFen - expectedFen,
}
})
}
export async function listFinanceReconciliations(input: Record<string, unknown> = {}) {
const page = Math.max(1, Number(input.page) || 1)
const pageSize = Math.min(100, Math.max(1, Number(input.pageSize ?? input.page_size) || 20))
const provider = String(input.provider || '').trim()
const params: unknown[] = []
const clauses: string[] = []
if (provider) {
params.push(provider)
clauses.push(`r.provider = $${params.length}`)
}
const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : ''
const count = await query<{ total: number }>(
`SELECT COUNT(*)::int AS total FROM finance_reconciliations r ${where}`,
params,
)
const rows = await query<Record<string, unknown>>(
`
SELECT r.*, au.display_name AS imported_by_name
FROM finance_reconciliations r
LEFT JOIN admin_users au ON au.id = r.imported_by_admin_user_id
${where}
ORDER BY r.created_at DESC, r.id DESC
LIMIT $${params.length + 1} OFFSET $${params.length + 2}
`,
[...params, pageSize, (page - 1) * pageSize],
)
return {
items: rows.rows.map(mapReconciliation),
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
}
}
export async function getFinanceReconciliation(idInput: unknown) {
const id = normalizeId(idInput)
const batch = await query<Record<string, unknown>>(
`
SELECT r.*, au.display_name AS imported_by_name
FROM finance_reconciliations r
LEFT JOIN admin_users au ON au.id = r.imported_by_admin_user_id
WHERE r.id = $1
LIMIT 1
`,
[id],
)
if (!batch.rows[0]) {
throw createHttpError('对账批次不存在', {
statusCode: 404,
errorCode: 'finance_reconciliation_not_found',
})
}
const items = await query<Record<string, unknown>>(
`SELECT * FROM finance_reconciliation_items WHERE reconciliation_id = $1 ORDER BY line_no`,
[id],
)
return {
...mapReconciliation(batch.rows[0]),
items: items.rows.map((row) => ({
id: Number(row.id),
lineNo: Number(row.line_no),
platformOrderId: String(row.platform_order_id || ''),
externalRef: String(row.external_ref || ''),
entryType: String(row.entry_type || ''),
amountFen: Number(row.amount_fen || 0),
expectedFen: row.expected_fen === null ? null : Number(row.expected_fen),
diffFen: row.diff_fen === null ? null : Number(row.diff_fen),
occurredAt: row.occurred_at,
matchedOrderId: row.matched_order_id ? Number(row.matched_order_id) : null,
matchedRefundId: row.matched_refund_id ? Number(row.matched_refund_id) : null,
matchStatus: String(row.match_status || ''),
detail: row.detail_json || {},
})),
}
}
export async function resolveFinanceReconciliation(
idInput: unknown,
note: unknown,
_session: AdminSession,
) {
const id = normalizeId(idInput)
const result = await query<Record<string, unknown>>(
`
UPDATE finance_reconciliations
SET status = 'resolved',
resolved_at = $2,
summary_json = jsonb_set(summary_json, '{resolutionNote}', to_jsonb($3::text), true),
updated_at = $2
WHERE id = $1 AND status IN ('differences', 'matched', 'imported')
RETURNING *
`,
[id, nowIso(), String(note || '').slice(0, 500)],
)
if (!result.rows[0]) {
throw createHttpError('对账批次不存在或已解决', {
statusCode: 404,
errorCode: 'finance_reconciliation_not_resolvable',
})
}
return mapReconciliation(result.rows[0])
}
async function matchRow(
client: PoolClient,
provider: string,
row: ReturnType<typeof normalizeRow>,
): Promise<{
status: 'matched' | 'amount_mismatch' | 'missing_order' | 'missing_refund'
orderId: number | null
refundId: number | null
expected: number | null
}> {
if (row.entryType === 'sale') {
const order = await client.query<{ id: number; total_amount: number }>(
`SELECT id, total_amount FROM orders
WHERE provider = $1 AND platform_order_id = $2
ORDER BY id DESC LIMIT 1`,
[provider, row.platformOrderId],
)
const found = order.rows[0]
if (!found) {
return { status: 'missing_order', orderId: null, refundId: null, expected: null }
}
const expected = Number(found.total_amount || 0)
return {
status: expected === row.amountFen ? 'matched' : 'amount_mismatch',
orderId: Number(found.id),
refundId: null,
expected,
}
}
const params: unknown[] = [provider, row.platformOrderId]
let externalClause = ''
if (row.externalRef) {
params.push(row.externalRef)
externalClause = ` AND r.external_ref = $${params.length}`
}
const refund = await client.query<{ id: number; amount_fen: number }>(
`
SELECT r.id, r.amount_fen
FROM order_refunds r
JOIN orders o ON o.id = r.order_id
WHERE o.provider = $1 AND o.platform_order_id = $2
AND r.status = 'confirmed' ${externalClause}
ORDER BY r.id DESC
LIMIT 1
`,
params,
)
const found = refund.rows[0]
if (!found) {
return { status: 'missing_refund', orderId: null, refundId: null, expected: null }
}
const expected = Number(found.amount_fen || 0)
return {
status: expected === row.amountFen ? 'matched' : 'amount_mismatch',
orderId: null,
refundId: Number(found.id),
expected,
}
}
function normalizeRow(row: ReconciliationRowInput, provider: string, index: number) {
const platformOrderId = String(row.platformOrderId ?? row.platform_order_id ?? '').trim()
if (!platformOrderId) {
throw createHttpError(`第 ${index + 1} 行缺少平台订单号`, {
statusCode: 400,
errorCode: 'finance_reconciliation_order_id_required',
})
}
const entryType = String(row.entryType ?? row.entry_type ?? 'sale').trim()
if (entryType !== 'sale' && entryType !== 'refund') {
throw createHttpError(`第 ${index + 1} 行类型只能是 sale/refund`, {
statusCode: 400,
errorCode: 'finance_reconciliation_type_invalid',
})
}
const amountFen = Math.trunc(Number(row.amountFen ?? row.amount_fen))
if (!Number.isFinite(amountFen) || amountFen <= 0) {
throw createHttpError(`第 ${index + 1} 行金额无效`, {
statusCode: 400,
errorCode: 'finance_reconciliation_amount_invalid',
})
}
const occurredAtRaw = row.occurredAt ?? row.occurred_at
const occurredAt = occurredAtRaw ? new Date(String(occurredAtRaw)) : null
if (occurredAtRaw && !Number.isFinite(occurredAt?.getTime())) {
throw createHttpError(`第 ${index + 1} 行时间无效`, {
statusCode: 400,
errorCode: 'finance_reconciliation_time_invalid',
})
}
return {
provider,
platformOrderId,
entryType,
amountFen,
externalRef: String(row.externalRef ?? row.external_ref ?? '').trim(),
occurredAt: occurredAt ? occurredAt.toISOString() : null,
}
}
function mapReconciliation(row: Record<string, unknown>) {
return {
id: Number(row.id),
provider: String(row.provider || ''),
periodFrom: row.period_from,
periodTo: row.period_to,
source: String(row.source || ''),
status: String(row.status || ''),
expectedFen: Number(row.expected_fen || 0),
actualFen: Number(row.actual_fen || 0),
diffFen: Number(row.diff_fen || 0),
summary: row.summary_json || {},
importedByAdminUserId: row.imported_by_admin_user_id
? Number(row.imported_by_admin_user_id)
: null,
importedByName: String(row.imported_by_name || ''),
resolvedAt: row.resolved_at,
createdAt: row.created_at,
}
}
function normalizeDate(value: unknown, label: string) {
const text = String(value || '').trim()
if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) {
throw createHttpError(`${label}格式无效(YYYY-MM-DD)`, {
statusCode: 400,
errorCode: 'finance_reconciliation_date_invalid',
})
}
return text
}
function normalizeId(value: unknown) {
const id = Number(value)
if (!Number.isInteger(id) || id <= 0) {
throw createHttpError('对账批次 ID 无效', {
statusCode: 400,
errorCode: 'finance_reconciliation_id_invalid',
})
}
return id
}