diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index a3b2e85..b77a660 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -1,6 +1,6 @@ 'use client' -import { useEffect, useState, useCallback, useMemo } from 'react' +import { useEffect, useState, useCallback, useMemo, useRef } from 'react' import { format } from 'date-fns' import { getCardsWithBillsSummary, @@ -19,8 +19,9 @@ import { BillDraftsPanel } from '@/components/mobile/BillDraftsPanel' import { ManualBillAmountDialog } from '@/components/mobile/ManualBillAmountDialog' import { PayableForm } from '@/components/mobile/PayableForm' import { - getRecurringPayables, payRecurringPayable, + getRecurringPayables, payRecurringPayable, getPayablePayments, type PayableWithStatus, + type PayablePaymentRecord, } from '@/lib/api/payables' import { formatCardTail, compareBillsListCardsByMode, pickDueReference, @@ -72,6 +73,15 @@ function tagSummary( return selectedTag === NO_BANK_TAG ? '非银行' : selectedTag } +/** 不可变地从 Record 中删除一个 key(无该 key 时返回原对象)。 */ +function omitRecordKey(record: Record, key: string): Record { + // 只判断自有属性:`in` 会沿原型链命中 toString/constructor 等 + if (!Object.prototype.hasOwnProperty.call(record, key)) return record + const next = { ...record } + delete next[key] + return next +} + export default function BillsPage() { const { user } = useAuth() const { displayConfig } = useUserPreferences() @@ -92,6 +102,11 @@ export default function BillsPage() { // 固定支出(房租/贷款等按月应付) const [payables, setPayables] = useState([]) const [payableFormOpen, setPayableFormOpen] = useState(false) + // 固定支出历史还款:按需加载,展开一次后缓存 + const [payablePayments, setPayablePayments] = useState>({}) + const [expandedPayableIds, setExpandedPayableIds] = useState>(new Set()) + const [payableHistoryErrors, setPayableHistoryErrors] = useState>({}) + const [payableHistoryLoading, setPayableHistoryLoading] = useState>(new Set()) const [editingPayable, setEditingPayable] = useState(null) const [celebrationNotice, setCelebrationNotice] = useState<{ open: boolean; message: string }>({ @@ -125,6 +140,59 @@ export default function BillsPage() { // 持卡人 id → name 映射 const [holderMap, setHolderMap] = useState>({}) + // 展开集合的 ref:异步回调里需要读最新值(state 是渲染快照) + const expandedPayableIdsRef = useRef(expandedPayableIds) + useEffect(() => { + expandedPayableIdsRef.current = expandedPayableIds + }, [expandedPayableIds]) + + // 同一笔的在途请求:并发点击或还款后重取都复用同一个 Promise,避免重复 RPC + const payableHistoryInFlight = useRef>>(new Map()) + + // 缓存代次:全量刷新或还款后递增,旧代次发起的请求不再写回 + const payableHistoryGeneration = useRef(0) + + /** 拉取并写入历史缓存;同一 payableId 复用进行中的请求。 */ + const loadPayableHistory = useCallback((payableId: string) => { + const running = payableHistoryInFlight.current.get(payableId) + if (running) return running + const generation = payableHistoryGeneration.current + setPayableHistoryLoading(prev => new Set(prev).add(payableId)) + let settle!: () => void + const current = new Promise(resolve => { settle = resolve }) + void (async () => { + try { + const records = await getPayablePayments(payableId) + // 代次已变(刷新/还款期间发起):结果作废,不写回旧数据 + if (payableHistoryGeneration.current !== generation) return + setPayablePayments(prev => ({ ...prev, [payableId]: records })) + setPayableHistoryErrors(prev => omitRecordKey(prev, payableId)) + } catch (err) { + if (payableHistoryGeneration.current !== generation) return + // 保持未加载状态:再次展开会重试;错误就地展示 + setPayableHistoryErrors(prev => ({ + ...prev, + [payableId]: err instanceof Error ? err.message : '历史还款加载失败', + })) + } finally { + // 只清理自己这条:被新任务顶替或代次已变时不能误删(否则新请求期间不显示加载中) + if ( + payableHistoryInFlight.current.get(payableId) === current && + payableHistoryGeneration.current === generation + ) { + payableHistoryInFlight.current.delete(payableId) + setPayableHistoryLoading(prev => { + const next = new Set(prev) + next.delete(payableId) + return next + }) + } + } + })().finally(() => settle()) + payableHistoryInFlight.current.set(payableId, current) + return current + }, []) + const loadData = useCallback(async () => { if (!user) return try { @@ -135,6 +203,12 @@ export default function BillsPage() { getHolders(user.id), ]) setCardsSummary(summaryData) + // 全量刷新:递增代次作废在途响应,清空缓存,并对仍展开的行重拉 + payableHistoryGeneration.current += 1 + payableHistoryInFlight.current.clear() + setPayablePayments({}) + setPayableHistoryErrors({}) + expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) }) const map: Record = {} for (const h of holders) map[h.id] = h.name setHolderMap(map) @@ -151,7 +225,7 @@ export default function BillsPage() { } finally { setLoading(false) } - }, [user]) + }, [user, loadPayableHistory]) useEffect(() => { loadData() @@ -416,6 +490,14 @@ export default function BillsPage() { const handlePayPayable = async (payable: PayableWithStatus) => { try { await payRecurringPayable(payable.id, payable.amount) + // 新还款落库:先等在途旧请求落定(否则它的成功回调会把不含新还款的记录写回), + // 再清缓存并重取 + // 递增代次:作废还款前发起的请求;随后清缓存 + payableHistoryGeneration.current += 1 + const running = payableHistoryInFlight.current.get(payable.id) + if (running) await running + setPayablePayments(prev => omitRecordKey(prev, payable.id)) + // 不在此处重取:紧随其后的 loadData 会统一清缓存并重拉展开行 setCelebrationNotice({ open: true, message: `🎉 已登记「${payable.name}」本期付款 ${currencySymbol(payable.currency)}${payable.amount.toLocaleString()}`, @@ -426,6 +508,22 @@ export default function BillsPage() { } } + /** 展开/收起固定支出历史:首次展开才拉取该笔记录。 */ + const handleTogglePayableHistory = useCallback( + (payableId: string) => { + const willOpen = !expandedPayableIdsRef.current.has(payableId) + setExpandedPayableIds(prev => { + const next = new Set(prev) + if (willOpen) next.add(payableId) + else next.delete(payableId) + return next + }) + if (!willOpen || payablePayments[payableId]) return + void loadPayableHistory(payableId) + }, + [payablePayments, loadPayableHistory] + ) + // 收起态摘要:把当前筛选、分组与排序压成一行可读文本 const filterSummary = useMemo(() => { const statusText = @@ -506,6 +604,11 @@ export default function BillsPage() { onRetry={() => loadData()} onEmptySync={handleSync} payables={filteredPayables} + payablePayments={payablePayments} + payableHistoryErrors={payableHistoryErrors} + payableHistoryLoading={payableHistoryLoading} + expandedPayableIds={expandedPayableIds} + onTogglePayableHistory={handleTogglePayableHistory} onEditPayable={p => { setEditingPayable(p); setPayableFormOpen(true) }} onPayPayable={handlePayPayable} cards={sortedCards} diff --git a/components/__tests__/BillReviewRegressions.test.tsx b/components/__tests__/BillReviewRegressions.test.tsx index 018ea80..2517da6 100644 --- a/components/__tests__/BillReviewRegressions.test.tsx +++ b/components/__tests__/BillReviewRegressions.test.tsx @@ -298,7 +298,10 @@ function makeBillsViewFixture(): { props: BillsViewProps; unpaid: BillDashboardI dimension: "holder", onDimension: vi.fn(), selectedTag: "all", onSelectedTag: vi.fn(), holderTags: [], bankTags: [], loading: false, loadError: null, onRetry: vi.fn(), onEmptySync: vi.fn(), - payables: [], onEditPayable: vi.fn(), onPayPayable: vi.fn(), cards: [item], + payables: [], onEditPayable: vi.fn(), onPayPayable: vi.fn(), + payablePayments: {}, payableHistoryErrors: {}, payableHistoryLoading: new Set(), + expandedPayableIds: new Set(), + onTogglePayableHistory: vi.fn(), cards: [item], allCards: [item], holderMap: {}, bankGroups: [], onOpenPayment: vi.fn(), onManualAmount: vi.fn(), onAddBill: vi.fn(), }, diff --git a/components/mobile/PayableList.tsx b/components/mobile/PayableList.tsx index e6f4385..1778b21 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -1,7 +1,13 @@ 'use client' import { useState } from 'react' -import { categoryLabel, type PayableWithStatus } from '@/lib/api/payables' +import { format } from 'date-fns' +import { + categoryLabel, + PAYABLE_HISTORY_LIMIT, + type PayableWithStatus, + type PayablePaymentRecord, +} from '@/lib/api/payables' import { payableNextCycleStatus } from '@/lib/utils' import { badgeToneClass, type BillBadgeTone } from '@/lib/bills-view-model' import { currencySymbol } from '@/lib/fx' @@ -11,10 +17,70 @@ export interface PayableRowProps { payable: PayableWithStatus /** 归属持卡人姓名;未指定归属时不显示 */ holderName?: string + /** 历史还款记录(按账期倒序);undefined = 尚未加载 */ + payments?: PayablePaymentRecord[] + /** 历史加载失败提示;为空表示无错误 */ + historyError?: string + /** 历史请求在途(含重试);优先于错误态展示 */ + historyLoading?: boolean + /** 是否展开历史还款 */ + historyOpen?: boolean + onToggleHistory?: () => void onEdit: (payable: PayableWithStatus) => void onPay: (payable: PayableWithStatus) => void } +/** 展开按钮文案:达到上限时改称「最近 N 笔」,避免误以为已看全。 */ +function historyLabel(payments: PayablePaymentRecord[] | undefined): string { + if (!payments || payments.length === 0) return '历史还款' + if (payments.length >= PAYABLE_HISTORY_LIMIT) return `最近 ${PAYABLE_HISTORY_LIMIT} 笔还款` + return `历史还款 ${payments.length} 笔` +} + +/** 历史还款展开区:加载中 / 失败 / 空 / 列表四态,避免嵌套三元。 */ +function renderPayableHistory( + payments: PayablePaymentRecord[] | undefined, + historyError: string | undefined, + historyLoading: boolean, + currency: string +) { + // 顺序必须是 在途 → 失败 → 未加载:失败时 payments 仍为 undefined, + // 若把 undefined 并入加载中,错误文案将永远不可达。 + if (historyLoading) { + return

加载中…

+ } + if (historyError) { + return

{historyError}

+ } + if (payments === undefined) { + // 无在途请求却仍为 undefined:说明缓存被清空但未重取,提示可再次展开 + return

展开以加载历史

+ } + if (payments.length === 0) { + return

还没有历史还款记录

+ } + return ( +
    + {payments.map(record => ( +
  • + {record.period} + + {format(new Date(record.paid_at), 'MM-dd')} + {record.note ? ' · ' + record.note : ''} + + + {currencySymbol(currency)} + {Number(record.amount).toLocaleString()} + +
  • + ))} +
+ ) +} + /** * 单条固定支出卡。从 PayableList 拆出:账单页现在把固定支出混进主列表统一排序。 * @@ -26,7 +92,17 @@ export interface PayableRowProps { * 滚动模型(服务端 resolveDisplayPeriod)保证任一时刻卡片只呈现一期: * 「已登记」只可能出现在待出账态,待还款态一定是可登记付款的未付期。 */ -export function PayableRow({ payable: p, holderName, onEdit, onPay }: PayableRowProps) { +export function PayableRow({ + payable: p, + holderName, + payments, + historyError, + historyLoading = false, + historyOpen = false, + onToggleHistory, + onEdit, + onPay, +}: PayableRowProps) { const [copiedAccount, setCopiedAccount] = useState(false) const paid = p.status === 'paid' const overdue = p.status === 'overdue' @@ -162,6 +238,22 @@ export function PayableRow({ payable: p, holderName, onEdit, onPay }: PayableRow {detail} + + {onToggleHistory && ( +
+ + {historyOpen && + renderPayableHistory(payments, historyError, historyLoading, p.currency)} +
+ )} ) } diff --git a/components/obsidian/BillsView.tsx b/components/obsidian/BillsView.tsx index 798b4dd..f4357c7 100644 --- a/components/obsidian/BillsView.tsx +++ b/components/obsidian/BillsView.tsx @@ -32,7 +32,7 @@ import { type BillsEntityType, } from '@/lib/bills-view-model' import { PayableRow } from '@/components/mobile/PayableList' -import type { PayableWithStatus } from '@/lib/api/payables' +import type { PayableWithStatus, PayablePaymentRecord } from '@/lib/api/payables' import { currencySymbol } from '@/lib/fx' import { AlertIcon, @@ -93,6 +93,13 @@ export interface BillsViewProps { onRetry: () => void onEmptySync: () => void payables: PayableWithStatus[] + /** 各固定支出的历史还款记录,key = payable id */ + payablePayments: Record + payableHistoryErrors: Record + payableHistoryLoading: Set + /** 已展开历史的 payable id */ + expandedPayableIds: Set + onTogglePayableHistory: (id: string) => void onEditPayable: (p: PayableWithStatus) => void onPayPayable: (p: PayableWithStatus) => void cards: CardWithBillsSummary[] @@ -276,11 +283,6 @@ function BillCard({ · 下期还款日 {format(new Date(item.nextDueDate), 'MM-dd')}

- {missingStatement && ( -

- 已过账单日 {missingStatement} 日,未接收到新的账单,请检查 -

- )} {isCleared || sortMode === 'max_interest_free' ? (

今日刷卡免息 {item.graceDays} 天 @@ -373,6 +375,13 @@ function BillCard({ )} )} + + {/* 缺账单提醒放在卡片最末:先看账单数据,再看采集异常 */} + {missingStatement && ( +

+ 已过账单日 {missingStatement} 日,未接收到新的账单,请检查 +

+ )} ) } @@ -386,6 +395,8 @@ export function BillsView(vm: BillsViewProps) { selectedTag, onSelectedTag, holderTags, bankTags, loading, loadError, onRetry, onEmptySync, payables, cards, allCards, holderMap, bankGroups, onOpenPayment, onManualAmount, onAddBill, sortMode, onSortMode, + payablePayments, payableHistoryErrors, payableHistoryLoading, + expandedPayableIds, onTogglePayableHistory, onEditPayable, onPayPayable, } = vm @@ -444,6 +455,11 @@ export function BillsView(vm: BillsViewProps) { key={`payable-${p.id}`} payable={p} holderName={p.holder_id ? holderMap[p.holder_id] : undefined} + payments={payablePayments[p.id]} + historyError={payableHistoryErrors[p.id]} + historyLoading={payableHistoryLoading.has(p.id)} + historyOpen={expandedPayableIds.has(p.id)} + onToggleHistory={() => onTogglePayableHistory(p.id)} onEdit={onEditPayable} onPay={onPayPayable} /> diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift index fa96dd1..277785c 100644 --- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift +++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift @@ -190,6 +190,43 @@ public struct PayableItem: Codable, Equatable, Identifiable, Sendable { } } +/// 历史还款返回上限:与 TS 侧 `PAYABLE_HISTORY_LIMIT` 对齐,集中在此处取值。 +public enum PayablePaymentHistory { + public static let limit = 60 +} + +/// 固定支出的一笔历史还款(/api/rpc/payables/getPayablePayments)。 +public struct PayablePaymentRecord: Codable, Sendable, Identifiable, Hashable { + public let id: String + public let payableId: String + /// 账期 'YYYY-MM' + public let period: String + public let amount: Double + /// 登记日期 'YYYY-MM-DD' + public let paidAt: String + public let note: String? + + enum CodingKeys: String, CodingKey { + case id + case payableId = "payable_id" + case period, amount + case paidAt = "paid_at" + case note + } + + public init( + id: String, payableId: String, period: String, + amount: Double, paidAt: String, note: String? = nil + ) { + self.id = id + self.payableId = payableId + self.period = period + self.amount = amount + self.paidAt = paidAt + self.note = note + } +} + /// 创建/编辑入参,对齐 Web `RecurringPayableInput`;id 由服务端生成。 public struct PayableDraft: Codable, Equatable, Sendable { public var name: String diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesRemoteService.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesRemoteService.swift index e412dc9..ae0d3a1 100644 --- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesRemoteService.swift +++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesRemoteService.swift @@ -62,6 +62,13 @@ public actor PayablesRemoteService { args: [AnyCodable(payableId), payload]) } + /// 某笔固定支出的历史还款(按账期倒序)。 + public func fetchPayments(payableId: String) async throws -> [PayablePaymentRecord] { + try await apiClient.rpc( + module: "payables", function: "getPayablePayments", + args: [AnyCodable(payableId)]) + } + public func delete(payableId: String) async throws { let _: EmptyAck = try await apiClient.rpc( module: "payables", function: "deleteRecurringPayable", diff --git a/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/PayableCurrencyFixtureTests.swift b/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/PayableCurrencyFixtureTests.swift index 108b8e7..48d9965 100644 --- a/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/PayableCurrencyFixtureTests.swift +++ b/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/PayableCurrencyFixtureTests.swift @@ -16,12 +16,15 @@ private struct PayableCurrencyFixtureFile: Codable { let expected: String? } + let paymentHistoryLimit: Int + let currencies: [CurrencyItem] let normalizationCases: [NormalizationCase] enum CodingKeys: String, CodingKey { case currencies case normalizationCases = "normalization_cases" + case paymentHistoryLimit = "payment_history_limit" } } @@ -41,6 +44,12 @@ struct PayableCurrencyFixtureTests { return try JSONDecoder().decode(PayableCurrencyFixtureFile.self, from: data) } + @Test("Payable payment history limit matches shared fixture") + func testPaymentHistoryLimitMatchesFixture() throws { + let fixtures = try loadFixtures() + #expect(PayablePaymentHistory.limit == fixtures.paymentHistoryLimit) + } + @Test("PayableCurrency cases, labels, and symbols match shared TS/Swift fixture") func testClosedCurrencySetMatchesFixture() throws { let fixtures = try loadFixtures() diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index 94438f0..4fdf632 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -119,6 +119,17 @@ public final class AppState { rates: rates, filter: filter, today: today) } } + /// 固定支出历史还款:按 payable id 缓存,展开时按需加载。 + public var payablePayments: [String: [PayablePaymentRecord]] = [:] + /// 已展开历史的固定支出。 + public var expandedPayableIds: Set = [] + /// 历史加载失败的固定支出(再次展开会重试)。 + public var payableHistoryErrors: Set = [] + /// 历史请求版本号:还款后递增,过期响应直接丢弃。 + private var payableHistoryRevision: [String: Int] = [:] + /// 刷新后待重取历史的已展开项:下一次展开交互时拉取。 + private var payableHistoryStale: Set = [] + public var payablesError: String? /// 盘库打不开、退到内存库时的可恢复提示(数据不持久化),由 UI 展示。 public var dbInitWarning: String? @@ -573,6 +584,11 @@ public final class AppState { dashboardRemoteErrors = [] payables = [] payablesError = nil + payablePayments = [:] + expandedPayableIds = [] + payableHistoryErrors = [] + payableHistoryRevision = [:] + payableHistoryStale = [] lastSyncError = nil // 401 会话过期不走完整 logout:per-user 快照靠 owner 记录在这里补清, // 否则下一个账号直接 login 时前任财务快照残留磁盘 @@ -634,6 +650,14 @@ public final class AppState { payables = items payablesError = nil + // 服务端列表已重取:先作废所有在途历史请求(否则其回调会把刷新前的旧数据写回), + // 再把已展开行标记为待重取,由视图按需拉取。 + for id in expandedPayableIds { + payableHistoryRevision[id] = (payableHistoryRevision[id] ?? 0) + 1 + } + payablePayments = [:] + payableHistoryErrors = [] + payableHistoryStale = expandedPayableIds // 空结果 = 用户删空了固定支出:移除快照(否则「删空后重启+离线」会复活已删条目); // 服务端瞬时异常返回空列表的窗口极窄且下次在线刷新即自愈,不值得为它保留陈旧快照。 @@ -760,6 +784,12 @@ public final class AppState { /// 登记固定支出当期还款,返回成功后刷新列表。 public func payPayable(_ item: PayableItem, amount: Double) async throws { _ = try await payablesService.pay(payableId: item.id, amount: amount) + // 新还款落库:递增版本号作废在途请求;已展开则立即重取,避免显示空的旧缓存 + payableHistoryRevision[item.id] = (payableHistoryRevision[item.id] ?? 0) + 1 + payablePayments[item.id] = nil + payableHistoryErrors.remove(item.id) + // 只刷新列表:refreshPayables 会清空历史缓存并标记 stale, + // 预取的结果必然被作废,交给视图按需重取 await refreshPayables() } @@ -776,8 +806,72 @@ public final class AppState { await refreshPayables() } + /// 展开/收起某笔固定支出的历史;首次展开才拉取,失败保留空列表供重试。 + public func togglePayableHistory(_ payableId: String) async { + if expandedPayableIds.contains(payableId) { + expandedPayableIds.remove(payableId) + return + } + expandedPayableIds.insert(payableId) + guard payablePayments[payableId] == nil else { return } + await loadPayableHistory(payableId) + } + + /// 该行历史是否需要重新拉取(刷新后清空缓存但保持展开)。 + public func isPayableHistoryStale(_ payableId: String) -> Bool { + payableHistoryStale.contains(payableId) + } + + /// 错误态点击「重试」:保持展开,直接重拉。 + public func retryPayableHistory(_ payableId: String) async { + expandedPayableIds.insert(payableId) + await loadPayableHistory(payableId) + } + + private func loadPayableHistory(_ payableId: String) async { + // 演示模式与 UI 测试不访问在线固定支出,历史同样跳过 + guard !UITestConfiguration.isEnabled, + !CommandLine.arguments.contains("--demo-mode") else { + payablePayments[payableId] = [] + return + } + let revision = (payableHistoryRevision[payableId] ?? 0) + 1 + payableHistoryRevision[payableId] = revision + // 重试在途:先清旧错误,UI 显示「加载中」而不是上次的失败文案 + payableHistoryErrors.remove(payableId) + do { + let records = try await payablesService.fetchPayments(payableId: payableId) + // 拉取在途期间发生还款会递增版本号,过期响应丢弃 + guard payableHistoryRevision[payableId] == revision else { return } + payablePayments[payableId] = records + payableHistoryErrors.remove(payableId) + payableHistoryStale.remove(payableId) + } catch is CancellationError { + // 视图取消(收起/离屏):不是失败,保持待重取状态 + guard payableHistoryRevision[payableId] == revision else { return } + payablePayments[payableId] = nil + payableHistoryStale.insert(payableId) + } catch let urlError as URLError where urlError.code == .cancelled { + guard payableHistoryRevision[payableId] == revision else { return } + payablePayments[payableId] = nil + payableHistoryStale.insert(payableId) + } catch { + guard payableHistoryRevision[payableId] == revision else { return } + // 保持「未加载」以便下次展开重试,并记录错误供 UI 展示; + // 同时清 stale,否则 stale 分支会反复自动重试形成死循环 + payablePayments[payableId] = nil + payableHistoryErrors.insert(payableId) + payableHistoryStale.remove(payableId) + } + } + public func deletePayable(_ item: PayableItem) async throws { try await payablesService.delete(payableId: item.id) + payablePayments[item.id] = nil + expandedPayableIds.remove(item.id) + payableHistoryErrors.remove(item.id) + payableHistoryRevision[item.id] = nil + payableHistoryStale.remove(item.id) await refreshPayables() } @@ -948,6 +1042,11 @@ public final class AppState { dashboardLoadError = nil payables = [] payablesError = nil + payablePayments = [:] + expandedPayableIds = [] + payableHistoryErrors = [] + payableHistoryRevision = [:] + payableHistoryStale = [] notificationScheduler.center.removeAllPendingNotificationRequests() watchSnapshots.clear() let emptySnapshot = WatchSnapshot( diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index 7e8eb66..a7b75bc 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -993,6 +993,8 @@ struct BillsView: View { .foregroundStyle(WCColors.textSecondary) } } + + payableHistorySection(payable) } .padding(16) .background(WCColors.surface, in: RoundedRectangle(cornerRadius: 16)) @@ -1016,6 +1018,98 @@ struct BillsView: View { .accessibilityIdentifier("bills.payable.row.\(payable.id)") } + /// 与服务端 PAYABLE_HISTORY_LIMIT 对齐:达到上限时改称「最近 N 笔」。 + private func payableHistoryLabel(_ records: [PayablePaymentRecord]?) -> String { + guard let records, !records.isEmpty else { return "历史还款" } + if records.count >= PayablePaymentHistory.limit { + return "最近 \(PayablePaymentHistory.limit) 笔还款" + } + return "历史还款 \(records.count) 笔" + } + + /// 固定支出历史还款:按钮常驻,展开才拉取;数据来自 AppState 缓存。 + @ViewBuilder + private func payableHistorySection(_ payable: PayableItem) -> some View { + let records = appState.payablePayments[payable.id] + let expanded = appState.expandedPayableIds.contains(payable.id) + let failed = appState.payableHistoryErrors.contains(payable.id) + + Divider().background(WCColors.border) + Button { + Task { await appState.togglePayableHistory(payable.id) } + } label: { + HStack { + Text(payableHistoryLabel(records)) + .font(.caption.weight(.semibold)) + .foregroundStyle(WCColors.textSecondary) + Spacer() + Text(expanded ? "收起" : "展开") + .font(.caption.weight(.semibold)) + .foregroundStyle(WCColors.primaryAccent) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("bills.payable.history.\(payable.id)") + + if expanded { + if failed { + // 失败态优先:失败时 records 恒为 nil,先判 nil 会让错误永远不可见 + Button { + Task { await appState.retryPayableHistory(payable.id) } + } label: { + Text("加载失败,点此重试") + .font(.caption2.weight(.semibold)) + .foregroundStyle(WCColors.dangerInk) + } + .buttonStyle(.plain) + } else if appState.isPayableHistoryStale(payable.id) { + // 刷新后缓存已清空但行仍展开:手动触发重取,避免 .task(id:) 不重触发的死锁 + Button { + Task { await appState.retryPayableHistory(payable.id) } + } label: { + Text("点击加载最新历史") + .font(.caption2.weight(.semibold)) + .foregroundStyle(WCColors.primaryAccent) + } + .buttonStyle(.plain) + } else if records == nil { + Text("加载中…") + .font(.caption2) + .foregroundStyle(WCColors.textSecondary) + } else if let records { + if records.isEmpty { + Text("还没有历史还款记录") + .font(.caption2) + .foregroundStyle(WCColors.textSecondary) + } else { + VStack(spacing: 6) { + ForEach(records) { record in + HStack { + Text(record.period) + .font(.caption2) + .foregroundStyle(WCColors.textSecondary) + Text(record.paidAt) + .font(.caption2) + .foregroundStyle(WCColors.textSecondary) + if let note = record.note, !note.isEmpty { + Text(note) + .font(.caption2) + .foregroundStyle(WCColors.textSecondary) + .lineLimit(1) + } + Spacer() + Text(DashboardMoney.format(record.amount, currency: payable.currency)) + .font(.caption2.weight(.semibold)) + .foregroundStyle(WCColors.textPrimary) + } + } + } + } + } + } + } + private func payableStatusBadge(_ payable: PayableItem) -> some View { HStack(spacing: 4) { if payable.isSettled || payable.remainingAmount <= 0.01 { diff --git a/lib/__tests__/payable-bank.test.ts b/lib/__tests__/payable-bank.test.ts index 3edb494..63a7c75 100644 --- a/lib/__tests__/payable-bank.test.ts +++ b/lib/__tests__/payable-bank.test.ts @@ -1,8 +1,15 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { createOpportunityDb, type SqliteD1 } from './helpers/sqlite-d1' import { setDb } from '../db/client' +import currencyFixtures from '../../shared/fixtures/payable-currencies.json' +import { PAYABLE_HISTORY_LIMIT } from '../api/payables.shared' import { RpcDomainError } from '../api/errors' -import { createRecurringPayable, updateRecurringPayable } from '../api/payables.server' +import { + createRecurringPayable, + updateRecurringPayable, + payRecurringPayable, + getPayablePayments, +} from '../api/payables.server' describe('recurring payable bank attribution', () => { let db: SqliteD1 | null = null @@ -62,3 +69,57 @@ describe('recurring payable bank attribution', () => { ).rejects.toBeInstanceOf(RpcDomainError) }) }) + +describe('recurring payable payment history', () => { + it('登记还款后可按账期倒序读取历史记录', async () => { + const db = createOpportunityDb() + db.exec("INSERT INTO users (id, email, password_hash) VALUES ('u1', 'u1@example.com', 'hash')") + setDb(db as unknown as D1Database) + + const payable = await createRecurringPayable({ + created_by: 'u1', + name: '房贷', + category: 'loan', + amount: 4500, + currency: 'CNY', + due_day: 5, + }) + await payRecurringPayable(payable.id, 4500, '十月') + + const records = await getPayablePayments(payable.id) + expect(records.length).toBe(1) + expect(records[0]).toMatchObject({ + payable_id: payable.id, + period: payable.period, + amount: 4500, + note: '十月', + }) + db.close() + }) + + it('无记录返回空数组;非法 ID 报 VALIDATION_FAILED', async () => { + const db = createOpportunityDb() + db.exec("INSERT INTO users (id, email, password_hash) VALUES ('u1', 'u1@example.com', 'hash')") + setDb(db as unknown as D1Database) + const payable = await createRecurringPayable({ + created_by: 'u1', + name: '房租', + category: 'rent', + amount: 2000, + currency: 'CNY', + due_day: 10, + }) + await expect(getPayablePayments(payable.id)).resolves.toEqual([]) + await expect(getPayablePayments('')).rejects.toMatchObject({ + name: 'RpcDomainError', + code: 'VALIDATION_FAILED', + }) + db.close() + }) +}) + +describe('shared fixture: payable payment history limit', () => { + it('TS 常量与 shared fixture 一致', () => { + expect(PAYABLE_HISTORY_LIMIT).toBe(currencyFixtures.payment_history_limit) + }) +}) diff --git a/lib/api/payables.server.ts b/lib/api/payables.server.ts index cbf78aa..fef215c 100644 --- a/lib/api/payables.server.ts +++ b/lib/api/payables.server.ts @@ -5,7 +5,11 @@ import { query, queryOne, execute, uuid, now } from '../db' import { payablePeriodOf, payableDueDate, nextPayablePeriodOf, diffInCalendarDays } from '../utils' -import { normalizePayableCurrency, type PayableCategory } from './payables.shared' +import { + PAYABLE_HISTORY_LIMIT, + normalizePayableCurrency, + type PayableCategory, +} from './payables.shared' import { RpcDomainError } from './errors' export type { PayableCategory } from './payables.shared' @@ -121,6 +125,33 @@ export async function resolveDisplayPeriod( return { period: current, paidAmount: paidCurrent } } +export interface PayablePaymentRecord { + id: string + payable_id: string + period: string + amount: number + paid_at: string + note: string | null + created_at: string +} + +/** 某个固定支出的历史还款记录(按账期倒序,同期按登记时间倒序)。 */ +export async function getPayablePayments(payableId: string): Promise { + if (typeof payableId !== 'string' || !payableId.trim()) { + throw new RpcDomainError('VALIDATION_FAILED', '缺少合法的固定支出 ID') + } + const { data, error } = await query( + `SELECT id, payable_id, period, amount, paid_at, note, created_at + FROM recurring_payable_payments + WHERE payable_id = ? + ORDER BY period DESC, created_at DESC + LIMIT ?`, + [payableId, PAYABLE_HISTORY_LIMIT] + ) + if (error) throw new Error(error.message) + return data ?? [] +} + /** 账单页用:当前生效的应付事项 + 当期状态。 */ export async function getRecurringPayables( userId: string, diff --git a/lib/api/payables.shared.ts b/lib/api/payables.shared.ts index e10e2b9..40de021 100644 --- a/lib/api/payables.shared.ts +++ b/lib/api/payables.shared.ts @@ -64,3 +64,6 @@ export function normalizePayableCurrency(value: unknown): PayableCurrency | null export function isPayableCurrency(value: unknown): value is PayableCurrency { return typeof value === 'string' && (PAYABLE_CURRENCIES as readonly string[]).includes(value) } + +/** 历史还款返回上限:服务端查询与前端「最近 N 笔」文案共用同一常量。 */ +export const PAYABLE_HISTORY_LIMIT = 60 diff --git a/lib/api/payables.ts b/lib/api/payables.ts index 52d7596..d5862d5 100644 --- a/lib/api/payables.ts +++ b/lib/api/payables.ts @@ -7,6 +7,7 @@ export type { RecurringPayableInput, CreateRecurringPayableInput, PayableWithStatus, + PayablePaymentRecord, } from './payables.server' // 纯类型与纯函数走 .shared,避免把服务端依赖带进浏览器包。 @@ -18,6 +19,7 @@ export { PAYABLE_CURRENCY_LABELS, isPayableCurrency, normalizePayableCurrency, + PAYABLE_HISTORY_LIMIT, } from './payables.shared' export function getRecurringPayables(...args: Parameters) { @@ -35,3 +37,6 @@ export function deleteRecurringPayable(...args: Parameters) { return callRpc('payables', 'payRecurringPayable', ...args) } +export function getPayablePayments(...args: Parameters) { + return callRpc('payables', 'getPayablePayments', ...args) +} diff --git a/lib/api/registry.ts b/lib/api/registry.ts index 11a4f92..8bc2a13 100644 --- a/lib/api/registry.ts +++ b/lib/api/registry.ts @@ -272,6 +272,7 @@ export const RPC_REGISTRY: Record> = { updateRecurringPayable: { impl: payablesServer.updateRecurringPayable, memberGuard: (args, ctx) => assertPayableAccess(args[0], ctx) }, deleteRecurringPayable: { impl: payablesServer.deleteRecurringPayable, memberGuard: (args, ctx) => assertPayableAccess(args[0], ctx) }, payRecurringPayable: { impl: payablesServer.payRecurringPayable, memberGuard: (args, ctx) => assertPayableAccess(args[0], ctx) }, + getPayablePayments: { impl: payablesServer.getPayablePayments, memberGuard: (args, ctx) => assertPayableAccess(args[0], ctx) }, }, opportunities: { // Session actor is prepended by the route; each impl re-authorizes via diff --git a/shared/fixtures/payable-currencies.json b/shared/fixtures/payable-currencies.json index b0e989d..6dfd737 100644 --- a/shared/fixtures/payable-currencies.json +++ b/shared/fixtures/payable-currencies.json @@ -5,31 +5,78 @@ "code": "CNY", "label": "人民币 CNY", "symbol": "¥", - "aliases": ["人民币"] + "aliases": [ + "人民币" + ] }, { "code": "USD", "label": "美元 USD", "symbol": "US$", - "aliases": ["美元"] + "aliases": [ + "美元" + ] }, { "code": "HKD", "label": "港币 HKD", "symbol": "HK$", - "aliases": ["港币"] + "aliases": [ + "港币" + ] } ], "normalization_cases": [ - { "id": "cny_canonical", "raw": "CNY", "expected": "CNY" }, - { "id": "usd_lowercase_trimmed", "raw": " usd ", "expected": "USD" }, - { "id": "hkd_mixed_case", "raw": "\thKd\n", "expected": "HKD" }, - { "id": "cny_alias", "raw": " 人民币 ", "expected": "CNY" }, - { "id": "usd_alias", "raw": "美元", "expected": "USD" }, - { "id": "hkd_alias", "raw": " 港币 ", "expected": "HKD" }, - { "id": "unknown_eur_preserved", "raw": "EUR", "expected": null }, - { "id": "unknown_lowercase_eur", "raw": " eur ", "expected": null }, - { "id": "unknown_rmb_not_guessed", "raw": "RMB", "expected": null }, - { "id": "empty_rejected", "raw": " ", "expected": null } - ] + { + "id": "cny_canonical", + "raw": "CNY", + "expected": "CNY" + }, + { + "id": "usd_lowercase_trimmed", + "raw": " usd ", + "expected": "USD" + }, + { + "id": "hkd_mixed_case", + "raw": "\thKd\n", + "expected": "HKD" + }, + { + "id": "cny_alias", + "raw": " 人民币 ", + "expected": "CNY" + }, + { + "id": "usd_alias", + "raw": "美元", + "expected": "USD" + }, + { + "id": "hkd_alias", + "raw": " 港币 ", + "expected": "HKD" + }, + { + "id": "unknown_eur_preserved", + "raw": "EUR", + "expected": null + }, + { + "id": "unknown_lowercase_eur", + "raw": " eur ", + "expected": null + }, + { + "id": "unknown_rmb_not_guessed", + "raw": "RMB", + "expected": null + }, + { + "id": "empty_rejected", + "raw": " ", + "expected": null + } + ], + "payment_history_limit": 60 }