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