import type { ProfileWalletLedgerEntry, ProfileWalletLedgerResponse, } from '../../contracts/runtime'; const PROFILE_WALLET_LEDGER_SOURCE_LABELS = { new_user_registration_reward: '注册赠送', points_recharge: '泥点充值', invite_inviter_reward: '邀请奖励', invite_invitee_reward: '填写邀请码奖励', snapshot_sync: '账户同步', membership_period_grant: '会员周期发放', membership_period_reset: '会员周期重置', membership_upgrade_grant: '会员升级补点', daily_free_grant: '每日免费发放', daily_free_reset: '每日免费重置', asset_operation_consume: '资产操作消耗', llm_router_consume: 'LLM 调用消耗', asset_operation_refund: '资产操作退回', recharge_refund_recovery: '充值退款追回', redeem_code_reward: '兑换码奖励', puzzle_author_incentive_claim: '拼图作者奖励', daily_task_reward: '每日任务奖励', game_purchase: '购买游戏', } satisfies Record; export type ProfileWalletLedgerEntryPresentation = { amountLabel: string; balanceLabel: string; createdAtLabel: string; id: string; isIncome: boolean; sourceLabel: string; }; export type ProfileWalletLedgerPresentation = { balance: number; balanceLabel: string; entries: ProfileWalletLedgerEntryPresentation[]; }; export function getWalletLedgerSourceLabel( sourceType: string | null | undefined, ) { const normalizedSourceType = sourceType?.trim() ?? ''; if (!normalizedSourceType) { return '未知来源'; } return ( PROFILE_WALLET_LEDGER_SOURCE_LABELS[ normalizedSourceType as ProfileWalletLedgerEntry['sourceType'] ] ?? normalizedSourceType ); } export function formatWalletLedgerAmount(amountDelta: number) { return amountDelta > 0 ? `+${amountDelta}` : `${amountDelta}`; } export function formatWalletLedgerDate(value: string) { const normalized = value.trim(); const numericTimestamp = normalized.match(/^(-?\d+(?:\.\d+)?)(?:Z)?$/u); let date: Date; if (numericTimestamp?.[1]) { const rawTimestamp = Number(numericTimestamp[1]); const absoluteTimestamp = Math.abs(rawTimestamp); const timestampMs = absoluteTimestamp >= 1_000_000_000_000_000 ? rawTimestamp / 1000 : absoluteTimestamp >= 1_000_000_000_000 ? rawTimestamp : absoluteTimestamp >= 1_000_000_000 ? rawTimestamp * 1000 : Number.NaN; date = new Date(timestampMs); } else { date = new Date(normalized); } if (Number.isNaN(date.getTime())) { return value; } const year = date.getUTCFullYear(); const month = String(date.getUTCMonth() + 1).padStart(2, '0'); const day = String(date.getUTCDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } export function buildWalletLedgerPresentation( ledger: ProfileWalletLedgerResponse | null, fallbackBalance: number, ): ProfileWalletLedgerPresentation { const entries = ledger?.entries ?? []; const balance = entries[0]?.balanceAfter ?? fallbackBalance; return { balance, balanceLabel: `${balance}泥点`, entries: entries.map((entry) => ({ amountLabel: formatWalletLedgerAmount(entry.amountDelta), balanceLabel: `余额 ${entry.balanceAfter}`, createdAtLabel: formatWalletLedgerDate(entry.createdAt), id: entry.id, isIncome: entry.amountDelta > 0, sourceLabel: entry.reason?.trim() || getWalletLedgerSourceLabel(entry.sourceType), })), }; }