From d01da29a6b4898670f52c1849ff39648266a2255 Mon Sep 17 00:00:00 2001 From: hubo Date: Tue, 3 Nov 2026 17:27:32 +0800 Subject: [PATCH 01/10] feat(payables): payment history and move missing-statement notice to card end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - new payables.getPayablePayments (member-guarded read of recurring_payable_payments, ordered by period desc) - web payable card gains a collapsible 历史还款 list loaded on first expand; iOS card gains the same section backed by an AppState cache that is invalidated after a new payment - missing-statement reminder moves from the cycle block to the bottom of the card so bill data reads first - tests: history read after payment, empty list, invalid id --- app/(mobile)/bills/page.tsx | 31 +++++++++- .../__tests__/BillReviewRegressions.test.tsx | 4 +- components/mobile/PayableList.tsx | 54 ++++++++++++++++- components/obsidian/BillsView.tsx | 23 ++++++-- .../Network/PayablesModels.swift | 32 ++++++++++ .../Network/PayablesRemoteService.swift | 7 +++ ios/WorldCredit/AppState.swift | 23 ++++++++ ios/WorldCredit/Views/BillsView.swift | 59 +++++++++++++++++++ lib/__tests__/payable-bank.test.ts | 55 ++++++++++++++++- lib/api/payables.server.ts | 26 ++++++++ lib/api/payables.ts | 4 ++ lib/api/registry.ts | 1 + 12 files changed, 308 insertions(+), 11 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index a3b2e85..53e660c 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -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, @@ -92,6 +93,9 @@ export default function BillsPage() { // 固定支出(房租/贷款等按月应付) const [payables, setPayables] = useState([]) const [payableFormOpen, setPayableFormOpen] = useState(false) + // 固定支出历史还款:按需加载,展开一次后缓存 + const [payablePayments, setPayablePayments] = useState>({}) + const [expandedPayableIds, setExpandedPayableIds] = useState>(new Set()) const [editingPayable, setEditingPayable] = useState(null) const [celebrationNotice, setCelebrationNotice] = useState<{ open: boolean; message: string }>({ @@ -426,6 +430,28 @@ export default function BillsPage() { } } + /** 展开/收起固定支出历史:首次展开才拉取该笔记录。 */ + const handleTogglePayableHistory = useCallback( + async (payableId: string) => { + const willOpen = !expandedPayableIds.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 + try { + const records = await getPayablePayments(payableId) + setPayablePayments(prev => ({ ...prev, [payableId]: records })) + } catch { + // 拉取失败不阻断卡片:保留空历史,用户可再次展开重试 + setPayablePayments(prev => ({ ...prev, [payableId]: [] })) + } + }, + [expandedPayableIds, payablePayments] + ) + // 收起态摘要:把当前筛选、分组与排序压成一行可读文本 const filterSummary = useMemo(() => { const statusText = @@ -506,6 +532,9 @@ export default function BillsPage() { onRetry={() => loadData()} onEmptySync={handleSync} payables={filteredPayables} + payablePayments={payablePayments} + 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..deea730 100644 --- a/components/__tests__/BillReviewRegressions.test.tsx +++ b/components/__tests__/BillReviewRegressions.test.tsx @@ -298,7 +298,9 @@ 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: {}, 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..7eedba4 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -1,7 +1,11 @@ 'use client' import { useState } from 'react' -import { categoryLabel, type PayableWithStatus } from '@/lib/api/payables' +import { + categoryLabel, + 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,6 +15,11 @@ export interface PayableRowProps { payable: PayableWithStatus /** 归属持卡人姓名;未指定归属时不显示 */ holderName?: string + /** 历史还款记录(按账期倒序);未加载时不显示 */ + payments?: PayablePaymentRecord[] + /** 是否展开历史还款 */ + historyOpen?: boolean + onToggleHistory?: () => void onEdit: (payable: PayableWithStatus) => void onPay: (payable: PayableWithStatus) => void } @@ -26,7 +35,15 @@ export interface PayableRowProps { * 滚动模型(服务端 resolveDisplayPeriod)保证任一时刻卡片只呈现一期: * 「已登记」只可能出现在待出账态,待还款态一定是可登记付款的未付期。 */ -export function PayableRow({ payable: p, holderName, onEdit, onPay }: PayableRowProps) { +export function PayableRow({ + payable: p, + holderName, + payments, + historyOpen = false, + onToggleHistory, + onEdit, + onPay, +}: PayableRowProps) { const [copiedAccount, setCopiedAccount] = useState(false) const paid = p.status === 'paid' const overdue = p.status === 'overdue' @@ -162,6 +179,39 @@ export function PayableRow({ payable: p, holderName, onEdit, onPay }: PayableRow {detail} + + {(payments?.length ?? 0) > 0 && ( +
+ + {historyOpen && ( +
    + {payments!.map(record => ( +
  • + {record.period} + + {record.paid_at.slice(5)} + {record.note ? ' · ' + record.note : ''} + + + {currencySymbol(p.currency)} + {Number(record.amount).toLocaleString()} + +
  • + ))} +
+ )} +
+ )} ) } diff --git a/components/obsidian/BillsView.tsx b/components/obsidian/BillsView.tsx index 798b4dd..5f847ee 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,11 @@ export interface BillsViewProps { onRetry: () => void onEmptySync: () => void payables: PayableWithStatus[] + /** 各固定支出的历史还款记录,key = payable id */ + payablePayments: Record + /** 已展开历史的 payable id */ + expandedPayableIds: Set + onTogglePayableHistory: (id: string) => void onEditPayable: (p: PayableWithStatus) => void onPayPayable: (p: PayableWithStatus) => void cards: CardWithBillsSummary[] @@ -276,11 +281,6 @@ function BillCard({ · 下期还款日 {format(new Date(item.nextDueDate), 'MM-dd')}

- {missingStatement && ( -

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

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

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

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

+ )} ) } @@ -386,6 +393,7 @@ export function BillsView(vm: BillsViewProps) { selectedTag, onSelectedTag, holderTags, bankTags, loading, loadError, onRetry, onEmptySync, payables, cards, allCards, holderMap, bankGroups, onOpenPayment, onManualAmount, onAddBill, sortMode, onSortMode, + payablePayments, expandedPayableIds, onTogglePayableHistory, onEditPayable, onPayPayable, } = vm @@ -444,6 +452,9 @@ export function BillsView(vm: BillsViewProps) { key={`payable-${p.id}`} payable={p} holderName={p.holder_id ? holderMap[p.holder_id] : undefined} + payments={payablePayments[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..c2ccda5 100644 --- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift +++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift @@ -190,6 +190,38 @@ public struct PayableItem: Codable, Equatable, Identifiable, Sendable { } } +/// 固定支出的一笔历史还款(/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/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index 94438f0..f385c31 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -119,6 +119,11 @@ public final class AppState { rates: rates, filter: filter, today: today) } } + /// 固定支出历史还款:按 payable id 缓存,展开时按需加载。 + public var payablePayments: [String: [PayablePaymentRecord]] = [:] + /// 已展开历史的固定支出。 + public var expandedPayableIds: Set = [] + public var payablesError: String? /// 盘库打不开、退到内存库时的可恢复提示(数据不持久化),由 UI 展示。 public var dbInitWarning: String? @@ -760,6 +765,8 @@ public final class AppState { /// 登记固定支出当期还款,返回成功后刷新列表。 public func payPayable(_ item: PayableItem, amount: Double) async throws { _ = try await payablesService.pay(payableId: item.id, amount: amount) + // 新还款落库后清掉该笔历史缓存,下次展开看到最新记录 + payablePayments[item.id] = nil await refreshPayables() } @@ -776,6 +783,22 @@ 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 } + do { + payablePayments[payableId] = try await payablesService.fetchPayments(payableId: payableId) + } catch { + // 拉取失败不阻断卡片展示;再次收起/展开会重试 + payablePayments[payableId] = [] + } + } + public func deletePayable(_ item: PayableItem) async throws { try await payablesService.delete(payableId: item.id) await refreshPayables() diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index 7e8eb66..5c5d758 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,63 @@ struct BillsView: View { .accessibilityIdentifier("bills.payable.row.\(payable.id)") } + /// 固定支出历史还款:默认收起,展开才拉取;数据来自 AppState 缓存。 + @ViewBuilder + private func payableHistorySection(_ payable: PayableItem) -> some View { + let records = appState.payablePayments[payable.id] ?? [] + let expanded = appState.expandedPayableIds.contains(payable.id) + if !records.isEmpty || expanded { + Divider().background(WCColors.border) + Button { + Task { await appState.togglePayableHistory(payable.id) } + } label: { + HStack { + Text(records.isEmpty ? "历史还款" : "历史还款 \(records.count) 笔") + .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 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..6492107 100644 --- a/lib/__tests__/payable-bank.test.ts +++ b/lib/__tests__/payable-bank.test.ts @@ -2,7 +2,12 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { createOpportunityDb, type SqliteD1 } from './helpers/sqlite-d1' import { setDb } from '../db/client' 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 +67,51 @@ 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() + }) +}) diff --git a/lib/api/payables.server.ts b/lib/api/payables.server.ts index cbf78aa..d77f0be 100644 --- a/lib/api/payables.server.ts +++ b/lib/api/payables.server.ts @@ -121,6 +121,32 @@ 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`, + [payableId] + ) + if (error) throw new Error(error.message) + return data ?? [] +} + /** 账单页用:当前生效的应付事项 + 当期状态。 */ export async function getRecurringPayables( userId: string, diff --git a/lib/api/payables.ts b/lib/api/payables.ts index 52d7596..0b2b9e6 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,避免把服务端依赖带进浏览器包。 @@ -35,3 +36,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 From c414d94beabc8c2bcd28e4c08bd6a9fddedfb8ea Mon Sep 17 00:00:00 2001 From: hubo Date: Tue, 3 Nov 2026 18:10:21 +0800 Subject: [PATCH 02/10] fix(payables): make history reachable and invalidate it correctly - history section is always visible; loading / empty / failed states are explicit instead of hiding the toggle behind "has records" - web keeps undefined on failure so re-expanding retries, shows the error, and drops the cache after a new payment - iOS keeps nil+error on failure, guards in-flight responses with a revision counter, refetches when the section is open and a payment lands, and clears caches on logout/session expiry/delete - aria-expanded on the toggle; no non-null assertions --- app/(mobile)/bills/page.tsx | 24 +++++++- .../__tests__/BillReviewRegressions.test.tsx | 2 +- components/mobile/PayableList.tsx | 56 +++++++++++-------- components/obsidian/BillsView.tsx | 4 +- ios/WorldCredit/AppState.swift | 41 ++++++++++++-- ios/WorldCredit/Views/BillsView.swift | 50 ++++++++++------- 6 files changed, 126 insertions(+), 51 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index 53e660c..4f54364 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -96,6 +96,7 @@ export default function BillsPage() { // 固定支出历史还款:按需加载,展开一次后缓存 const [payablePayments, setPayablePayments] = useState>({}) const [expandedPayableIds, setExpandedPayableIds] = useState>(new Set()) + const [payableHistoryErrors, setPayableHistoryErrors] = useState>({}) const [editingPayable, setEditingPayable] = useState(null) const [celebrationNotice, setCelebrationNotice] = useState<{ open: boolean; message: string }>({ @@ -420,6 +421,13 @@ export default function BillsPage() { const handlePayPayable = async (payable: PayableWithStatus) => { try { await payRecurringPayable(payable.id, payable.amount) + // 新还款落库:清掉该笔历史缓存,展开时重新拉取 + setPayablePayments(prev => { + if (!(payable.id in prev)) return prev + const next = { ...prev } + delete next[payable.id] + return next + }) setCelebrationNotice({ open: true, message: `🎉 已登记「${payable.name}」本期付款 ${currencySymbol(payable.currency)}${payable.amount.toLocaleString()}`, @@ -444,9 +452,18 @@ export default function BillsPage() { try { const records = await getPayablePayments(payableId) setPayablePayments(prev => ({ ...prev, [payableId]: records })) - } catch { - // 拉取失败不阻断卡片:保留空历史,用户可再次展开重试 - setPayablePayments(prev => ({ ...prev, [payableId]: [] })) + setPayableHistoryErrors(prev => { + if (!prev[payableId]) return prev + const next = { ...prev } + delete next[payableId] + return next + }) + } catch (err) { + // 保持未加载状态:再次展开会重试;错误就地展示 + setPayableHistoryErrors(prev => ({ + ...prev, + [payableId]: err instanceof Error ? err.message : '历史还款加载失败', + })) } }, [expandedPayableIds, payablePayments] @@ -533,6 +550,7 @@ export default function BillsPage() { onEmptySync={handleSync} payables={filteredPayables} payablePayments={payablePayments} + payableHistoryErrors={payableHistoryErrors} expandedPayableIds={expandedPayableIds} onTogglePayableHistory={handleTogglePayableHistory} onEditPayable={p => { setEditingPayable(p); setPayableFormOpen(true) }} diff --git a/components/__tests__/BillReviewRegressions.test.tsx b/components/__tests__/BillReviewRegressions.test.tsx index deea730..925ecf2 100644 --- a/components/__tests__/BillReviewRegressions.test.tsx +++ b/components/__tests__/BillReviewRegressions.test.tsx @@ -299,7 +299,7 @@ function makeBillsViewFixture(): { props: BillsViewProps; unpaid: BillDashboardI holderTags: [], bankTags: [], loading: false, loadError: null, onRetry: vi.fn(), onEmptySync: vi.fn(), payables: [], onEditPayable: vi.fn(), onPayPayable: vi.fn(), - payablePayments: {}, expandedPayableIds: new Set(), + payablePayments: {}, payableHistoryErrors: {}, 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 7eedba4..d17faa9 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -15,8 +15,10 @@ export interface PayableRowProps { payable: PayableWithStatus /** 归属持卡人姓名;未指定归属时不显示 */ holderName?: string - /** 历史还款记录(按账期倒序);未加载时不显示 */ + /** 历史还款记录(按账期倒序);undefined = 尚未加载 */ payments?: PayablePaymentRecord[] + /** 历史加载失败提示;为空表示无错误 */ + historyError?: string /** 是否展开历史还款 */ historyOpen?: boolean onToggleHistory?: () => void @@ -39,6 +41,7 @@ export function PayableRow({ payable: p, holderName, payments, + historyError, historyOpen = false, onToggleHistory, onEdit, @@ -180,35 +183,44 @@ export function PayableRow({ {detail} - {(payments?.length ?? 0) > 0 && ( + {onToggleHistory && (
{historyOpen && ( -
    - {payments!.map(record => ( -
  • - {record.period} - - {record.paid_at.slice(5)} - {record.note ? ' · ' + record.note : ''} - - - {currencySymbol(p.currency)} - {Number(record.amount).toLocaleString()} - -
  • - ))} -
+ historyError ? ( +

{historyError}

+ ) : payments === undefined ? ( +

加载中…

+ ) : payments.length === 0 ? ( +

还没有历史还款记录

+ ) : ( +
    + {payments.map(record => ( +
  • + {record.period} + + {record.paid_at.slice(5)} + {record.note ? ' · ' + record.note : ''} + + + {currencySymbol(p.currency)} + {Number(record.amount).toLocaleString()} + +
  • + ))} +
+ ) )}
)} diff --git a/components/obsidian/BillsView.tsx b/components/obsidian/BillsView.tsx index 5f847ee..84eac9f 100644 --- a/components/obsidian/BillsView.tsx +++ b/components/obsidian/BillsView.tsx @@ -95,6 +95,7 @@ export interface BillsViewProps { payables: PayableWithStatus[] /** 各固定支出的历史还款记录,key = payable id */ payablePayments: Record + payableHistoryErrors: Record /** 已展开历史的 payable id */ expandedPayableIds: Set onTogglePayableHistory: (id: string) => void @@ -393,7 +394,7 @@ export function BillsView(vm: BillsViewProps) { selectedTag, onSelectedTag, holderTags, bankTags, loading, loadError, onRetry, onEmptySync, payables, cards, allCards, holderMap, bankGroups, onOpenPayment, onManualAmount, onAddBill, sortMode, onSortMode, - payablePayments, expandedPayableIds, onTogglePayableHistory, + payablePayments, payableHistoryErrors, expandedPayableIds, onTogglePayableHistory, onEditPayable, onPayPayable, } = vm @@ -453,6 +454,7 @@ export function BillsView(vm: BillsViewProps) { payable={p} holderName={p.holder_id ? holderMap[p.holder_id] : undefined} payments={payablePayments[p.id]} + historyError={payableHistoryErrors[p.id]} historyOpen={expandedPayableIds.has(p.id)} onToggleHistory={() => onTogglePayableHistory(p.id)} onEdit={onEditPayable} diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index f385c31..fa6e900 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -123,6 +123,10 @@ public final class AppState { public var payablePayments: [String: [PayablePaymentRecord]] = [:] /// 已展开历史的固定支出。 public var expandedPayableIds: Set = [] + /// 历史加载失败的固定支出(再次展开会重试)。 + public var payableHistoryErrors: Set = [] + /// 历史请求版本号:还款后递增,过期响应直接丢弃。 + private var payableHistoryRevision: [String: Int] = [:] public var payablesError: String? /// 盘库打不开、退到内存库时的可恢复提示(数据不持久化),由 UI 展示。 @@ -578,6 +582,10 @@ public final class AppState { dashboardRemoteErrors = [] payables = [] payablesError = nil + payablePayments = [:] + expandedPayableIds = [] + payableHistoryErrors = [] + payableHistoryRevision = [:] lastSyncError = nil // 401 会话过期不走完整 logout:per-user 快照靠 owner 记录在这里补清, // 否则下一个账号直接 login 时前任财务快照残留磁盘 @@ -765,8 +773,13 @@ 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) + if expandedPayableIds.contains(item.id) { + await loadPayableHistory(item.id) + } await refreshPayables() } @@ -791,16 +804,32 @@ public final class AppState { } expandedPayableIds.insert(payableId) guard payablePayments[payableId] == nil else { return } + await loadPayableHistory(payableId) + } + + private func loadPayableHistory(_ payableId: String) async { + let revision = (payableHistoryRevision[payableId] ?? 0) + 1 + payableHistoryRevision[payableId] = revision do { - payablePayments[payableId] = try await payablesService.fetchPayments(payableId: payableId) + let records = try await payablesService.fetchPayments(payableId: payableId) + // 拉取在途期间发生还款会递增版本号,过期响应丢弃 + guard payableHistoryRevision[payableId] == revision else { return } + payablePayments[payableId] = records + payableHistoryErrors.remove(payableId) } catch { - // 拉取失败不阻断卡片展示;再次收起/展开会重试 - payablePayments[payableId] = [] + guard payableHistoryRevision[payableId] == revision else { return } + // 保持「未加载」以便下次展开重试,并记录错误供 UI 展示 + payablePayments[payableId] = nil + payableHistoryErrors.insert(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 await refreshPayables() } @@ -971,6 +1000,10 @@ public final class AppState { dashboardLoadError = nil payables = [] payablesError = nil + payablePayments = [:] + expandedPayableIds = [] + payableHistoryErrors = [] + payableHistoryRevision = [:] notificationScheduler.center.removeAllPendingNotificationRequests() watchSnapshots.clear() let emptySnapshot = WatchSnapshot( diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index 5c5d758..65775a9 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -1018,31 +1018,37 @@ struct BillsView: View { .accessibilityIdentifier("bills.payable.row.\(payable.id)") } - /// 固定支出历史还款:默认收起,展开才拉取;数据来自 AppState 缓存。 + /// 固定支出历史还款:按钮常驻,展开才拉取;数据来自 AppState 缓存。 @ViewBuilder private func payableHistorySection(_ payable: PayableItem) -> some View { - let records = appState.payablePayments[payable.id] ?? [] + let records = appState.payablePayments[payable.id] let expanded = appState.expandedPayableIds.contains(payable.id) - if !records.isEmpty || expanded { - Divider().background(WCColors.border) - Button { - Task { await appState.togglePayableHistory(payable.id) } - } label: { - HStack { - Text(records.isEmpty ? "历史还款" : "历史还款 \(records.count) 笔") - .font(.caption.weight(.semibold)) - .foregroundStyle(WCColors.textSecondary) - Spacer() - Text(expanded ? "收起" : "展开") - .font(.caption.weight(.semibold)) - .foregroundStyle(WCColors.primaryAccent) - } - .contentShape(Rectangle()) + let failed = appState.payableHistoryErrors.contains(payable.id) + + Divider().background(WCColors.border) + Button { + Task { await appState.togglePayableHistory(payable.id) } + } label: { + HStack { + Text(records.map { "历史还款 \($0.count) 笔" } ?? "历史还款") + .font(.caption.weight(.semibold)) + .foregroundStyle(WCColors.textSecondary) + Spacer() + Text(expanded ? "收起" : "展开") + .font(.caption.weight(.semibold)) + .foregroundStyle(WCColors.primaryAccent) } - .buttonStyle(.plain) - .accessibilityIdentifier("bills.payable.history.\(payable.id)") + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("bills.payable.history.\(payable.id)") - if expanded { + if expanded { + if failed { + Text("历史还款加载失败,请再次展开重试") + .font(.caption2) + .foregroundStyle(WCColors.dangerInk) + } else if let records { if records.isEmpty { Text("还没有历史还款记录") .font(.caption2) @@ -1071,6 +1077,10 @@ struct BillsView: View { } } } + } else { + Text("加载中…") + .font(.caption2) + .foregroundStyle(WCColors.textSecondary) } } } From d09fd3891e4ab84d9ca2375ffc12af5b33c455a9 Mon Sep 17 00:00:00 2001 From: hubo Date: Tue, 3 Nov 2026 18:30:55 +0800 Subject: [PATCH 03/10] fix(payables): refetch open history after payment and tidy states MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - web refetches immediately when the row is expanded, so it no longer sticks on 加载中 after a new payment - history block renders via an explicit function (loading/failed/empty/list) instead of nested ternaries - server caps history at 60 rows - iOS runs the history refetch and list refresh concurrently --- app/(mobile)/bills/page.tsx | 13 +++++- components/mobile/PayableList.tsx | 66 ++++++++++++++++++------------- ios/WorldCredit/AppState.swift | 9 +++-- lib/api/payables.server.ts | 3 +- 4 files changed, 57 insertions(+), 34 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index 4f54364..10d269b 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -421,13 +421,24 @@ export default function BillsPage() { const handlePayPayable = async (payable: PayableWithStatus) => { try { await payRecurringPayable(payable.id, payable.amount) - // 新还款落库:清掉该笔历史缓存,展开时重新拉取 + // 新还款落库:清掉该笔历史缓存;若当时正展开则立即重取,避免停在「加载中」 setPayablePayments(prev => { if (!(payable.id in prev)) return prev const next = { ...prev } delete next[payable.id] return next }) + if (expandedPayableIds.has(payable.id)) { + try { + const records = await getPayablePayments(payable.id) + setPayablePayments(prev => ({ ...prev, [payable.id]: records })) + } catch (err) { + setPayableHistoryErrors(prev => ({ + ...prev, + [payable.id]: err instanceof Error ? err.message : '历史还款加载失败', + })) + } + } setCelebrationNotice({ open: true, message: `🎉 已登记「${payable.name}」本期付款 ${currencySymbol(payable.currency)}${payable.amount.toLocaleString()}`, diff --git a/components/mobile/PayableList.tsx b/components/mobile/PayableList.tsx index d17faa9..b3af87a 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -37,6 +37,43 @@ export interface PayableRowProps { * 滚动模型(服务端 resolveDisplayPeriod)保证任一时刻卡片只呈现一期: * 「已登记」只可能出现在待出账态,待还款态一定是可登记付款的未付期。 */ +/** 历史还款展开区:加载中 / 失败 / 空 / 列表四态,避免嵌套三元。 */ +function renderPayableHistory( + payments: PayablePaymentRecord[] | undefined, + historyError: string | undefined, + currency: string +) { + if (historyError) { + return

{historyError}

+ } + if (payments === undefined) { + return

加载中…

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

还没有历史还款记录

+ } + return ( +
    + {payments.map(record => ( +
  • + {record.period} + + {record.paid_at.slice(5)} + {record.note ? ' · ' + record.note : ''} + + + {currencySymbol(currency)} + {Number(record.amount).toLocaleString()} + +
  • + ))} +
+ ) +} + export function PayableRow({ payable: p, holderName, @@ -194,34 +231,7 @@ export function PayableRow({ 历史还款{payments && payments.length > 0 ? ` ${payments.length} 笔` : ''} {historyOpen ? '收起' : '展开'} - {historyOpen && ( - historyError ? ( -

{historyError}

- ) : payments === undefined ? ( -

加载中…

- ) : payments.length === 0 ? ( -

还没有历史还款记录

- ) : ( -
    - {payments.map(record => ( -
  • - {record.period} - - {record.paid_at.slice(5)} - {record.note ? ' · ' + record.note : ''} - - - {currencySymbol(p.currency)} - {Number(record.amount).toLocaleString()} - -
  • - ))} -
- ) - )} + {historyOpen && renderPayableHistory(payments, historyError, p.currency)} )} diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index fa6e900..a7fe437 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -777,10 +777,11 @@ public final class AppState { payableHistoryRevision[item.id] = (payableHistoryRevision[item.id] ?? 0) + 1 payablePayments[item.id] = nil payableHistoryErrors.remove(item.id) - if expandedPayableIds.contains(item.id) { - await loadPayableHistory(item.id) - } - await refreshPayables() + // 历史重取与列表刷新互不依赖,并发执行减少一次往返等待 + async let history: Void = expandedPayableIds.contains(item.id) + ? loadPayableHistory(item.id) : () + async let refreshed: Void = refreshPayables() + _ = await (history, refreshed) } public func savePayable(_ draft: PayableDraft, existing: PayableItem?) async throws { diff --git a/lib/api/payables.server.ts b/lib/api/payables.server.ts index d77f0be..46af595 100644 --- a/lib/api/payables.server.ts +++ b/lib/api/payables.server.ts @@ -140,7 +140,8 @@ export async function getPayablePayments(payableId: string): Promise Date: Tue, 3 Nov 2026 18:57:10 +0800 Subject: [PATCH 04/10] fix(payables): single-flight history loading and stale-cache invalidation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - web dedupes concurrent history requests per payable and shares one loader between expand and post-payment refetch - history panel prefers 加载中 over a stale error; limit is a named constant and the label switches to 最近 N 笔 when truncated - iOS clears history caches after refreshPayables, skips history fetch in demo/UI-test mode, drops the old error when a retry starts, and turns the failure text into a retry button --- app/(mobile)/bills/page.tsx | 50 ++++++++++++++++----------- components/mobile/PayableList.tsx | 38 ++++++++++++-------- ios/WorldCredit/AppState.swift | 11 ++++++ ios/WorldCredit/Views/BillsView.swift | 16 +++++++-- lib/api/payables.server.ts | 5 ++- 5 files changed, 80 insertions(+), 40 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index 10d269b..406e41c 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, @@ -429,15 +429,7 @@ export default function BillsPage() { return next }) if (expandedPayableIds.has(payable.id)) { - try { - const records = await getPayablePayments(payable.id) - setPayablePayments(prev => ({ ...prev, [payable.id]: records })) - } catch (err) { - setPayableHistoryErrors(prev => ({ - ...prev, - [payable.id]: err instanceof Error ? err.message : '历史还款加载失败', - })) - } + await loadPayableHistory(payable.id) } setCelebrationNotice({ open: true, @@ -450,16 +442,14 @@ export default function BillsPage() { } /** 展开/收起固定支出历史:首次展开才拉取该笔记录。 */ - const handleTogglePayableHistory = useCallback( - async (payableId: string) => { - const willOpen = !expandedPayableIds.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 + // 同一笔的在途请求:并发点击或还款后重取都复用同一个 Promise,避免重复 RPC + const payableHistoryInFlight = useRef>>(new Map()) + + /** 拉取并写入历史缓存;同一 payableId 复用进行中的请求。 */ + const loadPayableHistory = useCallback((payableId: string) => { + const running = payableHistoryInFlight.current.get(payableId) + if (running) return running + const task = (async () => { try { const records = await getPayablePayments(payableId) setPayablePayments(prev => ({ ...prev, [payableId]: records })) @@ -475,9 +465,27 @@ export default function BillsPage() { ...prev, [payableId]: err instanceof Error ? err.message : '历史还款加载失败', })) + } finally { + payableHistoryInFlight.current.delete(payableId) } + })() + payableHistoryInFlight.current.set(payableId, task) + return task + }, []) + + const handleTogglePayableHistory = useCallback( + (payableId: string) => { + const willOpen = !expandedPayableIds.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) }, - [expandedPayableIds, payablePayments] + [expandedPayableIds, payablePayments, loadPayableHistory] ) // 收起态摘要:把当前筛选、分组与排序压成一行可读文本 diff --git a/components/mobile/PayableList.tsx b/components/mobile/PayableList.tsx index b3af87a..c253637 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -26,29 +26,22 @@ export interface PayableRowProps { onPay: (payable: PayableWithStatus) => void } -/** - * 单条固定支出卡。从 PayableList 拆出:账单页现在把固定支出混进主列表统一排序。 - * - * 整卡可点进编辑(与 BillCard 整卡进详情同交互模型):固定支出没有单独的 - * 详情页,「编辑表单」就是它的详情视图。内层动作(复制账号/登记付款)阻止冒泡。 - * - * 状态徽章与信用卡卡片同构(右上角、soft 底 + ink 文字): - * 已逾期(danger) / 待还款·今天应付(warn) / 待出账(success)。 - * 滚动模型(服务端 resolveDisplayPeriod)保证任一时刻卡片只呈现一期: - * 「已登记」只可能出现在待出账态,待还款态一定是可登记付款的未付期。 - */ +/** 与服务端 LIMIT 保持一致:超出时文案改称「最近 N 笔」。 */ +const PAYABLE_HISTORY_LIMIT = 60 + /** 历史还款展开区:加载中 / 失败 / 空 / 列表四态,避免嵌套三元。 */ function renderPayableHistory( payments: PayablePaymentRecord[] | undefined, historyError: string | undefined, currency: string ) { - if (historyError) { - return

{historyError}

- } + // 重试在途时优先显示「加载中」,旧错误不再滞留 if (payments === undefined) { return

加载中…

} + if (historyError) { + return

{historyError}

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

还没有历史还款记录

} @@ -74,6 +67,17 @@ function renderPayableHistory( ) } +/** + * 单条固定支出卡。从 PayableList 拆出:账单页现在把固定支出混进主列表统一排序。 + * + * 整卡可点进编辑(与 BillCard 整卡进详情同交互模型):固定支出没有单独的 + * 详情页,「编辑表单」就是它的详情视图。内层动作(复制账号/登记付款)阻止冒泡。 + * + * 状态徽章与信用卡卡片同构(右上角、soft 底 + ink 文字): + * 已逾期(danger) / 待还款·今天应付(warn) / 待出账(success)。 + * 滚动模型(服务端 resolveDisplayPeriod)保证任一时刻卡片只呈现一期: + * 「已登记」只可能出现在待出账态,待还款态一定是可登记付款的未付期。 + */ export function PayableRow({ payable: p, holderName, @@ -228,7 +232,11 @@ export function PayableRow({ onClick={e => { e.stopPropagation(); onToggleHistory() }} className='flex w-full items-center justify-between text-[11px] font-semibold text-d-muted' > - 历史还款{payments && payments.length > 0 ? ` ${payments.length} 笔` : ''} + + {payments && payments.length >= PAYABLE_HISTORY_LIMIT + ? `最近 ${PAYABLE_HISTORY_LIMIT} 笔还款` + : `历史还款${payments && payments.length > 0 ? ` ${payments.length} 笔` : ''}`} + {historyOpen ? '收起' : '展开'} {historyOpen && renderPayableHistory(payments, historyError, p.currency)} diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index a7fe437..10d904f 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -647,6 +647,9 @@ public final class AppState { payables = items payablesError = nil + // 服务端列表已重取:历史缓存可能过期,清空后按需重拉 + payablePayments = [:] + payableHistoryErrors = [] // 空结果 = 用户删空了固定支出:移除快照(否则「删空后重启+离线」会复活已删条目); // 服务端瞬时异常返回空列表的窗口极窄且下次在线刷新即自愈,不值得为它保留陈旧快照。 @@ -809,8 +812,16 @@ public final class AppState { } 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) // 拉取在途期间发生还款会递增版本号,过期响应丢弃 diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index 65775a9..52d1eff 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -1044,10 +1044,20 @@ struct BillsView: View { .accessibilityIdentifier("bills.payable.history.\(payable.id)") if expanded { - if failed { - Text("历史还款加载失败,请再次展开重试") + if records == nil { + // 在途(含重试)优先显示加载中 + Text("加载中…") .font(.caption2) - .foregroundStyle(WCColors.dangerInk) + .foregroundStyle(WCColors.textSecondary) + } else if failed { + Button { + Task { await appState.togglePayableHistory(payable.id) } + } label: { + Text("加载失败,点此重试") + .font(.caption2.weight(.semibold)) + .foregroundStyle(WCColors.dangerInk) + } + .buttonStyle(.plain) } else if let records { if records.isEmpty { Text("还没有历史还款记录") diff --git a/lib/api/payables.server.ts b/lib/api/payables.server.ts index 46af595..94d2702 100644 --- a/lib/api/payables.server.ts +++ b/lib/api/payables.server.ts @@ -121,6 +121,9 @@ export async function resolveDisplayPeriod( return { period: current, paidAmount: paidCurrent } } +/** 历史还款返回上限:与前端「最近 N 笔」文案一致。 */ +export const PAYABLE_HISTORY_LIMIT = 60 + export interface PayablePaymentRecord { id: string payable_id: string @@ -141,7 +144,7 @@ export async function getPayablePayments(payableId: string): Promise Date: Tue, 3 Nov 2026 19:28:26 +0800 Subject: [PATCH 05/10] fix(payables): correct history loading states and refresh semantics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - error state is reachable again: explicit loading flag takes priority, and a failed load keeps the error instead of a permanent 加载中 - page waits for an in-flight request before refetching after a payment, so a stale response cannot overwrite fresh data - full refresh paths clear history caches; omitRecordKey dedupes the three immutable-delete sites - PAYABLE_HISTORY_LIMIT moves to payables.shared (one definition for server and UI); label becomes 最近 N 笔 at the cap - iOS retry is its own entry point (stays expanded), refresh refetches expanded rows, and the toggle label no longer nests ternaries --- app/(mobile)/bills/page.tsx | 37 ++++++++++++------- .../__tests__/BillReviewRegressions.test.tsx | 3 +- components/mobile/PayableList.tsx | 29 ++++++++++----- components/obsidian/BillsView.tsx | 5 ++- ios/WorldCredit/AppState.swift | 12 +++++- ios/WorldCredit/Views/BillsView.swift | 2 +- lib/api/payables.server.ts | 9 +++-- lib/api/payables.shared.ts | 3 ++ lib/api/payables.ts | 1 + 9 files changed, 70 insertions(+), 31 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index 406e41c..427cb2a 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -73,6 +73,14 @@ function tagSummary( return selectedTag === NO_BANK_TAG ? '非银行' : selectedTag } +/** 不可变地从 Record 中删除一个 key(无该 key 时返回原对象)。 */ +function omitRecordKey(record: Record, key: string): Record { + if (!(key in record)) return record + const next = { ...record } + delete next[key] + return next +} + export default function BillsPage() { const { user } = useAuth() const { displayConfig } = useUserPreferences() @@ -97,6 +105,7 @@ export default function BillsPage() { 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 }>({ @@ -140,6 +149,9 @@ export default function BillsPage() { getHolders(user.id), ]) setCardsSummary(summaryData) + // 全量刷新:历史缓存可能过期,清空后按需重拉 + setPayablePayments({}) + setPayableHistoryErrors({}) const map: Record = {} for (const h of holders) map[h.id] = h.name setHolderMap(map) @@ -421,13 +433,10 @@ export default function BillsPage() { const handlePayPayable = async (payable: PayableWithStatus) => { try { await payRecurringPayable(payable.id, payable.amount) - // 新还款落库:清掉该笔历史缓存;若当时正展开则立即重取,避免停在「加载中」 - setPayablePayments(prev => { - if (!(payable.id in prev)) return prev - const next = { ...prev } - delete next[payable.id] - return next - }) + // 新还款落库:清掉该笔历史缓存;先等在途旧请求落定,避免旧结果回写覆盖新数据 + setPayablePayments(prev => omitRecordKey(prev, payable.id)) + const running = payableHistoryInFlight.current.get(payable.id) + if (running) await running if (expandedPayableIds.has(payable.id)) { await loadPayableHistory(payable.id) } @@ -449,16 +458,12 @@ export default function BillsPage() { const loadPayableHistory = useCallback((payableId: string) => { const running = payableHistoryInFlight.current.get(payableId) if (running) return running + setPayableHistoryLoading(prev => new Set(prev).add(payableId)) const task = (async () => { try { const records = await getPayablePayments(payableId) setPayablePayments(prev => ({ ...prev, [payableId]: records })) - setPayableHistoryErrors(prev => { - if (!prev[payableId]) return prev - const next = { ...prev } - delete next[payableId] - return next - }) + setPayableHistoryErrors(prev => omitRecordKey(prev, payableId)) } catch (err) { // 保持未加载状态:再次展开会重试;错误就地展示 setPayableHistoryErrors(prev => ({ @@ -467,6 +472,11 @@ export default function BillsPage() { })) } finally { payableHistoryInFlight.current.delete(payableId) + setPayableHistoryLoading(prev => { + const next = new Set(prev) + next.delete(payableId) + return next + }) } })() payableHistoryInFlight.current.set(payableId, task) @@ -570,6 +580,7 @@ export default function BillsPage() { payables={filteredPayables} payablePayments={payablePayments} payableHistoryErrors={payableHistoryErrors} + payableHistoryLoading={payableHistoryLoading} expandedPayableIds={expandedPayableIds} onTogglePayableHistory={handleTogglePayableHistory} onEditPayable={p => { setEditingPayable(p); setPayableFormOpen(true) }} diff --git a/components/__tests__/BillReviewRegressions.test.tsx b/components/__tests__/BillReviewRegressions.test.tsx index 925ecf2..2517da6 100644 --- a/components/__tests__/BillReviewRegressions.test.tsx +++ b/components/__tests__/BillReviewRegressions.test.tsx @@ -299,7 +299,8 @@ function makeBillsViewFixture(): { props: BillsViewProps; unpaid: BillDashboardI holderTags: [], bankTags: [], loading: false, loadError: null, onRetry: vi.fn(), onEmptySync: vi.fn(), payables: [], onEditPayable: vi.fn(), onPayPayable: vi.fn(), - payablePayments: {}, payableHistoryErrors: {}, expandedPayableIds: new Set(), + 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 c253637..9604d1d 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -3,6 +3,7 @@ import { useState } from 'react' import { categoryLabel, + PAYABLE_HISTORY_LIMIT, type PayableWithStatus, type PayablePaymentRecord, } from '@/lib/api/payables' @@ -19,6 +20,8 @@ export interface PayableRowProps { payments?: PayablePaymentRecord[] /** 历史加载失败提示;为空表示无错误 */ historyError?: string + /** 历史请求在途(含重试);优先于错误态展示 */ + historyLoading?: boolean /** 是否展开历史还款 */ historyOpen?: boolean onToggleHistory?: () => void @@ -26,22 +29,30 @@ export interface PayableRowProps { onPay: (payable: PayableWithStatus) => void } -/** 与服务端 LIMIT 保持一致:超出时文案改称「最近 N 笔」。 */ -const PAYABLE_HISTORY_LIMIT = 60 +/** 展开按钮文案:达到上限时改称「最近 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 ) { - // 重试在途时优先显示「加载中」,旧错误不再滞留 - if (payments === undefined) { + // 在途优先:重试时不显示上一次的错误 + if (historyLoading) { return

加载中…

} if (historyError) { return

{historyError}

} + if (payments === undefined) { + return

加载中…

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

还没有历史还款记录

} @@ -83,6 +94,7 @@ export function PayableRow({ holderName, payments, historyError, + historyLoading = false, historyOpen = false, onToggleHistory, onEdit, @@ -232,14 +244,11 @@ export function PayableRow({ onClick={e => { e.stopPropagation(); onToggleHistory() }} className='flex w-full items-center justify-between text-[11px] font-semibold text-d-muted' > - - {payments && payments.length >= PAYABLE_HISTORY_LIMIT - ? `最近 ${PAYABLE_HISTORY_LIMIT} 笔还款` - : `历史还款${payments && payments.length > 0 ? ` ${payments.length} 笔` : ''}`} - + {historyLabel(payments)} {historyOpen ? '收起' : '展开'} - {historyOpen && renderPayableHistory(payments, historyError, p.currency)} + {historyOpen && + renderPayableHistory(payments, historyError, historyLoading, p.currency)} )} diff --git a/components/obsidian/BillsView.tsx b/components/obsidian/BillsView.tsx index 84eac9f..f4357c7 100644 --- a/components/obsidian/BillsView.tsx +++ b/components/obsidian/BillsView.tsx @@ -96,6 +96,7 @@ export interface BillsViewProps { /** 各固定支出的历史还款记录,key = payable id */ payablePayments: Record payableHistoryErrors: Record + payableHistoryLoading: Set /** 已展开历史的 payable id */ expandedPayableIds: Set onTogglePayableHistory: (id: string) => void @@ -394,7 +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, expandedPayableIds, onTogglePayableHistory, + payablePayments, payableHistoryErrors, payableHistoryLoading, + expandedPayableIds, onTogglePayableHistory, onEditPayable, onPayPayable, } = vm @@ -455,6 +457,7 @@ export function BillsView(vm: BillsViewProps) { 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} diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index 10d904f..e0e0fa7 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -647,9 +647,13 @@ public final class AppState { payables = items payablesError = nil - // 服务端列表已重取:历史缓存可能过期,清空后按需重拉 + // 服务端列表已重取:历史缓存可能过期,清空并对已展开项立即重拉 + let expanded = expandedPayableIds payablePayments = [:] payableHistoryErrors = [] + for id in expanded where payables.contains(where: { $0.id == id }) { + await loadPayableHistory(id) + } // 空结果 = 用户删空了固定支出:移除快照(否则「删空后重启+离线」会复活已删条目); // 服务端瞬时异常返回空列表的窗口极窄且下次在线刷新即自愈,不值得为它保留陈旧快照。 @@ -811,6 +815,12 @@ public final class AppState { await loadPayableHistory(payableId) } + /// 错误态点击「重试」:保持展开,直接重拉。 + public func retryPayableHistory(_ payableId: String) async { + expandedPayableIds.insert(payableId) + await loadPayableHistory(payableId) + } + private func loadPayableHistory(_ payableId: String) async { // 演示模式与 UI 测试不访问在线固定支出,历史同样跳过 guard !UITestConfiguration.isEnabled, diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index 52d1eff..fbaf3aa 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -1051,7 +1051,7 @@ struct BillsView: View { .foregroundStyle(WCColors.textSecondary) } else if failed { Button { - Task { await appState.togglePayableHistory(payable.id) } + Task { await appState.retryPayableHistory(payable.id) } } label: { Text("加载失败,点此重试") .font(.caption2.weight(.semibold)) diff --git a/lib/api/payables.server.ts b/lib/api/payables.server.ts index 94d2702..32bc684 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,9 +125,6 @@ export async function resolveDisplayPeriod( return { period: current, paidAmount: paidCurrent } } -/** 历史还款返回上限:与前端「最近 N 笔」文案一致。 */ -export const PAYABLE_HISTORY_LIMIT = 60 - export interface PayablePaymentRecord { id: string payable_id: 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 0b2b9e6..d5862d5 100644 --- a/lib/api/payables.ts +++ b/lib/api/payables.ts @@ -19,6 +19,7 @@ export { PAYABLE_CURRENCY_LABELS, isPayableCurrency, normalizePayableCurrency, + PAYABLE_HISTORY_LIMIT, } from './payables.shared' export function getRecurringPayables(...args: Parameters) { From 95ae00acc78fae099877fb7a6f217a268392dc0f Mon Sep 17 00:00:00 2001 From: hubo Date: Tue, 3 Nov 2026 19:57:46 +0800 Subject: [PATCH 06/10] fix(payables): reachable failure state and cheaper history refresh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - iOS failure branch now precedes the loading branch (records is always nil on failure), and the retry button keeps the row expanded - web merges the two identical loading branches; after a full refresh it refetches expanded rows instead of leaving them on 加载中 - payment refetch re-reads expansion state from a ref and waits out any in-flight request before refetching - history loader is declared before loadData; iOS refresh marks expanded rows stale and refetches on view demand instead of serially awaiting N requests - LIMIT is bound as a parameter; iOS label switches to 最近 60 笔 at the cap --- app/(mobile)/bills/page.tsx | 78 +++++++++++++++------------ components/mobile/PayableList.tsx | 7 +-- ios/WorldCredit/AppState.swift | 18 +++++-- ios/WorldCredit/Views/BillsView.swift | 21 ++++++-- lib/api/payables.server.ts | 4 +- 5 files changed, 78 insertions(+), 50 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index 427cb2a..4e1d10f 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -139,6 +139,44 @@ 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()) + + /** 拉取并写入历史缓存;同一 payableId 复用进行中的请求。 */ + const loadPayableHistory = useCallback((payableId: string) => { + const running = payableHistoryInFlight.current.get(payableId) + if (running) return running + setPayableHistoryLoading(prev => new Set(prev).add(payableId)) + const task = (async () => { + try { + const records = await getPayablePayments(payableId) + setPayablePayments(prev => ({ ...prev, [payableId]: records })) + setPayableHistoryErrors(prev => omitRecordKey(prev, payableId)) + } catch (err) { + // 保持未加载状态:再次展开会重试;错误就地展示 + setPayableHistoryErrors(prev => ({ + ...prev, + [payableId]: err instanceof Error ? err.message : '历史还款加载失败', + })) + } finally { + payableHistoryInFlight.current.delete(payableId) + setPayableHistoryLoading(prev => { + const next = new Set(prev) + next.delete(payableId) + return next + }) + } + })() + payableHistoryInFlight.current.set(payableId, task) + return task + }, []) + const loadData = useCallback(async () => { if (!user) return try { @@ -149,9 +187,10 @@ export default function BillsPage() { getHolders(user.id), ]) setCardsSummary(summaryData) - // 全量刷新:历史缓存可能过期,清空后按需重拉 + // 全量刷新:历史缓存可能过期;清空后对仍展开的行立即重拉,避免停在「加载中」 setPayablePayments({}) setPayableHistoryErrors({}) + expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) }) const map: Record = {} for (const h of holders) map[h.id] = h.name setHolderMap(map) @@ -168,7 +207,7 @@ export default function BillsPage() { } finally { setLoading(false) } - }, [user]) + }, [user, loadPayableHistory]) useEffect(() => { loadData() @@ -437,7 +476,8 @@ export default function BillsPage() { setPayablePayments(prev => omitRecordKey(prev, payable.id)) const running = payableHistoryInFlight.current.get(payable.id) if (running) await running - if (expandedPayableIds.has(payable.id)) { + // 等待期间用户可能收起/展开,重取前重新读取展开状态 + if (expandedPayableIdsRef.current.has(payable.id)) { await loadPayableHistory(payable.id) } setCelebrationNotice({ @@ -451,38 +491,6 @@ export default function BillsPage() { } /** 展开/收起固定支出历史:首次展开才拉取该笔记录。 */ - // 同一笔的在途请求:并发点击或还款后重取都复用同一个 Promise,避免重复 RPC - const payableHistoryInFlight = useRef>>(new Map()) - - /** 拉取并写入历史缓存;同一 payableId 复用进行中的请求。 */ - const loadPayableHistory = useCallback((payableId: string) => { - const running = payableHistoryInFlight.current.get(payableId) - if (running) return running - setPayableHistoryLoading(prev => new Set(prev).add(payableId)) - const task = (async () => { - try { - const records = await getPayablePayments(payableId) - setPayablePayments(prev => ({ ...prev, [payableId]: records })) - setPayableHistoryErrors(prev => omitRecordKey(prev, payableId)) - } catch (err) { - // 保持未加载状态:再次展开会重试;错误就地展示 - setPayableHistoryErrors(prev => ({ - ...prev, - [payableId]: err instanceof Error ? err.message : '历史还款加载失败', - })) - } finally { - payableHistoryInFlight.current.delete(payableId) - setPayableHistoryLoading(prev => { - const next = new Set(prev) - next.delete(payableId) - return next - }) - } - })() - payableHistoryInFlight.current.set(payableId, task) - return task - }, []) - const handleTogglePayableHistory = useCallback( (payableId: string) => { const willOpen = !expandedPayableIds.has(payableId) diff --git a/components/mobile/PayableList.tsx b/components/mobile/PayableList.tsx index 9604d1d..2c4d22a 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -43,16 +43,13 @@ function renderPayableHistory( historyLoading: boolean, currency: string ) { - // 在途优先:重试时不显示上一次的错误 - if (historyLoading) { + // 在途或尚未加载都算加载中:合并同一份文案,重试时不显示上一次的错误 + if (historyLoading || payments === undefined) { return

加载中…

} if (historyError) { return

{historyError}

} - if (payments === undefined) { - return

加载中…

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

还没有历史还款记录

} diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index e0e0fa7..c4fab01 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -127,6 +127,8 @@ public final class AppState { public var payableHistoryErrors: Set = [] /// 历史请求版本号:还款后递增,过期响应直接丢弃。 private var payableHistoryRevision: [String: Int] = [:] + /// 刷新后待重取历史的已展开项:下一次展开交互时拉取。 + private var payableHistoryStale: Set = [] public var payablesError: String? /// 盘库打不开、退到内存库时的可恢复提示(数据不持久化),由 UI 展示。 @@ -586,6 +588,7 @@ public final class AppState { expandedPayableIds = [] payableHistoryErrors = [] payableHistoryRevision = [:] + payableHistoryStale = [] lastSyncError = nil // 401 会话过期不走完整 logout:per-user 快照靠 owner 记录在这里补清, // 否则下一个账号直接 login 时前任财务快照残留磁盘 @@ -647,13 +650,11 @@ public final class AppState { payables = items payablesError = nil - // 服务端列表已重取:历史缓存可能过期,清空并对已展开项立即重拉 - let expanded = expandedPayableIds + // 服务端列表已重取:历史缓存可能过期。已展开的行标记为待重取, + // 由视图在下一次展开交互时按需拉取,避免刷新路径串行追加 N 次请求。 payablePayments = [:] payableHistoryErrors = [] - for id in expanded where payables.contains(where: { $0.id == id }) { - await loadPayableHistory(id) - } + payableHistoryStale = expandedPayableIds // 空结果 = 用户删空了固定支出:移除快照(否则「删空后重启+离线」会复活已删条目); // 服务端瞬时异常返回空列表的窗口极窄且下次在线刷新即自愈,不值得为它保留陈旧快照。 @@ -815,6 +816,11 @@ public final class AppState { await loadPayableHistory(payableId) } + /// 该行历史是否需要重新拉取(刷新后清空缓存但保持展开)。 + public func isPayableHistoryStale(_ payableId: String) -> Bool { + payableHistoryStale.contains(payableId) + } + /// 错误态点击「重试」:保持展开,直接重拉。 public func retryPayableHistory(_ payableId: String) async { expandedPayableIds.insert(payableId) @@ -838,6 +844,7 @@ public final class AppState { guard payableHistoryRevision[payableId] == revision else { return } payablePayments[payableId] = records payableHistoryErrors.remove(payableId) + payableHistoryStale.remove(payableId) } catch { guard payableHistoryRevision[payableId] == revision else { return } // 保持「未加载」以便下次展开重试,并记录错误供 UI 展示 @@ -1026,6 +1033,7 @@ public final class AppState { 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 fbaf3aa..19af068 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -1018,6 +1018,13 @@ 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 >= 60 { return "最近 60 笔还款" } + return "历史还款 \(records.count) 笔" + } + /// 固定支出历史还款:按钮常驻,展开才拉取;数据来自 AppState 缓存。 @ViewBuilder private func payableHistorySection(_ payable: PayableItem) -> some View { @@ -1030,7 +1037,7 @@ struct BillsView: View { Task { await appState.togglePayableHistory(payable.id) } } label: { HStack { - Text(records.map { "历史还款 \($0.count) 笔" } ?? "历史还款") + Text(payableHistoryLabel(records)) .font(.caption.weight(.semibold)) .foregroundStyle(WCColors.textSecondary) Spacer() @@ -1044,12 +1051,16 @@ struct BillsView: View { .accessibilityIdentifier("bills.payable.history.\(payable.id)") if expanded { - if records == nil { - // 在途(含重试)优先显示加载中 + if appState.isPayableHistoryStale(payable.id) { + // 刷新后缓存已清空但行仍展开:立即重取 Text("加载中…") .font(.caption2) .foregroundStyle(WCColors.textSecondary) + .task(id: payable.id) { + await appState.retryPayableHistory(payable.id) + } } else if failed { + // 失败态:records 恒为 nil,必须优先于「加载中」判定 Button { Task { await appState.retryPayableHistory(payable.id) } } label: { @@ -1058,6 +1069,10 @@ struct BillsView: View { .foregroundStyle(WCColors.dangerInk) } .buttonStyle(.plain) + } else if records == nil { + Text("加载中…") + .font(.caption2) + .foregroundStyle(WCColors.textSecondary) } else if let records { if records.isEmpty { Text("还没有历史还款记录") diff --git a/lib/api/payables.server.ts b/lib/api/payables.server.ts index 32bc684..fef215c 100644 --- a/lib/api/payables.server.ts +++ b/lib/api/payables.server.ts @@ -145,8 +145,8 @@ export async function getPayablePayments(payableId: string): Promise Date: Tue, 3 Nov 2026 20:26:24 +0800 Subject: [PATCH 07/10] fix(payables): restore error state and unstick iOS retry loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - web: failed loads keep payments undefined, so the 加载中 condition must not absorb it — branch order is now loading → error → undefined - web: wait for the in-flight request before clearing cache after a payment so a stale response cannot write back; toggle direction reads the ref - iOS: clear the stale flag on failure (otherwise the stale branch retried forever), prefer the failure branch over stale, and clear stale on delete --- app/(mobile)/bills/page.tsx | 12 +++++------- components/mobile/PayableList.tsx | 8 ++++++-- ios/WorldCredit/AppState.swift | 5 ++++- ios/WorldCredit/Views/BillsView.swift | 20 ++++++++++---------- 4 files changed, 25 insertions(+), 20 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index 4e1d10f..7cf4b60 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -472,14 +472,12 @@ export default function BillsPage() { const handlePayPayable = async (payable: PayableWithStatus) => { try { await payRecurringPayable(payable.id, payable.amount) - // 新还款落库:清掉该笔历史缓存;先等在途旧请求落定,避免旧结果回写覆盖新数据 - setPayablePayments(prev => omitRecordKey(prev, payable.id)) + // 新还款落库:先等在途旧请求落定(否则它的成功回调会把不含新还款的记录写回), + // 再清缓存并重取 const running = payableHistoryInFlight.current.get(payable.id) if (running) await running + setPayablePayments(prev => omitRecordKey(prev, payable.id)) // 等待期间用户可能收起/展开,重取前重新读取展开状态 - if (expandedPayableIdsRef.current.has(payable.id)) { - await loadPayableHistory(payable.id) - } setCelebrationNotice({ open: true, message: `🎉 已登记「${payable.name}」本期付款 ${currencySymbol(payable.currency)}${payable.amount.toLocaleString()}`, @@ -493,7 +491,7 @@ export default function BillsPage() { /** 展开/收起固定支出历史:首次展开才拉取该笔记录。 */ const handleTogglePayableHistory = useCallback( (payableId: string) => { - const willOpen = !expandedPayableIds.has(payableId) + const willOpen = !expandedPayableIdsRef.current.has(payableId) setExpandedPayableIds(prev => { const next = new Set(prev) if (willOpen) next.add(payableId) @@ -503,7 +501,7 @@ export default function BillsPage() { if (!willOpen || payablePayments[payableId]) return void loadPayableHistory(payableId) }, - [expandedPayableIds, payablePayments, loadPayableHistory] + [payablePayments, loadPayableHistory] ) // 收起态摘要:把当前筛选、分组与排序压成一行可读文本 diff --git a/components/mobile/PayableList.tsx b/components/mobile/PayableList.tsx index 2c4d22a..0f9c113 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -43,13 +43,17 @@ function renderPayableHistory( historyLoading: boolean, currency: string ) { - // 在途或尚未加载都算加载中:合并同一份文案,重试时不显示上一次的错误 - if (historyLoading || payments === undefined) { + // 顺序必须是 在途 → 失败 → 未加载:失败时 payments 仍为 undefined, + // 若把 undefined 并入加载中,错误文案将永远不可达。 + if (historyLoading) { return

加载中…

} if (historyError) { return

{historyError}

} + if (payments === undefined) { + return

加载中…

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

还没有历史还款记录

} diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index c4fab01..fb80d69 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -847,9 +847,11 @@ public final class AppState { payableHistoryStale.remove(payableId) } catch { guard payableHistoryRevision[payableId] == revision else { return } - // 保持「未加载」以便下次展开重试,并记录错误供 UI 展示 + // 保持「未加载」以便下次展开重试,并记录错误供 UI 展示; + // 同时清 stale,否则 stale 分支会反复自动重试形成死循环 payablePayments[payableId] = nil payableHistoryErrors.insert(payableId) + payableHistoryStale.remove(payableId) } } @@ -859,6 +861,7 @@ public final class AppState { expandedPayableIds.remove(item.id) payableHistoryErrors.remove(item.id) payableHistoryRevision[item.id] = nil + payableHistoryStale.remove(item.id) await refreshPayables() } diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index 19af068..53c5722 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -1051,16 +1051,8 @@ struct BillsView: View { .accessibilityIdentifier("bills.payable.history.\(payable.id)") if expanded { - if appState.isPayableHistoryStale(payable.id) { - // 刷新后缓存已清空但行仍展开:立即重取 - Text("加载中…") - .font(.caption2) - .foregroundStyle(WCColors.textSecondary) - .task(id: payable.id) { - await appState.retryPayableHistory(payable.id) - } - } else if failed { - // 失败态:records 恒为 nil,必须优先于「加载中」判定 + if failed { + // 失败态优先:失败时 records 恒为 nil,先判 nil 会让错误永远不可见 Button { Task { await appState.retryPayableHistory(payable.id) } } label: { @@ -1069,6 +1061,14 @@ struct BillsView: View { .foregroundStyle(WCColors.dangerInk) } .buttonStyle(.plain) + } else if appState.isPayableHistoryStale(payable.id) { + // 刷新后缓存已清空但行仍展开:立即重取 + Text("加载中…") + .font(.caption2) + .foregroundStyle(WCColors.textSecondary) + .task(id: payable.id) { + await appState.retryPayableHistory(payable.id) + } } else if records == nil { Text("加载中…") .font(.caption2) From da616fc904527995ca2a8fb43b895b122c978a1c Mon Sep 17 00:00:00 2001 From: hubo Date: Tue, 3 Nov 2026 20:54:30 +0800 Subject: [PATCH 08/10] fix(payables): invalidate in-flight history on refresh and handle cancellation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - web: loadData clears the in-flight map before wiping caches so a pre-refresh response cannot repopulate stale rows; in-flight identity is tracked by a dedicated promise so a superseded request cannot delete the new one - iOS: refresh bumps revision for expanded rows before clearing caches - iOS: CancellationError / URLError.cancelled keep the row pending instead of surfacing as a load failure - iOS: drop the unreachable trailing 加载中 branch --- app/(mobile)/bills/page.tsx | 20 ++++++++++++++------ ios/WorldCredit/AppState.swift | 14 ++++++++++++-- ios/WorldCredit/Views/BillsView.swift | 4 ---- 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index 7cf4b60..856c772 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -153,7 +153,9 @@ export default function BillsPage() { const running = payableHistoryInFlight.current.get(payableId) if (running) return running setPayableHistoryLoading(prev => new Set(prev).add(payableId)) - const task = (async () => { + let settle!: () => void + const current = new Promise(resolve => { settle = resolve }) + void (async () => { try { const records = await getPayablePayments(payableId) setPayablePayments(prev => ({ ...prev, [payableId]: records })) @@ -165,16 +167,20 @@ export default function BillsPage() { [payableId]: err instanceof Error ? err.message : '历史还款加载失败', })) } finally { - payableHistoryInFlight.current.delete(payableId) + // 只清理自己这条:若期间已被 loadData 清空并重新发起,不能误删新任务 + // 用 token 而非 task 引用比对(task 在 IIFE 内部尚未赋值) + if (payableHistoryInFlight.current.get(payableId) === current) { + payableHistoryInFlight.current.delete(payableId) + } setPayableHistoryLoading(prev => { const next = new Set(prev) next.delete(payableId) return next }) } - })() - payableHistoryInFlight.current.set(payableId, task) - return task + })().finally(() => settle()) + payableHistoryInFlight.current.set(payableId, current) + return current }, []) const loadData = useCallback(async () => { @@ -187,7 +193,9 @@ export default function BillsPage() { getHolders(user.id), ]) setCardsSummary(summaryData) - // 全量刷新:历史缓存可能过期;清空后对仍展开的行立即重拉,避免停在「加载中」 + // 全量刷新:历史缓存可能过期。先丢弃在途请求(否则其成功回调会把刷新前的旧数据写回), + // 再清空缓存并对仍展开的行重拉,避免停在「加载中」 + payableHistoryInFlight.current.clear() setPayablePayments({}) setPayableHistoryErrors({}) expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) }) diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index fb80d69..0ed6dec 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -650,8 +650,11 @@ public final class AppState { payables = items payablesError = nil - // 服务端列表已重取:历史缓存可能过期。已展开的行标记为待重取, - // 由视图在下一次展开交互时按需拉取,避免刷新路径串行追加 N 次请求。 + // 服务端列表已重取:先作废所有在途历史请求(否则其回调会把刷新前的旧数据写回), + // 再把已展开行标记为待重取,由视图按需拉取。 + for id in expandedPayableIds { + payableHistoryRevision[id] = (payableHistoryRevision[id] ?? 0) + 1 + } payablePayments = [:] payableHistoryErrors = [] payableHistoryStale = expandedPayableIds @@ -845,6 +848,13 @@ public final class AppState { payablePayments[payableId] = records payableHistoryErrors.remove(payableId) payableHistoryStale.remove(payableId) + } catch is CancellationError { + // 视图取消(收起/离屏):不是失败,保持待重取状态 + guard payableHistoryRevision[payableId] == revision else { return } + payablePayments[payableId] = nil + } catch let urlError as URLError where urlError.code == .cancelled { + guard payableHistoryRevision[payableId] == revision else { return } + payablePayments[payableId] = nil } catch { guard payableHistoryRevision[payableId] == revision else { return } // 保持「未加载」以便下次展开重试,并记录错误供 UI 展示; diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index 53c5722..abbe4d0 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -1102,10 +1102,6 @@ struct BillsView: View { } } } - } else { - Text("加载中…") - .font(.caption2) - .foregroundStyle(WCColors.textSecondary) } } } From d0f5a311a186f1cedc283c63e3509a02f9df8f65 Mon Sep 17 00:00:00 2001 From: hubo Date: Tue, 3 Nov 2026 21:27:10 +0800 Subject: [PATCH 09/10] fix(payables): generation guard for stale responses and explicit reload paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - replace the ineffective in-flight map clear with a cache generation: any request started before a refresh/payment is discarded on completion - payment path refetches immediately when the row is expanded, so the row no longer sits on a fake 加载中 with no request behind it - undefined cache with no request renders 展开以加载历史 instead of 加载中 - iOS stale rows expose an explicit 点击加载最新历史 button; .task(id:) could not retrigger while the id stayed unchanged --- app/(mobile)/bills/page.tsx | 20 ++++++++++++++++---- components/mobile/PayableList.tsx | 3 ++- ios/WorldCredit/Views/BillsView.swift | 16 +++++++++------- 3 files changed, 27 insertions(+), 12 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index 856c772..deeb95d 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -148,27 +148,33 @@ export default function BillsPage() { // 同一笔的在途请求:并发点击或还款后重取都复用同一个 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 { - // 只清理自己这条:若期间已被 loadData 清空并重新发起,不能误删新任务 - // 用 token 而非 task 引用比对(task 在 IIFE 内部尚未赋值) + // 只清理自己这条:被新任务顶替时不能误删 if (payableHistoryInFlight.current.get(payableId) === current) { payableHistoryInFlight.current.delete(payableId) } @@ -193,8 +199,8 @@ export default function BillsPage() { getHolders(user.id), ]) setCardsSummary(summaryData) - // 全量刷新:历史缓存可能过期。先丢弃在途请求(否则其成功回调会把刷新前的旧数据写回), - // 再清空缓存并对仍展开的行重拉,避免停在「加载中」 + // 全量刷新:递增代次作废在途响应,清空缓存,并对仍展开的行重拉 + payableHistoryGeneration.current += 1 payableHistoryInFlight.current.clear() setPayablePayments({}) setPayableHistoryErrors({}) @@ -482,9 +488,15 @@ export default function BillsPage() { 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)) + // 展开中则立即重取,否则收起态下次展开会拉取 + if (expandedPayableIdsRef.current.has(payable.id)) { + await loadPayableHistory(payable.id) + } // 等待期间用户可能收起/展开,重取前重新读取展开状态 setCelebrationNotice({ open: true, diff --git a/components/mobile/PayableList.tsx b/components/mobile/PayableList.tsx index 0f9c113..6e6edd4 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -52,7 +52,8 @@ function renderPayableHistory( return

{historyError}

} if (payments === undefined) { - return

加载中…

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

展开以加载历史

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

还没有历史还款记录

diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index abbe4d0..19c86f1 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -1062,13 +1062,15 @@ struct BillsView: View { } .buttonStyle(.plain) } else if appState.isPayableHistoryStale(payable.id) { - // 刷新后缓存已清空但行仍展开:立即重取 - Text("加载中…") - .font(.caption2) - .foregroundStyle(WCColors.textSecondary) - .task(id: payable.id) { - await appState.retryPayableHistory(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) From 9cb5b1e84b12f65074b05b0820ed44c875362d36 Mon Sep 17 00:00:00 2001 From: hubo Date: Tue, 3 Nov 2026 23:00:36 +0800 Subject: [PATCH 10/10] fix(payables): close remaining review findings - omitRecordKey checks own properties (prototype keys no longer match) - loading cleanup is guarded by request identity and cache generation - drop the redundant post-payment refetch (loadData already reloads) - format paid_at with date-fns instead of slicing the ISO string - iOS: no prefetch racing refreshPayables; cancellation marks the row stale - payment-history limit lives in the shared fixture and both TS and Swift assert against it, so the two sides cannot drift silently --- app/(mobile)/bills/page.tsx | 26 +++---- components/mobile/PayableList.tsx | 3 +- .../Network/PayablesModels.swift | 5 ++ .../PayableCurrencyFixtureTests.swift | 9 +++ ios/WorldCredit/AppState.swift | 10 +-- ios/WorldCredit/Views/BillsView.swift | 4 +- lib/__tests__/payable-bank.test.ts | 8 ++ shared/fixtures/payable-currencies.json | 75 +++++++++++++++---- 8 files changed, 106 insertions(+), 34 deletions(-) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index deeb95d..b77a660 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -75,7 +75,8 @@ function tagSummary( /** 不可变地从 Record 中删除一个 key(无该 key 时返回原对象)。 */ function omitRecordKey(record: Record, key: string): Record { - if (!(key in record)) return record + // 只判断自有属性:`in` 会沿原型链命中 toString/constructor 等 + if (!Object.prototype.hasOwnProperty.call(record, key)) return record const next = { ...record } delete next[key] return next @@ -174,15 +175,18 @@ export default function BillsPage() { [payableId]: err instanceof Error ? err.message : '历史还款加载失败', })) } finally { - // 只清理自己这条:被新任务顶替时不能误删 - if (payableHistoryInFlight.current.get(payableId) === current) { + // 只清理自己这条:被新任务顶替或代次已变时不能误删(否则新请求期间不显示加载中) + 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 + }) } - setPayableHistoryLoading(prev => { - const next = new Set(prev) - next.delete(payableId) - return next - }) } })().finally(() => settle()) payableHistoryInFlight.current.set(payableId, current) @@ -493,11 +497,7 @@ export default function BillsPage() { const running = payableHistoryInFlight.current.get(payable.id) if (running) await running setPayablePayments(prev => omitRecordKey(prev, payable.id)) - // 展开中则立即重取,否则收起态下次展开会拉取 - if (expandedPayableIdsRef.current.has(payable.id)) { - await loadPayableHistory(payable.id) - } - // 等待期间用户可能收起/展开,重取前重新读取展开状态 + // 不在此处重取:紧随其后的 loadData 会统一清缓存并重拉展开行 setCelebrationNotice({ open: true, message: `🎉 已登记「${payable.name}」本期付款 ${currencySymbol(payable.currency)}${payable.amount.toLocaleString()}`, diff --git a/components/mobile/PayableList.tsx b/components/mobile/PayableList.tsx index 6e6edd4..1778b21 100644 --- a/components/mobile/PayableList.tsx +++ b/components/mobile/PayableList.tsx @@ -1,6 +1,7 @@ 'use client' import { useState } from 'react' +import { format } from 'date-fns' import { categoryLabel, PAYABLE_HISTORY_LIMIT, @@ -67,7 +68,7 @@ function renderPayableHistory( > {record.period} - {record.paid_at.slice(5)} + {format(new Date(record.paid_at), 'MM-dd')} {record.note ? ' · ' + record.note : ''} diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift index c2ccda5..277785c 100644 --- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift +++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/PayablesModels.swift @@ -190,6 +190,11 @@ 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 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 0ed6dec..4fdf632 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -788,11 +788,9 @@ public final class AppState { payableHistoryRevision[item.id] = (payableHistoryRevision[item.id] ?? 0) + 1 payablePayments[item.id] = nil payableHistoryErrors.remove(item.id) - // 历史重取与列表刷新互不依赖,并发执行减少一次往返等待 - async let history: Void = expandedPayableIds.contains(item.id) - ? loadPayableHistory(item.id) : () - async let refreshed: Void = refreshPayables() - _ = await (history, refreshed) + // 只刷新列表:refreshPayables 会清空历史缓存并标记 stale, + // 预取的结果必然被作废,交给视图按需重取 + await refreshPayables() } public func savePayable(_ draft: PayableDraft, existing: PayableItem?) async throws { @@ -852,9 +850,11 @@ public final class AppState { // 视图取消(收起/离屏):不是失败,保持待重取状态 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 展示; diff --git a/ios/WorldCredit/Views/BillsView.swift b/ios/WorldCredit/Views/BillsView.swift index 19c86f1..a7b75bc 100644 --- a/ios/WorldCredit/Views/BillsView.swift +++ b/ios/WorldCredit/Views/BillsView.swift @@ -1021,7 +1021,9 @@ struct BillsView: View { /// 与服务端 PAYABLE_HISTORY_LIMIT 对齐:达到上限时改称「最近 N 笔」。 private func payableHistoryLabel(_ records: [PayablePaymentRecord]?) -> String { guard let records, !records.isEmpty else { return "历史还款" } - if records.count >= 60 { return "最近 60 笔还款" } + if records.count >= PayablePaymentHistory.limit { + return "最近 \(PayablePaymentHistory.limit) 笔还款" + } return "历史还款 \(records.count) 笔" } diff --git a/lib/__tests__/payable-bank.test.ts b/lib/__tests__/payable-bank.test.ts index 6492107..63a7c75 100644 --- a/lib/__tests__/payable-bank.test.ts +++ b/lib/__tests__/payable-bank.test.ts @@ -1,6 +1,8 @@ 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, @@ -115,3 +117,9 @@ describe('recurring payable payment history', () => { 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/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 }