feat(finance): 完成财务控制、L1 钱包硬化与迁移收敛
- P0/P1:影子总账追加调整、关账/退款/资金/积分幂等、成本版本追溯、对账订单项维度 - 迁移收敛:原 103–114 合并为 103_finance_foundation、104_finance_controls、105_work_order_consignment - 数据:L1 钱包 BIGINT/CHECK/奖励幂等;重复奖励审计口径修正与人工核对清单 - 报表:销售毛利缺失成本收入提示,旧收支页明确现金流口径 - 文档:同步迁移基线、合并评估、代码复核与上线说明
This commit is contained in:
@@ -7,6 +7,8 @@
|
||||
*
|
||||
* 后续接平台退款 API 时,只需写 source='api'/'platform' 的记录,其余逻辑复用。
|
||||
*/
|
||||
import type { PoolClient } from 'pg'
|
||||
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import type { AdminSession } from '../admin/admin-auth-service.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
@@ -140,6 +142,7 @@ export async function createManualRefund(
|
||||
errorCode: 'order_refund_order_not_found',
|
||||
})
|
||||
}
|
||||
await assertBasisPeriodOpen(client, order.basis_at, '退款')
|
||||
|
||||
const itemsResult = await client.query<{
|
||||
id: number
|
||||
@@ -203,38 +206,63 @@ export async function createManualRefund(
|
||||
})
|
||||
}
|
||||
|
||||
if (externalRef) {
|
||||
const duplicate = await client.query<{ id: number }>(
|
||||
`SELECT id FROM order_refunds
|
||||
WHERE source = $1 AND external_ref = $2
|
||||
LIMIT 1`,
|
||||
[source, externalRef],
|
||||
)
|
||||
if (duplicate.rows[0]) {
|
||||
throw createHttpError('该平台退款单号已登记过,不能重复退款', {
|
||||
statusCode: 409,
|
||||
errorCode: 'order_refund_external_ref_exists',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const batchNo = generateRefundNo(new Date(refundedAt))
|
||||
const insertedIds: number[] = []
|
||||
for (const [index, row] of rows.entries()) {
|
||||
const inserted = await client.query<{ id: number }>(
|
||||
`
|
||||
INSERT INTO order_refunds (
|
||||
refund_no, batch_no, order_id, order_item_id, amount_fen,
|
||||
reason, note, source, status, refunded_at, external_ref,
|
||||
operator_admin_user_id, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5,
|
||||
$6, $7, $8, 'confirmed', $9::timestamptz, $10,
|
||||
$11, $12::timestamptz, $12::timestamptz
|
||||
)
|
||||
RETURNING id
|
||||
`,
|
||||
[
|
||||
`${batchNo}-${String(index + 1).padStart(2, '0')}`,
|
||||
batchNo,
|
||||
orderId,
|
||||
row.itemId,
|
||||
row.amountFen,
|
||||
reason,
|
||||
note,
|
||||
source,
|
||||
refundedAt,
|
||||
externalRef,
|
||||
session?.userId || null,
|
||||
now,
|
||||
],
|
||||
)
|
||||
insertedIds.push(Number(inserted.rows[0]?.id || 0))
|
||||
try {
|
||||
const inserted = await client.query<{ id: number }>(
|
||||
`
|
||||
INSERT INTO order_refunds (
|
||||
refund_no, batch_no, order_id, order_item_id, amount_fen,
|
||||
reason, note, source, status, refunded_at, external_ref,
|
||||
operator_admin_user_id, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5,
|
||||
$6, $7, $8, 'confirmed', $9::timestamptz, $10,
|
||||
$11, $12::timestamptz, $12::timestamptz
|
||||
)
|
||||
RETURNING id
|
||||
`,
|
||||
[
|
||||
`${batchNo}-${String(index + 1).padStart(2, '0')}`,
|
||||
batchNo,
|
||||
orderId,
|
||||
row.itemId,
|
||||
row.amountFen,
|
||||
reason,
|
||||
note,
|
||||
source,
|
||||
refundedAt,
|
||||
externalRef,
|
||||
session?.userId || null,
|
||||
now,
|
||||
],
|
||||
)
|
||||
insertedIds.push(Number(inserted.rows[0]?.id || 0))
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code === '23505') {
|
||||
throw createHttpError('该平台退款单号已登记过,不能重复退款', {
|
||||
statusCode: 409,
|
||||
errorCode: 'order_refund_external_ref_exists',
|
||||
})
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// 订单项都退完 → 订单级 pay_status 同步为 refunded(与平台全额退款口径一致)。
|
||||
@@ -327,10 +355,11 @@ export async function voidOrderRefund(
|
||||
id: number
|
||||
order_id: number
|
||||
status: string
|
||||
pay_status: string
|
||||
basis_at: string
|
||||
}>(
|
||||
`
|
||||
SELECT r.id, r.order_id, r.status, COALESCE(o.paid_at, o.created_at) AS basis_at
|
||||
SELECT r.id, r.order_id, r.status, o.pay_status, COALESCE(o.paid_at, o.created_at) AS basis_at
|
||||
FROM order_refunds r
|
||||
JOIN orders o ON o.id = r.order_id
|
||||
WHERE r.id = $1
|
||||
@@ -351,6 +380,7 @@ export async function voidOrderRefund(
|
||||
errorCode: 'order_refund_already_voided',
|
||||
})
|
||||
}
|
||||
await assertBasisPeriodOpen(client, row.basis_at, '撤销退款')
|
||||
await client.query(
|
||||
`
|
||||
UPDATE order_refunds
|
||||
@@ -363,6 +393,50 @@ export async function voidOrderRefund(
|
||||
`,
|
||||
[now, reason, session?.userId || null, id],
|
||||
)
|
||||
|
||||
// 撤销后按“剩余 confirmed 退款”重算订单支付状态:
|
||||
// 全额退款撤销必须把订单从 refunded 恢复为 paid,否则销售事实仍会按全额退款冲减。
|
||||
const totals = await client.query<{ revenue_fen: number; refunded_fen: number }>(
|
||||
`
|
||||
SELECT
|
||||
COALESCE(SUM(GREATEST(COALESCE(oi.revenue_amount_fen, 0), 0)), 0)::bigint AS revenue_fen,
|
||||
COALESCE((
|
||||
SELECT SUM(r.amount_fen)
|
||||
FROM order_refunds r
|
||||
JOIN order_items ri ON ri.id = r.order_item_id
|
||||
WHERE ri.order_id = $1 AND r.status = 'confirmed'
|
||||
), 0)::bigint AS refunded_fen
|
||||
FROM order_items oi
|
||||
WHERE oi.order_id = $1
|
||||
`,
|
||||
[row.order_id],
|
||||
)
|
||||
const totalRevenue = Number(totals.rows[0]?.revenue_fen || 0)
|
||||
const totalRefunded = Number(totals.rows[0]?.refunded_fen || 0)
|
||||
let nextPayStatus = row.pay_status
|
||||
if (totalRevenue > 0) {
|
||||
nextPayStatus = totalRefunded >= totalRevenue ? 'refunded' : 'paid'
|
||||
}
|
||||
await client.query(
|
||||
`UPDATE orders SET pay_status = $1, updated_at = $2::timestamptz WHERE id = $3`,
|
||||
[nextPayStatus, now, row.order_id],
|
||||
)
|
||||
|
||||
// 退款时自动关闭的成本异常,撤销后重新打开,避免成本缺口被永久忽略。
|
||||
await client.query(
|
||||
`
|
||||
UPDATE cost_exceptions
|
||||
SET status = 'open',
|
||||
resolved_at = NULL,
|
||||
resolved_by_admin_user_id = NULL,
|
||||
resolution_note = ''
|
||||
WHERE status = 'ignored'
|
||||
AND resolution_note = '订单已退款,成本异常自动关闭'
|
||||
AND order_item_id IN (SELECT id FROM order_items WHERE order_id = $1)
|
||||
`,
|
||||
[row.order_id],
|
||||
)
|
||||
|
||||
return { orderId: Number(row.order_id), basisAt: row.basis_at }
|
||||
})
|
||||
|
||||
@@ -404,6 +478,26 @@ export function mapOrderRefund(row: OrderRefundRow): OrderRefund {
|
||||
}
|
||||
}
|
||||
|
||||
async function assertBasisPeriodOpen(
|
||||
client: Pick<PoolClient, 'query'>,
|
||||
basisAt: string,
|
||||
action: string,
|
||||
) {
|
||||
const basisDate = toChinaDate(basisAt)
|
||||
if (!basisDate) return
|
||||
const periodKey = basisDate.slice(0, 7)
|
||||
const period = await client.query<{ status: string }>(
|
||||
`SELECT status FROM finance_periods WHERE period_key = $1 LIMIT 1`,
|
||||
[periodKey],
|
||||
)
|
||||
if (period.rows[0]?.status === 'closed') {
|
||||
throw createHttpError(`订单所属期间 ${periodKey} 已关账,请先反关账后再${action}`, {
|
||||
statusCode: 409,
|
||||
errorCode: 'order_refund_period_closed',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeId(value: unknown, label: string): number {
|
||||
const id = Number(value || 0)
|
||||
if (!Number.isFinite(id) || id <= 0) {
|
||||
@@ -484,16 +578,6 @@ export async function approveAndRecordKuaishouRefund(
|
||||
errorCode: 'platform_refund_order_item_required',
|
||||
})
|
||||
}
|
||||
const itemExist = await query<{ id: number }>(
|
||||
`SELECT id FROM order_items WHERE id = $1 AND order_id = $2 LIMIT 1`,
|
||||
[orderItemId, orderId],
|
||||
)
|
||||
if (!itemExist.rows[0]) {
|
||||
throw createHttpError('订单项不存在或不属于该订单', {
|
||||
statusCode: 404,
|
||||
errorCode: 'platform_refund_order_item_not_found',
|
||||
})
|
||||
}
|
||||
const order = await query<{ provider: string; platform_order_id: string }>(
|
||||
`SELECT provider, platform_order_id FROM orders WHERE id = $1 LIMIT 1`,
|
||||
[orderId],
|
||||
@@ -519,27 +603,228 @@ export async function approveAndRecordKuaishouRefund(
|
||||
errorCode: 'platform_refund_amount_invalid',
|
||||
})
|
||||
}
|
||||
const approval = await approveKuaishouIndustryRefund({
|
||||
refundId: platformRefundId,
|
||||
refundAmount: amountFen,
|
||||
desc: input.desc || input.note || '',
|
||||
refundHandingWay: input.refundHandingWay,
|
||||
...(input.sellerId ? { sellerId: input.sellerId } : {}),
|
||||
})
|
||||
const refund = await createManualRefund(
|
||||
{
|
||||
orderId,
|
||||
orderItemId,
|
||||
amountFen,
|
||||
reason: input.reason || '平台退款',
|
||||
note: input.note,
|
||||
refundedAt: input.refundedAt,
|
||||
source: 'platform',
|
||||
externalRef: platformRefundId,
|
||||
},
|
||||
session,
|
||||
|
||||
const existingItem = await query<{ id: number }>(
|
||||
`SELECT id FROM order_items WHERE id = $1 AND order_id = $2 LIMIT 1`,
|
||||
[orderItemId, orderId],
|
||||
)
|
||||
return { approval, ...refund }
|
||||
if (!existingItem.rows[0]) {
|
||||
throw createHttpError('订单项不存在或不属于该订单', {
|
||||
statusCode: 404,
|
||||
errorCode: 'platform_refund_order_item_not_found',
|
||||
})
|
||||
}
|
||||
|
||||
// 已关账期间不能直接改原期间事实;必须先反关账,否则平台退款后本地无法正确冲减。
|
||||
const basis = await query<{ basis_at: string }>(
|
||||
`SELECT COALESCE(paid_at, created_at) AS basis_at FROM orders WHERE id = $1 LIMIT 1`,
|
||||
[orderId],
|
||||
)
|
||||
if (basis.rows[0]?.basis_at) {
|
||||
const basisDate = toChinaDate(String(basis.rows[0].basis_at))
|
||||
const periodKey = basisDate.slice(0, 7)
|
||||
const period = await query<{ status: string }>(
|
||||
`SELECT status FROM finance_periods WHERE period_key = $1 LIMIT 1`,
|
||||
[periodKey],
|
||||
)
|
||||
if (period.rows[0]?.status === 'closed') {
|
||||
throw createHttpError(`订单所属期间 ${periodKey} 已关账,请先反关账后再退款`, {
|
||||
statusCode: 409,
|
||||
errorCode: 'order_refund_period_closed',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 已经登记过的平台退款必须幂等返回,不能因为剩余可退为 0 被误判为超额。
|
||||
const recorded = await findRecordedPlatformRefund(orderId, platformRefundId)
|
||||
if (recorded) {
|
||||
return {
|
||||
approval: { idempotent: true, platformRefundId },
|
||||
batchNo: recorded.batchNo,
|
||||
refunds: [recorded],
|
||||
fullRefunded: false,
|
||||
closedExceptionCount: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// 先做可退金额校验,再落退款意图;平台调用之后不再做“才发现金额超了”的校验。
|
||||
const remainingFen = await getRefundableFen(orderId, orderItemId)
|
||||
if (amountFen > remainingFen) {
|
||||
throw createHttpError(`退款金额超出可退金额(剩余 ${formatFen(remainingFen)})`, {
|
||||
statusCode: 409,
|
||||
errorCode: 'order_refund_amount_exceeds',
|
||||
})
|
||||
}
|
||||
|
||||
const intent = await beginPlatformRefundIntent({
|
||||
provider: '91kaquan',
|
||||
externalRef: platformRefundId,
|
||||
orderId,
|
||||
orderItemId,
|
||||
amountFen,
|
||||
actorUserId: session?.userId || null,
|
||||
})
|
||||
|
||||
const needsPlatformCall =
|
||||
intent.status === 'pending' ||
|
||||
(intent.status === 'failed' && !String(intent.error_message || '').startsWith('record_failed:'))
|
||||
|
||||
let approval: unknown = { idempotent: true, platformRefundId }
|
||||
if (needsPlatformCall) {
|
||||
try {
|
||||
approval = await approveKuaishouIndustryRefund({
|
||||
refundId: platformRefundId,
|
||||
refundAmount: amountFen,
|
||||
desc: input.desc || input.note || '',
|
||||
refundHandingWay: input.refundHandingWay,
|
||||
...(input.sellerId ? { sellerId: input.sellerId } : {}),
|
||||
})
|
||||
await updatePlatformRefundIntent(intent.id, 'platform_approved')
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
await updatePlatformRefundIntent(intent.id, 'failed', `platform_call_failed:${message}`)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const refund = await createManualRefund(
|
||||
{
|
||||
orderId,
|
||||
orderItemId,
|
||||
amountFen,
|
||||
reason: input.reason || '平台退款',
|
||||
note: input.note,
|
||||
refundedAt: input.refundedAt,
|
||||
source: 'platform',
|
||||
externalRef: platformRefundId,
|
||||
},
|
||||
session,
|
||||
)
|
||||
await updatePlatformRefundIntent(intent.id, 'recorded')
|
||||
return { approval, ...refund }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
await updatePlatformRefundIntent(intent.id, 'failed', `record_failed:${message}`)
|
||||
throw createHttpError(
|
||||
`平台已同意退款,但本地记账失败:${message}。已保留退款意图,可用同一 platformRefundId 重试`,
|
||||
{
|
||||
statusCode: 502,
|
||||
errorCode: 'platform_refund_record_failed',
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
type PlatformRefundIntentRow = {
|
||||
id: number
|
||||
status: string
|
||||
error_message: string
|
||||
}
|
||||
|
||||
async function beginPlatformRefundIntent(input: {
|
||||
provider: string
|
||||
externalRef: string
|
||||
orderId: number
|
||||
orderItemId: number
|
||||
amountFen: number
|
||||
actorUserId: number | null
|
||||
}): Promise<PlatformRefundIntentRow> {
|
||||
return withTransaction(async (client) => {
|
||||
const existing = await client.query<PlatformRefundIntentRow>(
|
||||
`SELECT id, status, error_message
|
||||
FROM finance_refund_intents
|
||||
WHERE provider = $1 AND external_ref = $2
|
||||
FOR UPDATE`,
|
||||
[input.provider, input.externalRef],
|
||||
)
|
||||
if (existing.rows[0]) return existing.rows[0]
|
||||
|
||||
try {
|
||||
const inserted = await client.query<PlatformRefundIntentRow>(
|
||||
`
|
||||
INSERT INTO finance_refund_intents (
|
||||
provider, external_ref, order_id, order_item_id, amount_fen,
|
||||
status, error_message, created_by_admin_user_id, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, 'pending', '', $6, $7, $7)
|
||||
RETURNING id, status, error_message
|
||||
`,
|
||||
[
|
||||
input.provider,
|
||||
input.externalRef,
|
||||
input.orderId,
|
||||
input.orderItemId,
|
||||
input.amountFen,
|
||||
input.actorUserId,
|
||||
nowIso(),
|
||||
],
|
||||
)
|
||||
return inserted.rows[0] as PlatformRefundIntentRow
|
||||
} catch (error) {
|
||||
// 并发请求同时插入时,唯一键冲突后读取已存在的意图,由调用方按状态决定是否重试。
|
||||
if ((error as { code?: string }).code === '23505') {
|
||||
const again = await client.query<PlatformRefundIntentRow>(
|
||||
`SELECT id, status, error_message
|
||||
FROM finance_refund_intents
|
||||
WHERE provider = $1 AND external_ref = $2
|
||||
LIMIT 1`,
|
||||
[input.provider, input.externalRef],
|
||||
)
|
||||
return again.rows[0] as PlatformRefundIntentRow
|
||||
}
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function updatePlatformRefundIntent(
|
||||
id: number,
|
||||
status: 'platform_approved' | 'recorded' | 'failed',
|
||||
errorMessage = '',
|
||||
) {
|
||||
await query(
|
||||
`UPDATE finance_refund_intents
|
||||
SET status = $2, error_message = $3, updated_at = $4
|
||||
WHERE id = $1`,
|
||||
[id, status, errorMessage.slice(0, 1000), nowIso()],
|
||||
)
|
||||
}
|
||||
|
||||
async function getRefundableFen(orderId: number, orderItemId: number): Promise<number> {
|
||||
const result = await query<{ remaining_fen: string }>(
|
||||
`
|
||||
SELECT
|
||||
(GREATEST(COALESCE(oi.revenue_amount_fen, 0), 0)
|
||||
- COALESCE((
|
||||
SELECT SUM(r.amount_fen)
|
||||
FROM order_refunds r
|
||||
WHERE r.order_item_id = oi.id AND r.status = 'confirmed'
|
||||
), 0))::bigint AS remaining_fen
|
||||
FROM order_items oi
|
||||
WHERE oi.id = $1 AND oi.order_id = $2
|
||||
LIMIT 1
|
||||
`,
|
||||
[orderItemId, orderId],
|
||||
)
|
||||
if (!result.rows[0]) {
|
||||
throw createHttpError('订单项不存在或不属于该订单', {
|
||||
statusCode: 404,
|
||||
errorCode: 'platform_refund_order_item_not_found',
|
||||
})
|
||||
}
|
||||
return Number(result.rows[0].remaining_fen || 0)
|
||||
}
|
||||
|
||||
async function findRecordedPlatformRefund(orderId: number, externalRef: string) {
|
||||
const result = await query<{ id: number }>(
|
||||
`SELECT id FROM order_refunds
|
||||
WHERE order_id = $1 AND source = 'platform' AND external_ref = $2 AND status = 'confirmed'
|
||||
LIMIT 1`,
|
||||
[orderId, externalRef],
|
||||
)
|
||||
if (!result.rows[0]) return null
|
||||
const refunds = await listOrderRefunds(orderId)
|
||||
return refunds.find((item) => item.id === Number(result.rows[0]?.id)) || null
|
||||
}
|
||||
|
||||
function normalizeRefundSource(value: unknown): 'manual' | 'api' | 'platform' | 'legacy' {
|
||||
|
||||
Reference in New Issue
Block a user