Skip to content

feat(payables): payment history and missing-statement placement - #53

Merged
hubo1989 merged 10 commits into
mainfrom
feat/payable-history
Nov 3, 2026
Merged

hubo1989 merged 10 commits into
mainfrom
feat/payable-history

Conversation

@hubo1989

@hubo1989 hubo1989 commented Nov 3, 2026

Copy link
Copy Markdown
Owner

变更

  • 新增 payables.getPayablePayments(成员守卫,按账期倒序读取 recurring_payable_payments)
  • Web 固定支出卡新增可折叠「历史还款」,首次展开按需加载
  • iOS 固定支出卡新增同款历史区,AppState 缓存,新登记还款后失效重取
  • 「缺账单」提醒从周期区移到卡片末尾,先看账单数据再看采集异常

测试

  • typecheck / lint / vitest 990 条
  • swift test 177 条
  • iOS 模拟器 BUILD SUCCEEDED

数据库

只读查询,无新增迁移。

…card end

- 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
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-03T09:28:02.077561Z
We couldn’t complete this review. Comment @codex review to try again.
d01da29 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7b4501e4-f21e-490e-8f14-40d671fbcd62
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

🔍 OpenCodeReview found 6 issue(s) in this PR.

  • ✅ Successfully posted inline: 6 comment(s)

const [payables, setPayables] = useState<PayableWithStatus[]>([])
const [payableFormOpen, setPayableFormOpen] = useState(false)
// 固定支出历史还款:按需加载,展开一次后缓存
const [payablePayments, setPayablePayments] = useState<Record<string, PayablePaymentRecord[]>>({})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
payablePayments 缓存缺少失效机制:用户通过 handlePayPayable 成功登记本期还款后(payRecurringPayable 会向 recurring_payable_payments 插入新记录,随后仅 loadData 刷新 payables 列表),已拉取过的历史列表不会刷新,刚登记的还款不会出现在「历史还款」中,展示与实际账目不一致。建议在 handlePayPayable 成功后删除该 payable 的缓存条目(下次展开自动重拉);另外当前展开无 in-flight 去重,缓存为空期间快速连续点击同一卡片会重复发起相同请求,可用 loading 标记一并防护。

Suggestion:

Suggested change
const [payablePayments, setPayablePayments] = useState<Record<string, PayablePaymentRecord[]>>({})
await payRecurringPayable(payable.id, payable.amount)
// 登记还款后失效历史缓存,下次展开重新拉取
setPayablePayments(prev => {
if (!(payable.id in prev)) return prev
const next = { ...prev }
delete next[payable.id]
return next
})

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +447 to +450
} catch {
// 拉取失败不阻断卡片:保留空历史,用户可再次展开重试
setPayablePayments(prev => ({ ...prev, [payableId]: [] }))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
catch 分支将 payablePayments[payableId] 缓存为空数组 [],而守卫条件 payablePayments[payableId] 对空数组恒为真值,下次展开直接 return,不会重新发起请求;同时 PayableRow 仅在 payments.length > 0 时渲染历史入口,失败后入口整体消失,用户在本次页面会话内无法重试——与注释「用户可再次展开重试」直接矛盾。建议失败时不写入缓存(key 保持 undefined),下次展开自然触发重试;若需区分「确无历史」与「加载失败」,可用独立的 error/loading 标记。

Suggestion:

Suggested change
} catch {
// 拉取失败不阻断卡片:保留空历史,用户可再次展开重试
setPayablePayments(prev => ({ ...prev, [payableId]: [] }))
}
} catch {
// 拉取失败不写缓存(key 保持 undefined),下次展开自动重试;
// 不阻断卡片本身
}

Comment thread components/mobile/PayableList.tsx Outdated
Comment on lines +183 to +189
{(payments?.length ?? 0) > 0 && (
<div className='mt-2.5 border-t border-d-border pt-2'>
<button
type='button'
onClick={e => { e.stopPropagation(); onToggleHistory?.() }}
className='flex w-full items-center justify-between text-[11px] font-semibold text-d-muted'
>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
历史还款区块(含「历史还款 N 笔」展开按钮)被 (payments?.length ?? 0) > 0 整体包裹,但 payments 只有点击该按钮后由父级调用 getPayablePayments 才会加载。初始渲染时 payments === undefined,按钮不出现 → 无法触发拉取 → payments 永远是 undefined,形成「先有鸡还是先有蛋」死循环,Web 端懒加载链路完全不可达(全库仅此处调用 onToggleHistory,卡片根节点也无 onClick 兜底)。建议把入口按钮改为始终可见(仅「加载完成且为空」时隐藏),长度判断只作用于列表本身;顺带可消除下方 payments! 的非空断言。

Suggestion:

Suggested change
{(payments?.length ?? 0) > 0 && (
<div className='mt-2.5 border-t border-d-border pt-2'>
<button
type='button'
onClick={e => { e.stopPropagation(); onToggleHistory?.() }}
className='flex w-full items-center justify-between text-[11px] font-semibold text-d-muted'
>
{(payments === undefined || payments.length > 0) && (
<div className='mt-2.5 border-t border-d-border pt-2'>
<button
type='button'
onClick={e => { e.stopPropagation(); onToggleHistory?.() }}
className='flex w-full items-center justify-between text-[11px] font-semibold text-d-muted'
>
<span>{payments ? `历史还款 ${payments.length} 笔` : '历史还款'}</span>

Comment on lines +185 to +189
<button
type='button'
onClick={e => { e.stopPropagation(); onToggleHistory?.() }}
className='flex w-full items-center justify-between text-[11px] font-semibold text-d-muted'
>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style · low
历史还款的展开/收起按钮缺少 aria-expanded 状态标注。同功能域内 BillCard 的「历史账单明细」折叠按钮(components/obsidian/BillsView.tsx)已设置 aria-expanded={historyOpen},此处新按钮只靠文案「展开/收起」传达状态,读屏用户无法感知该可折叠区块的当前状态。建议对齐补上 aria-expanded。

Suggestion:

Suggested change
<button
type='button'
onClick={e => { e.stopPropagation(); onToggleHistory?.() }}
className='flex w-full items-center justify-between text-[11px] font-semibold text-d-muted'
>
<button
type='button'
aria-expanded={historyOpen}
onClick={e => { e.stopPropagation(); onToggleHistory?.() }}
className='flex w-full items-center justify-between text-[11px] font-semibold text-d-muted'
>

Comment thread components/mobile/PayableList.tsx Outdated
Comment on lines +193 to +195
{historyOpen && (
<ul className='mt-1.5 flex flex-col gap-1'>
{payments!.map(record => (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
payments!.length 与 payments!.map 依赖外层条件渲染保证安全,非空断言可读性差,后续调整渲染条件时容易引入空指针回归。建议在区块顶部用局部常量收窄类型(const records = payments ?? []),后续逻辑直接使用 records;若按上一条建议把长度判断只作用于列表,断言可自然消除。

Suggestion:

Suggested change
{historyOpen && (
<ul className='mt-1.5 flex flex-col gap-1'>
{payments!.map(record => (
{historyOpen && payments && payments.length > 0 && (
<ul className='mt-1.5 flex flex-col gap-1'>
{payments.map(record => (

Comment on lines 767 to +769
_ = try await payablesService.pay(payableId: item.id, amount: amount)
// 新还款落库后清掉该笔历史缓存,下次展开看到最新记录
payablePayments[item.id] = nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
若该卡片的历史区块当前处于展开态,此处清缓存后 records 变为空数组,但 expandedPayableIds 仍包含该 id,UI 会立即显示"还没有历史还款记录"——而服务端此时已存在刚登记的一笔,且已展开的视图不会自动重拉(重拉仅在缓存为 nil 后重新展开时触发),财务数据短暂呈现错误。建议清缓存时同步移除展开态(收起卡片),使下次展开重新拉取。

Suggestion:

Suggested change
_ = try await payablesService.pay(payableId: item.id, amount: amount)
// 新还款落库后清掉该笔历史缓存,下次展开看到最新记录
payablePayments[item.id] = nil
_ = try await payablesService.pay(payableId: item.id, amount: amount)
// 新还款落库后清掉该笔历史缓存;若卡片正展开则一并收起,
// 避免已展开视图读到空缓存而误显示"还没有历史还款记录"
payablePayments[item.id] = nil
expandedPayableIds.remove(item.id)

Comment on lines +794 to +796
do {
payablePayments[payableId] = try await payablesService.fetchPayments(payableId: payableId)
} catch {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
await 前后的 check-then-act 竞态导致过期数据永久驻留:guard 判断缓存为 nil 后发起 fetchPayments 并挂起 MainActor。若拉取在途期间用户对该固定支出登记了还款,payPayable 会执行 payablePayments[id] = nil 作废缓存;随后本次在途请求完成后仍会把还款前的旧列表写回缓存。此后缓存非 nil,guard 永远直接 return,重新展开也不会重拉 —— UI 将无限期展示缺少最新一笔的历史(慢网络下展开后快速确认还款即可复现)。且此问题独立于既有确认项:即使清缓存时同步移除展开态,过期结果回填后仍会阻断后续重拉。建议 await 返回后校验请求仍然有效(仍处于展开态且缓存未被作废)再提交结果。

Suggestion:

Suggested change
do {
payablePayments[payableId] = try await payablesService.fetchPayments(payableId: payableId)
} catch {
do {
let records = try await payablesService.fetchPayments(payableId: payableId)
// await 期间 payPayable 可能已清缓存:过期结果不得回填,交由下次展开重拉
if expandedPayableIds.contains(payableId), payablePayments[payableId] == nil {
payablePayments[payableId] = records
}
} catch {

Comment on lines +794 to +799
do {
payablePayments[payableId] = try await payablesService.fetchPayments(payableId: payableId)
} catch {
// 拉取失败不阻断卡片展示;再次收起/展开会重试
payablePayments[payableId] = []
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
失败分支把缓存置为空数组 [],与上方 guard payablePayments[payableId] == nil else { return } 的重拉条件冲突:一旦拉取失败,缓存值为非 nil 的 [],后续展开在 guard 处直接 return,注释承诺的"再次收起/展开会重试"永远不会发生;错误同时被静默吞掉,该固定支出将一直显示"还没有历史还款记录"(仅再次登记还款清缓存才能恢复)。建议失败时保持缓存为 nil 以便下次展开真正重试。

Suggestion:

Suggested change
do {
payablePayments[payableId] = try await payablesService.fetchPayments(payableId: payableId)
} catch {
// 拉取失败不阻断卡片展示;再次收起/展开会重试
payablePayments[payableId] = []
}
do {
payablePayments[payableId] = try await payablesService.fetchPayments(payableId: payableId)
} catch {
// 失败时保持 nil,下次展开会真正重试;如需提示可另设错误态字段
payablePayments[payableId] = nil
}

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1024 to +1030
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: {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
展开入口不可达:if !records.isEmpty || expanded 把整个区块(含"展开"按钮)都藏在了条件里。但对任何从未展开过的固定支出,payablePayments[id] 必然为 nil(records 为空)且 expandedPayableIds 不包含该 id,条件恒为 false —— 按钮永远不渲染。而 records 只能通过点击该按钮触发 togglePayableHistory 拉取后才会非空,形成循环依赖:全仓库仅此一处调用 togglePayableHistory(已检索确认),没有任何其他入口能插入 expandedPayableIds 或填充缓存。结果是"历史还款"功能对用户完全不可用。建议把切换按钮行移出条件、无条件渲染,仅用 expanded 门控下方记录列表。

Suggestion:

Suggested change
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: {
let records = appState.payablePayments[payable.id] ?? []
let expanded = appState.expandedPayableIds.contains(payable.id)
// 切换行始终可见,否则首次展开无入口;仅记录列表按 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 {

Comment on lines +1046 to +1050
if records.isEmpty {
Text("还没有历史还款记录")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
展开后、首次拉取完成前 records 同样为空数组,此时会先显示"还没有历史还款记录",与"确无记录"、"加载失败"(见 AppState 失败分支写入空数组)三种状态无法区分,网络慢或失败时会对财务历史给出误导性结论。建议引入加载中/加载失败的状态提示,区分这三种情形。

Suggestion:

Suggested change
if records.isEmpty {
Text("还没有历史还款记录")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else {
if records.isEmpty {
// 建议区分"加载中"与"确无记录"(必要时再加失败态),
// 避免首次拉取完成前或失败后误显示空历史
Text("还没有历史还款记录")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else {

- 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
Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +424 to +430
// 新还款落库:清掉该笔历史缓存,展开时重新拉取
setPayablePayments(prev => {
if (!(payable.id in prev)) return prev
const next = { ...prev }
delete next[payable.id]
return next
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
还款成功后仅清除该笔历史缓存而不触发重新拉取:若该行历史当时处于展开态,payments 会回到 undefined 且 expandedPayableIds 仍包含该 id、historyError 为空,UI 将一直显示「加载中…」,用户必须手动收起再展开才能重新请求(拉取逻辑只存在于 handleTogglePayableHistory)。另外还存在窄竞态:用户先展开(请求在途)再立即还款,清缓存后在途响应落回 setPayablePayments,会写入缺失本次新还款的过期记录。建议把拉取逻辑提取为独立的 fetchPayablePayments(payableId),在清缓存后若该 payable 仍处于展开态则立即重新拉取,并在响应落回时校验请求仍有效。

Suggestion:

Suggested change
// 新还款落库:清掉该笔历史缓存,展开时重新拉取
setPayablePayments(prev => {
if (!(payable.id in prev)) return prev
const next = { ...prev }
delete next[payable.id]
return next
})
// 新还款落库:清掉该笔历史缓存;若该行正处于展开态,立即重新拉取,
// 避免界面停留在「加载中…」或渲染缺失新还款的过期记录
const wasExpanded = expandedPayableIds.has(payable.id)
setPayablePayments(prev => {
if (!(payable.id in prev)) return prev
const next = { ...prev }
delete next[payable.id]
return next
})
if (wasExpanded) void fetchPayablePayments(payable.id)

Comment thread components/mobile/PayableList.tsx Outdated
Comment on lines +197 to +204
{historyOpen && (
historyError ? (
<p className='mt-1.5 text-[11px] text-d-danger-ink'>{historyError}</p>
) : payments === undefined ? (
<p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
) : payments.length === 0 ? (
<p className='mt-1.5 text-[11px] text-d-muted'>还没有历史还款记录</p>
) : (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style · low
展开区域使用 historyError ? … : payments === undefined ? … : payments.length === 0 ? … 的三层嵌套三元表达式,违反嵌套三元禁用规范,可读性差且后续加分支会更难维护。建议改用 if/else 赋值给局部变量,或提取为独立的渲染辅助函数。

Suggestion:

Suggested change
{historyOpen && (
historyError ? (
<p className='mt-1.5 text-[11px] text-d-danger-ink'>{historyError}</p>
) : payments === undefined ? (
<p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
) : payments.length === 0 ? (
<p className='mt-1.5 text-[11px] text-d-muted'>还没有历史还款记录</p>
) : (
{historyOpen && renderHistoryBody()}

Comment thread ios/WorldCredit/AppState.swift Outdated
Comment on lines +780 to +782
if expandedPayableIds.contains(item.id) {
await loadPayableHistory(item.id)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · low
已展开历史时,loadPayableHistory(历史重取)与 refreshPayables(列表刷新)是两个互不依赖的只读刷新,却串行 await,登记还款后的等待时间多了约一次网络往返。可用 async let 并发执行两者(均为 @mainactor 方法,网络等待段可并发,状态写入仍在主 actor 串行化,安全)。

Suggestion:

Suggested change
if expandedPayableIds.contains(item.id) {
await loadPayableHistory(item.id)
}
if expandedPayableIds.contains(item.id) {
// 历史重取与列表刷新互不依赖:并发执行,少等一次往返
async let history: Void = loadPayableHistory(item.id)
await refreshPayables()
await history
} else {
await refreshPayables()
}

Comment thread lib/api/payables.server.ts Outdated
Comment on lines +139 to +144
const { data, error } = await query<PayablePaymentRecord>(
`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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · low
getPayablePayments 查询无 LIMIT,长期使用的固定支出会一次性返回全量历史记录(虽受 (payable_id, period) 唯一约束限制、量级有限,但与周期正相关且无上限)。建议参照分页/上限惯例加一个上限值(如 LIMIT 60),配合客户端倒序展示即可覆盖近期历史。另注:handleTogglePayableHistory 基于闭包判断缓存,快速连续切换展开时可能在缓存落位前发出并发重复请求(后写覆盖),影响轻微,可在提取拉取函数时一并做在途请求去重。

Suggestion:

Suggested change
const { data, error } = await query<PayablePaymentRecord>(
`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]
const { data, error } = await query<PayablePaymentRecord>(
`SELECT id, payable_id, period, amount, paid_at, note, created_at
FROM recurring_payable_payments
WHERE payable_id = ?
ORDER BY period DESC, created_at DESC
LIMIT 60`,
[payableId]

- 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
Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +431 to +435
if (expandedPayableIds.has(payable.id)) {
try {
const records = await getPayablePayments(payable.id)
setPayablePayments(prev => ({ ...prev, [payable.id]: records }))
} catch (err) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
与 handleTogglePayableHistory 中的加载逻辑几乎完全重复(相同的 try/catch、setPayablePayments 写缓存、setPayableHistoryErrors 清错/写错结构)。两处独立维护容易出现逻辑不同步(例如后续只在一处加 in-flight 守卫或错误兜底)。建议抽取共享的加载帮助函数,两处调用同一实现。

Suggestion:

Suggested change
if (expandedPayableIds.has(payable.id)) {
try {
const records = await getPayablePayments(payable.id)
setPayablePayments(prev => ({ ...prev, [payable.id]: records }))
} catch (err) {
if (expandedPayableIds.has(payable.id)) {
await loadPayableHistory(payable.id)
}
// 抽取后的共享帮助函数(供 handlePayPayable 重取与 handleTogglePayableHistory 共用)
const loadPayableHistory = async (payableId: string) => {
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
})
} catch (err) {
setPayableHistoryErrors(prev => ({
...prev,
[payableId]: err instanceof Error ? err.message : '历史还款加载失败',
}))
}
}

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +462 to +464
if (!willOpen || payablePayments[payableId]) return
try {
const records = await getPayablePayments(payableId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
缺少 in-flight 守卫:payablePayments[payableId] 是闭包里的旧状态,首个请求返回前快速重复点击「展开/收起」,或与 handlePayPayable 在展开态下触发的重取并发执行时,会对同一 payableId 发出多个重复的 getPayablePayments 请求(响应幂等、以后写入者为准,仅浪费请求,但属于应防住的竞态)。建议用 useRef 维护进行中请求的 id 集合,请求发起前查重、finally 中移除。

Suggestion:

Suggested change
if (!willOpen || payablePayments[payableId]) return
try {
const records = await getPayablePayments(payableId)
if (!willOpen || payablePayments[payableId]) return
if (payableHistoryInFlight.current.has(payableId)) return
payableHistoryInFlight.current.add(payableId)
try {
const records = await getPayablePayments(payableId)
// ...
} finally {
payableHistoryInFlight.current.delete(payableId)
}

Comment on lines +40 to +41
/** 历史还款展开区:加载中 / 失败 / 空 / 列表四态,避免嵌套三元。 */
function renderPayableHistory(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
新增的 renderPayableHistory 插在了 PayableRow 原有 JSDoc(「单条固定支出卡。从 PayableList 拆出……」)与 PayableRow 函数之间,使该文档注释与其目标函数被隔开、视觉上像是 renderPayableHistory 的说明。建议把 renderPayableHistory 移到 PayableRow 的 JSDoc 之前(或组件之后),保持注释与函数紧邻。

Suggestion:

Suggested change
/** 历史还款展开区:加载中 / 失败 / 空 / 列表四态,避免嵌套三元。 */
function renderPayableHistory(
/** 历史还款展开区:加载中 / 失败 / 空 / 列表四态,避免嵌套三元。 */
function renderPayableHistory(/* ... */) { /* ... */ }
/**
* 单条固定支出卡。从 PayableList 拆出:账单页现在把固定支出混进主列表统一排序。
* ……(原有 JSDoc 保持紧邻 PayableRow)
*/
export function PayableRow({ /* ... */ }: PayableRowProps) { /* ... */ }

Comment on lines +46 to +51
if (historyError) {
return <p className='mt-1.5 text-[11px] text-d-danger-ink'>{historyError}</p>
}
if (payments === undefined) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
错误态优先于加载态会造成旧错误滞留:上次展开失败的错误会一直留在 payableHistoryErrors 中,用户收起再展开触发重试时,请求进行中面板仍显示上次的失败文案而不是「加载中…」,直到成功才跳成列表,期间提示有误导性。建议不要在此调整判断顺序(失败后面板保持展开、无新请求时会需要常驻错误文案),而是在发起重取的加载路径上先清掉该笔旧错误——可与已确认的共享加载函数一并处理。

Comment on lines +806 to +808
expandedPayableIds.insert(payableId)
guard payablePayments[payableId] == nil else { return }
await loadPayableHistory(payableId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
历史缓存仅在本地 payPayable/deletePayable(及会话重置)时作废,而 refreshPayables(下拉刷新)会从服务端重取 payables 列表却不清 payablePayments;togglePayableHistory 中只要缓存非 nil 就直接复用(guard payablePayments[payableId] == nil else { return }),收起再展开也不会重拉。多端场景下另一台设备登记还款后,本端下拉刷新虽更新了列表金额,展开的历史还款仍是旧数据,用户看到的记录与汇总和实际不符。建议在 refreshPayables 成功路径中作废缓存并对已展开的条目按需重取,例如:let expandedIds = expandedPayableIds; payablePayments.removeAll(); for id in expandedIds { await loadPayableHistory(id) }(未展开的留待下次展开时按需拉取,成本极低)。

Suggestion:

Suggested change
expandedPayableIds.insert(payableId)
guard payablePayments[payableId] == nil else { return }
await loadPayableHistory(payableId)
expandedPayableIds.insert(payableId)
guard payablePayments[payableId] == nil else { return }
await loadPayableHistory(payableId)
// refreshPayables 成功路径中:
payables = items
payablesError = nil
// 远端列表已刷新(含其他设备的还款):作废历史缓存,
// 已展开的立即重取,未展开的下次展开时按需重拉
let expandedIds = expandedPayableIds
payablePayments.removeAll()
for id in expandedIds { await loadPayableHistory(id) }

Comment on lines +814 to +817
do {
let records = try await payablesService.fetchPayments(payableId: payableId)
// 拉取在途期间发生还款会递增版本号,过期响应丢弃
guard payableHistoryRevision[payableId] == revision else { return }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
演示模式/UI 测试不变量被绕过:refreshPayables 明确约定「演示模式(--demo-mode)与 UI 测试都不拉在线固定支出」以保持演示态干净,但 loadDemoData 注入的演示 payable(id 为 demo-payable-*)展开历史时会真实发起 getPayablePayments RPC。UI 测试模式下 apiClient 使用 OfflineUITestNetworkSession 必然失败,每个演示条目展开后都显示「历史还款加载失败」,演示体验像出了故障。建议在 togglePayableHistory/loadPayableHistory 中加同样的 UITestConfiguration/--demo-mode 守卫(直接返回空记录),或在 BillsView 对演示数据隐藏历史区块。

Suggestion:

Suggested change
do {
let records = try await payablesService.fetchPayments(payableId: payableId)
// 拉取在途期间发生还款会递增版本号,过期响应丢弃
guard payableHistoryRevision[payableId] == revision else { return }
/// 展开/收起某笔固定支出的历史;首次展开才拉取,失败保留空列表供重试。
public func togglePayableHistory(_ payableId: String) async {
// 演示模式与 UI 测试不拉在线固定支出(与 refreshPayables 同款守卫),演示数据直接按空历史处理
guard !UITestConfiguration.isEnabled,
!CommandLine.arguments.contains("--demo-mode") else { return }
if expandedPayableIds.contains(payableId) {
expandedPayableIds.remove(payableId)
return
}

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1046 to +1050
if expanded {
if failed {
Text("历史还款加载失败,请再次展开重试")
.font(.caption2)
.foregroundStyle(WCColors.dangerInk)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
重试在途期间仍显示旧的失败文案:loadPayableHistory 只在成功后才移除 payableHistoryErrors,失败后经「收起→展开」重试时,请求在途阶段 failed 仍为 true,展开区显示「历史还款加载失败,请再次展开重试」而不是「加载中…」,用户无法感知重试正在进行;且与 payPayable 路径(先 remove 错误再重取,正确显示加载中)行为不一致。建议在发起加载前先移除该 payable 的错误标记,让重试期间展示加载态。

Suggestion:

Suggested change
if expanded {
if failed {
Text("历史还款加载失败,请再次展开重试")
.font(.caption2)
.foregroundStyle(WCColors.dangerInk)
private func loadPayableHistory(_ payableId: String) async {
let revision = (payableHistoryRevision[payableId] ?? 0) + 1
payableHistoryRevision[payableId] = revision
// 发起重取即清除错误标记:重试在途期间展示「加载中…」而非旧失败文案
payableHistoryErrors.remove(payableId)
do {

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1047 to +1050
if failed {
Text("历史还款加载失败,请再次展开重试")
.font(.caption2)
.foregroundStyle(WCColors.dangerInk)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
加载失败后行仍处于展开态、按钮显示「收起」,而提示语是「请再次展开重试」:此时第一次点击执行的是收起(togglePayableHistory 先 remove expandedPayableIds),用户实际需要点两次(收起 → 展开)才能触发重试,与提示语的用户预期不符。建议把错误文案本身做成重试按钮,直接调用重载逻辑,一次点击即完成重试。

Suggestion:

Suggested change
if failed {
Text("历史还款加载失败,请再次展开重试")
.font(.caption2)
.foregroundStyle(WCColors.dangerInk)
if failed {
Button {
Task { await appState.retryPayableHistory(payable.id) }
} label: {
Text("历史还款加载失败,点此重试")
.font(.caption2)
.foregroundStyle(WCColors.dangerInk)
}
.buttonStyle(.plain)
}
// AppState 中配套新增:
public func retryPayableHistory(_ payableId: String) async {
guard expandedPayableIds.contains(payableId) else { return }
await loadPayableHistory(payableId)
}

Comment thread lib/api/payables.server.ts Outdated
Comment on lines +143 to +144
ORDER BY period DESC, created_at DESC
LIMIT 60`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
LIMIT 60 为业务硬编码,且超出 60 条的历史被静默截断:PayableRow 展开按钮上的「N 笔」计数来自返回数组,最多显示「60 笔」,用户会误以为已看到全部历史(按月登记一笔,60 条即 5 年)。建议抽取具名常量并在前端文案上注明「最近 N 条」,或调整计数语义,避免截断误导。

Suggestion:

Suggested change
ORDER BY period DESC, created_at DESC
LIMIT 60`,
/** 历史还款最多返回条数;前端「N 笔」计数与截断文案依赖此值。 */
const MAX_PAYABLE_HISTORY = 60
// ...
ORDER BY period DESC, created_at DESC
LIMIT ${MAX_PAYABLE_HISTORY}`,

…tion

- 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
Comment on lines +96 to +97
// 固定支出历史还款:按需加载,展开一次后缓存
const [payablePayments, setPayablePayments] = useState<Record<string, PayablePaymentRecord[]>>({})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
历史还款缓存只有「本机还款成功」(handlePayPayable)这一个失效入口,而页面所有全量刷新路径——loadData(手动重试 onRetry、BillDraftsPanel onChanged、PayableForm onSuccess)与 handleSync(邮件同步)——都不会触碰它。结果:用户展开过某笔固定支出的历史后,若在另一设备/浏览器登记了付款,回到本页点「同步」或触发任意 loadData,已缓存(尤其仍处于展开态)的历史列表依旧显示旧数据,且因缓存命中(payablePayments[payableId] 为真)收起再展开也不会重拉,只能等该笔在本机再次还款才刷新。本 PR 同期新增了 iOS 端 PayablePaymentRecord 客户端,多端读写是常态场景。建议在 loadData 成功后清空 payablePayments(可保留 expandedPayableIds,使展开中的项自动重新拉取)。

Suggestion:

Suggested change
// 固定支出历史还款:按需加载,展开一次后缓存
const [payablePayments, setPayablePayments] = useState<Record<string, PayablePaymentRecord[]>>({})
// 固定支出历史还款:按需加载,展开一次后缓存;
// loadData 全量刷新时整体失效,让展开中的项重新拉取(跨设备产生的还款才能出现在历史里)
const [payablePayments, setPayablePayments] = useState<Record<string, PayablePaymentRecord[]>>({})

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +425 to +430
setPayablePayments(prev => {
if (!(payable.id in prev)) return prev
const next = { ...prev }
delete next[payable.id]
return next
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
「从 Record 状态中不可变地删除单个 key」的同构逻辑在本文件新增代码中出现了三处(此处清缓存、loadPayableHistory 成功后清错误、失败时写错误),仅条件略有差异。建议抽取一个小工具函数(如 omitRecordKey(prev, id))复用,避免后续调整失效策略时漏改其中一处造成状态不一致。

Suggestion:

Suggested change
setPayablePayments(prev => {
if (!(payable.id in prev)) return prev
const next = { ...prev }
delete next[payable.id]
return next
})
// omitRecordKey: 返回删除指定 key 后的新对象;key 不存在时原样返回
setPayablePayments(prev => omitRecordKey(prev, payable.id))

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +431 to +433
if (expandedPayableIds.has(payable.id)) {
await loadPayableHistory(payable.id)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
还款成功后 loadPayableHistory 会复用 payableHistoryInFlight 中的在途旧请求(发起于本次还款之前),其结果不含刚登记的付款却会回写缓存,导致展开中的历史列表看不到刚登记的这笔,需收起再展开才能刷新。建议先等在途请求落定再重取,让旧结果被随后的新请求覆盖。

Suggestion:

Suggested change
if (expandedPayableIds.has(payable.id)) {
await loadPayableHistory(payable.id)
}
if (expandedPayableIds.has(payable.id)) {
// 先等在途请求落定再重取:直接复用旧 Promise 会把不含本次还款的陈旧结果回写缓存
await payableHistoryInFlight.current.get(payable.id)
await loadPayableHistory(payable.id)
}

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +452 to +454
const task = (async () => {
try {
const records = await getPayablePayments(payableId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
该函数与 PayableList 的「错误分支不可达」问题相关:失败时仅写错误、payments 保持 undefined,若按上述把 historyError 判定前置,则重试在途时会先命中残留旧错误而显示错误文案,违背 PayableList 注释「重试在途时优先显示加载中」。建议在发起请求的入口处先清除该笔旧错误,使 undefined(在途)始终对应「加载中」、错误仅在落定失败时短暂呈现。

Suggestion:

Suggested change
const task = (async () => {
try {
const records = await getPayablePayments(payableId)
const task = (async () => {
// 进入在途即清旧错误:配合 PayableList「错误优先」的判定顺序,重试期间能回到「加载中」
setPayableHistoryErrors(prev => {
if (!prev[payableId]) return prev
const next = { ...prev }
delete next[payableId]
return next
})
try {
const records = await getPayablePayments(payableId)

Comment thread components/mobile/PayableList.tsx Outdated
Comment on lines +29 to +30
/** 与服务端 LIMIT 保持一致:超出时文案改称「最近 N 笔」。 */
const PAYABLE_HISTORY_LIMIT = 60

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
PAYABLE_HISTORY_LIMIT = 60 与 lib/api/payables.server.ts 中导出的同名常量是跨端手工复制的双份定义,一旦服务端调整截断上限而前端未同步,展开区「最近 60 笔还款」文案将与实际条数不符。仓库已有客户端安全的 lib/api/payables.shared.ts 模块(与 payables.ts 顶部「纯类型与纯函数走 .shared」的约定一致),建议把常量下沉到该处,两端同源引用。

Suggestion:

Suggested change
/** 与服务端 LIMIT 保持一致:超出时文案改称「最近 N 笔」。 */
const PAYABLE_HISTORY_LIMIT = 60
// lib/api/payables.shared.ts 中单点定义,payables.server.ts 与本组件共同引用,避免跨端复制失联
import { PAYABLE_HISTORY_LIMIT } from '@/lib/api/payables.shared'

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Task { await appState.togglePayableHistory(payable.id) }
} label: {
HStack {
Text(records.map { "历史还款 \($0.count) 笔" } ?? "历史还款")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
「历史还款 ($0.count) 笔」展示的 count 受服务端 LIMIT 60(PAYABLE_HISTORY_LIMIT)截断:还款超过 60 笔时,这里显示的是截断后的条数而非真实总数,「历史还款 60 笔」会误导用户以为历史只有 60 笔。服务端注释明确该上限对应 Web 端「最近 N 笔」的截断文案,iOS 文案未体现这一语义。建议文案改为体现截断(如「最近 60 笔还款」)或由服务端额外返回总数。

Suggestion:

Suggested change
Text(records.map { "历史还款 \($0.count) 笔" } ?? "历史还款")
Text(records.map { "最近 60 笔还款(\($0.count) 笔)" } ?? "历史还款")

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1046 to +1052
if expanded {
if records == nil {
// 在途(含重试)优先显示加载中
Text("加载中…")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else if failed {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
失败分支不可达:loadPayableHistory 的失败路径会同时把 payablePayments[payableId] 置 nil 并写入 payableHistoryErrors(成功路径则清错误标记),因此「failed == true」时 records 恒为 nil,永远先命中第一分支显示「加载中…」。后果:加载失败(网络抖动、服务端错误)后该行会永久显示「加载中…」——既无失败提示也无重试入口(且此时并无在途请求),「加载失败,点此重试」按钮成为死代码,与 AppState「记录错误供 UI 展示」的设计意图相矛盾。建议把 failed 判断提到 records == nil 之前;同时由于重试不能复用 togglePayableHistory(已知问题:会先收起),需在 AppState 提供直接触发 loadPayableHistory 的重试入口(如 retryPayableHistory(_:))。

Suggestion:

Suggested change
if expanded {
if records == nil {
// 在途(含重试)优先显示加载中
Text("加载中…")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else if failed {
if expanded {
// 失败态必须先于「加载中」判断:失败时缓存必为 nil,
// 先判 records == nil 会让失败被永久渲染为加载中、重试按钮不可达
if failed {
Button {
Task { await appState.retryPayableHistory(payable.id) }
} label: {
Text("加载失败,点此重试")
.font(.caption2.weight(.semibold))
.foregroundStyle(WCColors.dangerInk)
}
.buttonStyle(.plain)
} else if records == nil {
Text("加载中…")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else if let records {

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1054 to +1056
Task { await appState.togglePayableHistory(payable.id) }
} label: {
Text("加载失败,点此重试")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
该「重试」按钮仅在 expanded=true 且加载失败时渲染,点击调用 togglePayableHistory 会先命中 expandedPayableIds.contains 分支直接收起并 return,永远走不到 loadPayableHistory 的重新拉取逻辑——「点此重试」实际执行的是收起操作,用户需再点一次「展开」才会真正重试,失败恢复的显式入口与语义相反。建议在 AppState 提供独立重试入口(如公开 retryPayableHistory(_:),内部直接调用 loadPayableHistory),此按钮改调该方法;toggle 仅保留给「历史还款/展开/收起」主按钮。

Suggestion:

Suggested change
Task { await appState.togglePayableHistory(payable.id) }
} label: {
Text("加载失败,点此重试")
Task { await appState.retryPayableHistory(payable.id) }
} label: {
Text("加载失败,点此重试")

Comment thread lib/api/payables.server.ts Outdated
Comment on lines +124 to +125
/** 历史还款返回上限:与前端「最近 N 笔」文案一致。 */
export const PAYABLE_HISTORY_LIMIT = 60

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
PAYABLE_HISTORY_LIMIT = 60 在服务端与客户端重复定义(components/mobile/PayableList.tsx 也硬编码了同值常量,用于「最近 60 笔还款」文案及“可能还有更多”的判断)。两端各自维护,未来调整上限时容易漂移失配。建议将该常量移入 payables.shared.ts(该模块专为服务端/浏览器共享常量而设),前端从 shared 导入,实现单一数据源。

Suggestion:

Suggested change
/** 历史还款返回上限:与前端「最近 N 笔」文案一致。 */
export const PAYABLE_HISTORY_LIMIT = 60
// payables.shared.ts(供服务端与前端共用,避免两端各写一份 60)
export const PAYABLE_HISTORY_LIMIT = 60

Comment on lines +142 to +149
const { data, error } = await query<PayablePaymentRecord>(
`SELECT id, payable_id, period, amount, paid_at, note, created_at
FROM recurring_payable_payments
WHERE payable_id = ?
ORDER BY period DESC, created_at DESC
LIMIT ${PAYABLE_HISTORY_LIMIT}`,
[payableId]
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
LIMIT 值通过模板字符串拼进 SQL 文本。当前值是数字常量、无注入风险,但与代码库惯例不一致:其他动态 limit 均使用绑定参数(如 bills.server.ts 的 LIMIT ? + [limit]、admin.server.ts、gmail-ledger.server.ts)。改用 LIMIT ? 绑定可保持风格统一,也避免将来 limit 变为动态入参时留下注入隐患。

Suggestion:

Suggested change
const { data, error } = await query<PayablePaymentRecord>(
`SELECT id, payable_id, period, amount, paid_at, note, created_at
FROM recurring_payable_payments
WHERE payable_id = ?
ORDER BY period DESC, created_at DESC
LIMIT ${PAYABLE_HISTORY_LIMIT}`,
[payableId]
)
const { data, error } = await query<PayablePaymentRecord>(
`SELECT id, payable_id, period, amount, paid_at, note, created_at
FROM recurring_payable_payments
WHERE payable_id = ?
ORDER BY period DESC, created_at DESC
LIMIT ?`,
[payableId, PAYABLE_HISTORY_LIMIT]
)

- 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
Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +152 to +154
// 全量刷新:历史缓存可能过期,清空后按需重拉
setPayablePayments({})
setPayableHistoryErrors({})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
清空历史缓存但未处理已展开的行:expandedPayableIds 未重置,清空后也没有对已展开项重拉。此时已展开行 payments=undefined、loading=false、无错误,renderPayableHistory 会落入 payments === undefined 分支永久显示「加载中…」,没有自动重拉也没有重试入口,只能手动收起再展开恢复。触发路径高频:每次还款成功后的 await loadData()(第 447 行)、同步刷新(第 192/235/321 行)、BillDraftsPanel onChanged(第 538 行)都会命中。建议清空缓存后对 expandedPayableIds 中的每一项调用 loadPayableHistory 立即重拉(需配合将 payableHistoryInFlight / loadPayableHistory 声明上移到 loadData 之前,见另一条意见);若想改动最小,也可在此处同步 setExpandedPayableIds(new Set()),让展开态与缓存一起失效、下次展开重拉。

Suggestion:

Suggested change
// 全量刷新:历史缓存可能过期,清空后按需重拉
setPayablePayments({})
setPayableHistoryErrors({})
// 全量刷新:历史缓存可能过期,清空后按需重拉;
// 已展开的行缓存被清空后不会自动重拉,会永久停留在「加载中…」,需立即重拉
setPayablePayments({})
setPayableHistoryErrors({})
for (const id of expandedPayableIdsRef.current) void loadPayableHistory(id)

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +436 to +442
// 新还款落库:清掉该笔历史缓存;先等在途旧请求落定,避免旧结果回写覆盖新数据
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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
竞态处理不完整:await running 落定后,旧任务体(loadPayableHistory 内)仍会无条件 setPayablePayments 回写不包含新还款的过期记录;且 expandedPayableIds.has 是本次渲染的快照,若用户在 payRecurringPayable 的网络窗口期间展开该行,这里会判定为「收起」而跳过重拉。虽然随后的 await loadData() 会清空全部缓存兜底,但仍有两个窗口会暴露旧数据:(1) loadData 清空发生前的窗口内用户展开该行,会命中旧缓存,看到缺少刚登记还款的历史;(2) loadData 的前置请求(getCardsWithBillsSummary/getHolders)失败进入 catch 时清空不会执行,过期记录留存,之后展开在 payablePayments[payableId] 处短路(第 495 行),长期显示旧数据。建议改为「令牌失效」模式:为每个 payableId 维护请求代数,失效缓存时递增令牌,任务回写前校验令牌是否仍为最新、过期则丢弃结果;同时 expanded 判断改用 ref 读取最新展开态,不依赖 await 顺序与 loadData 兜底。

Suggestion:

Suggested change
// 新还款落库:清掉该笔历史缓存;先等在途旧请求落定,避免旧结果回写覆盖新数据
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)
}
// 新还款落库:失效该笔历史缓存(令牌 +1 使在途旧请求的回写作废)
invalidatePayableHistory(payable.id)
if (expandedPayableIdsRef.current.has(payable.id)) {
await loadPayableHistory(payable.id)
}

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +453 to +455
/** 展开/收起固定支出历史:首次展开才拉取该笔记录。 */
// 同一笔的在途请求:并发点击或还款后重取都复用同一个 Promise,避免重复 RPC
const payableHistoryInFlight = useRef<Map<string, Promise<void>>>(new Map())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
声明顺序与依赖方向颠倒:payableHistoryInFlight 与 loadPayableHistory 被上方的 handlePayPayable(第 438/441 行)引用,却声明在其后。运行时因事件回调延迟执行不会触发 TDZ,但阅读时依赖关系不直观,后续重构(如提前调用、抽离子组件)时容易踩暂时性死区。建议将 ref 与 loadPayableHistory 整体上移到 handlePayPayable 之前;这同时能让 loadData(第 142 行)复用 loadPayableHistory,修复「刷新后已展开行卡在加载中」的问题。

Suggestion:

Suggested change
/** 展开/收起固定支出历史:首次展开才拉取该笔记录。 */
// 同一笔的在途请求:并发点击或还款后重取都复用同一个 Promise,避免重复 RPC
const payableHistoryInFlight = useRef<Map<string, Promise<void>>>(new Map())
// 同一笔的在途请求:并发点击或还款后重取都复用同一个 Promise,避免重复 RPC
const payableHistoryInFlight = useRef<Map<string, Promise<void>>>(new Map())
/** 拉取并写入历史缓存;同一 payableId 复用进行中的请求。 */
const loadPayableHistory = useCallback(/* ... */)
/** 登记固定支出本期付款。账期由服务端决定,客户端只传金额。 */
const handlePayPayable = async (payable: PayableWithStatus) => { /* ... */ }

Comment on lines +53 to +55
if (payments === undefined) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
「加载中…」的

(含完全相同的 className)与函数开头 historyLoading 分支重复;两个分支输出一致,可合并为 historyLoading || payments === undefined,避免后续调整文案或样式时改一漏一。另外该分支隐含「必有在途或即将发生的加载」假设——父级 loadData 清空缓存后该假设不成立时,会永久停留在此态(详见页面侧 loadData 的评审意见)。

Suggestion:

Suggested change
if (payments === undefined) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}
// 在途优先:重试时不显示上一次的错误;undefined 视同尚未拉到结果
if (historyLoading || payments === undefined) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}

Comment thread ios/WorldCredit/AppState.swift Outdated
Comment on lines +651 to +656
let expanded = expandedPayableIds
payablePayments = [:]
payableHistoryErrors = []
for id in expanded where payables.contains(where: { $0.id == id }) {
await loadPayableHistory(id)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · medium
每次 refreshPayables 都整体清空 payablePayments 并对已展开项逐个串行 await loadPayableHistory(id):该函数被首屏加载、sync、pay/save/deletePayable、下拉刷新等多条高频路径调用,展开 N 项时每次刷新追加 N 次串行 RPC 往返,且清空缓存会让已展示历史的行闪回「加载中…」;此外 payPayable 中 async let history 的直接重取与这里的重拉会对同一 id 重复请求(仅靠 revision 丢弃旧响应,多耗一次 RPC)。建议用 TaskGroup 并行重拉以缩短刷新在途时间,并考虑去掉 payPayable 中的直接重取(item.id 已展开时 refreshPayables 的重拉循环必然覆盖它)。

Suggestion:

Suggested change
let expanded = expandedPayableIds
payablePayments = [:]
payableHistoryErrors = []
for id in expanded where payables.contains(where: { $0.id == id }) {
await loadPayableHistory(id)
}
let expanded = expandedPayableIds.filter { id in payables.contains(where: { $0.id == id }) }
payablePayments = [:]
payableHistoryErrors = []
// 并行重拉:各项互不依赖,串行 await 会把 N 次往返线性叠加到每条刷新路径上
await withTaskGroup(of: Void.self) { group in
for id in expanded {
group.addTask { @MainActor in await self.loadPayableHistory(id) }
}
}

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1033 to +1035
Text(records.map { "历史还款 \($0.count) 笔" } ?? "历史还款")
.font(.caption.weight(.semibold))
.foregroundStyle(WCColors.textSecondary)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
历史还款计数在达到服务端截断上限时失真:服务端 getPayablePayments 用 PAYABLE_HISTORY_LIMIT = 60 截断(lib/api/payables.shared.ts,按账期倒序只返回最近 60 条),Web 端 PayableList.tsx 在达到上限时专门显示「最近 60 笔还款」来表达截断语义;而 iOS 这里无条件显示「历史还款 ($0.count) 笔」。固定支出(房租/贷款)还款超过 60 期很常见,届时会把 60 误标为还款总数,与 Web 端文案也不一致。建议与该常量对齐:达到上限时显示「最近 60 笔还款」之类的截断文案。

Suggestion:

Suggested change
Text(records.map { "历史还款 \($0.count) 笔" } ?? "历史还款")
.font(.caption.weight(.semibold))
.foregroundStyle(WCColors.textSecondary)
Text(records.map {
$0.count >= 60 ? "最近 60 笔还款" : "历史还款 \($0.count) 笔"
} ?? "历史还款")
.font(.caption.weight(.semibold))
.foregroundStyle(WCColors.textSecondary)

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1046 to +1052
if expanded {
if records == nil {
// 在途(含重试)优先显示加载中
Text("加载中…")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else if failed {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
分支顺序错误导致失败态不可达:AppState.loadPayableHistory 的失败路径会将 payablePayments[payableId] 置为 nil 并写入 payableHistoryErrors(二者总是同时发生,且其他任何写 error 的路径都不会保留非空缓存),即 failed == true 时 records 必为 nil。此处 records == nil(显示「加载中…」)排在 failed(重试按钮)之前,因此历史加载失败后 UI 永远停在「加载中…」,「加载失败,点此重试」按钮成为死代码,用户无法感知失败也无法重试,与 retryPayableHistory 的设计意图相悖。末尾的兜底 else { Text("加载中…") } 同样因分支穷尽不可达。建议把 failed 判断提前到 records == nil 之前。

Suggestion:

Suggested change
if expanded {
if records == nil {
// 在途(含重试)优先显示加载中
Text("加载中…")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else if failed {
if expanded {
if failed {
// 失败态优先:failed 时 records 必为 nil,先于「加载中」判断否则重试按钮不可达
Button {
Task { await appState.retryPayableHistory(payable.id) }
} label: {
Text("加载失败,点此重试")
.font(.caption2.weight(.semibold))
.foregroundStyle(WCColors.dangerInk)
}
.buttonStyle(.plain)
} else if records == nil {
Text("加载中…")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else if let records {

Comment thread lib/api/payables.server.ts Outdated
Comment on lines +147 to +149
ORDER BY period DESC, created_at DESC
LIMIT ${PAYABLE_HISTORY_LIMIT}`,
[payableId]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
LIMIT 值通过模板插值拼接进 SQL。虽然 PAYABLE_HISTORY_LIMIT 是模块常量、无注入风险,但本文件(以及 lib/db/helpers.ts 的 query/execute 封装)的约定是所有值都用 ? 占位符绑定(D1 支持 LIMIT ?)。建议改为参数绑定,维持「值一律参数化」的不变量,避免后续维护者模仿此处把动态值也插值进 SQL。

Suggestion:

Suggested change
ORDER BY period DESC, created_at DESC
LIMIT ${PAYABLE_HISTORY_LIMIT}`,
[payableId]
ORDER BY period DESC, created_at DESC
LIMIT ?`,
[payableId, PAYABLE_HISTORY_LIMIT]

- 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
Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +476 to +478
setPayablePayments(prev => omitRecordKey(prev, payable.id))
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
还款成功后先清缓存再 await running 存在缓存陈旧问题:在途旧请求在还款前发出,其成功回调会把不含本次新还款的过期记录回写 payablePayments;若等待期间(或回写后、判断展开态前)用户已收起该行,则不会重拉,之后重新展开时 handleTogglePayableHistory 命中这条过期缓存直接展示,新还款不可见。建议把清缓存挪到旧请求落定之后,保证无论行当前展开与否,缓存都不会留下过期数据。

Suggestion:

Suggested change
setPayablePayments(prev => omitRecordKey(prev, payable.id))
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running
// 旧请求在还款前发出,落定时会把过期记录回写缓存,需在其后再清一次;
// 收起态下保持缓存为空,确保下次展开时重新请求,避免展示不含新还款的旧历史
setPayablePayments(prev => omitRecordKey(prev, payable.id))

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +480 to +482
if (expandedPayableIdsRef.current.has(payable.id)) {
await loadPayableHistory(payable.id)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · low
定向重取与紧随其后的 loadData() 重复:handlePayPayable 成功路径最后总会 await loadData(),而 loadData 内部已无条件清空 payablePayments/payableHistoryErrors 并对 expandedPayableIdsRef 中仍展开的行统一重拉。此处的 await loadPayableHistory 会在正常路径下发起第二次相同 RPC,结果随即被 loadData 清掉,且在展开态下把成功提示(setCelebrationNotice)延后了一个网络往返。建议删除该定向重取、直接依赖 loadData 的全量刷新与展开行重拉(缓存清理保持在在途请求落定之后即可保证不回写过期数据,与既有修复建议兼容);若有意保留以防 loadData 初次 Promise.all 失败时缓存缺失,也应将成功提示提前到重取之前。

Suggestion:

Suggested change
if (expandedPayableIdsRef.current.has(payable.id)) {
await loadPayableHistory(payable.id)
}
// 历史缓存刷新交给下方 loadData():它已清空缓存并对仍展开的行统一重拉,
// 此处不再定向重取,避免同一笔在一秒内重复请求两次、也避免延迟成功提示。

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +496 to +502
const willOpen = !expandedPayableIds.has(payableId)
setExpandedPayableIds(prev => {
const next = new Set(prev)
if (willOpen) next.add(payableId)
else next.delete(payableId)
return next
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
willOpen 基于渲染快照 expandedPayableIds 判断开合方向,而实际更新发生在函数式 setExpandedPayableIds 内部;同一渲染周期内多次触发时方向判断可能基于过期快照,导致展开态与是否发起加载的意图不一致。页面已有 expandedPayableIdsRef 专为异步回调读取最新值,建议改用它判断方向,并可一并从 useCallback 依赖中移除 expandedPayableIds。

Suggestion:

Suggested change
const willOpen = !expandedPayableIds.has(payableId)
setExpandedPayableIds(prev => {
const next = new Set(prev)
if (willOpen) next.add(payableId)
else next.delete(payableId)
return next
})
const willOpen = !expandedPayableIdsRef.current.has(payableId)
setExpandedPayableIds(prev => {
const next = new Set(prev)
if (willOpen) next.add(payableId)
else next.delete(payableId)
return next
})

Comment thread components/mobile/PayableList.tsx Outdated
Comment on lines +47 to +52
if (historyLoading || payments === undefined) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}
if (historyError) {
return <p className='mt-1.5 text-[11px] text-d-danger-ink'>{historyError}</p>
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
renderPayableHistory 首个分支条件 historyLoading || payments === undefined 导致 historyError 分支不可达:page.tsx 的 loadPayableHistory 失败时只写入 payableHistoryErrors、不写 payments(catch 中没有 setPayablePayments),因此请求失败后 payments 恒为 undefined,这里永远命中「加载中…」,错误文案成为死代码,用户看不到失败原因,与页面侧「错误就地展示」的设计注释矛盾。建议先按在途判断,再对「非在途且无缓存」的状态区分错误与加载。

Suggestion:

Suggested change
if (historyLoading || payments === undefined) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}
if (historyError) {
return <p className='mt-1.5 text-[11px] text-d-danger-ink'>{historyError}</p>
}
if (historyLoading) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}
if (payments === undefined) {
// 非在途且无缓存 = 上次请求已失败(见 page.tsx loadPayableHistory)
if (historyError) {
return <p className='mt-1.5 text-[11px] text-d-danger-ink'>{historyError}</p>
}
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}

historyError={payableHistoryErrors[p.id]}
historyLoading={payableHistoryLoading.has(p.id)}
historyOpen={expandedPayableIds.has(p.id)}
onToggleHistory={() => onTogglePayableHistory(p.id)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

performance · low
每行以内联箭头函数包装 onTogglePayableHistory,且 PayableRow 未做 memo:页面任一状态变化(含历史缓存、加载态更新)都会为所有固定支出行重建回调并触发整列表重渲染。当前数据规模影响有限,属可选优化:可用 React.memo 包裹 PayableRow 并稳定回调引用后再启用。

Suggestion:

Suggested change
onToggleHistory={() => onTogglePayableHistory(p.id)}
onToggleHistory={() => onTogglePayableHistory(p.id)}
{/* 可选优化:PayableRow 以 React.memo 包裹并稳定回调引用,避免整列表重渲染 */}

Comment thread ios/WorldCredit/AppState.swift Outdated
Comment on lines +788 to +792
// 历史重取与列表刷新互不依赖,并发执行减少一次往返等待
async let history: Void = expandedPayableIds.contains(item.id)
? loadPayableHistory(item.id) : ()
async let refreshed: Void = refreshPayables()
_ = await (history, refreshed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
历史重取与 refreshPayables 并行存在完成顺序竞争:若 loadPayableHistory 先返回并写入记录,refreshPayables 随后执行的 payablePayments = [:] 与 payableHistoryStale = expandedPayableIds 会抹掉刚取到的历史并把该行重新标 stale,UI stale 分支的 .task 又自动重拉一次——冗余网络请求加上「历史出现→消失→加载中→再出现」的闪烁。刷新成功路径本就会通过 stale 标记让已展开行自动重取,这里的主动预取与它冲突。建议改为串行:先完成列表刷新,再按需重取历史(或直接删除主动预取,完全依赖 stale 的 .task 自动重取)。

Suggestion:

Suggested change
// 历史重取与列表刷新互不依赖,并发执行减少一次往返等待
async let history: Void = expandedPayableIds.contains(item.id)
? loadPayableHistory(item.id) : ()
async let refreshed: Void = refreshPayables()
_ = await (history, refreshed)
// 先刷新列表:refreshPayables 会清空历史缓存并把已展开行标为 stale,
// 由视图的 .task 自动重取,避免历史先写入又被刷新清空的顺序竞争
await refreshPayables()
if expandedPayableIds.contains(item.id) {
await loadPayableHistory(item.id)
}

Comment on lines +848 to +853
} catch {
guard payableHistoryRevision[payableId] == revision else { return }
// 保持「未加载」以便下次展开重试,并记录错误供 UI 展示
payablePayments[payableId] = nil
payableHistoryErrors.insert(payableId)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
catch 分支不清除 payableHistoryStale,与 BillsView payableHistorySection 的分支顺序(stale 判定先于 failed)组合成一个状态机死锁:刷新后行保持展开(stale 置位)→ stale 分支的 .task 自动重试失败 → errors 置位但 stale 仍在 → UI 永远命中 stale 分支的「加载中…」文本(不可点击),「加载失败,点此重试」按钮不可达,且 .task(id: payable.id) 因 id 不变不会重启,用户只能收起再展开恢复。这直接违背 BillsView 中「失败态必须优先于『加载中』判定」的注释意图。另外该 catch 也未区分 CancellationError:stale 分支的 .task 在行滚出视口时被取消,取消会被误记为加载失败污染 errors 集合(虽能靠 stale 自愈重拉)。建议真实失败时清除 stale 使 failed 分支可达,并将取消与其他错误分离。

Suggestion:

Suggested change
} catch {
guard payableHistoryRevision[payableId] == revision else { return }
// 保持「未加载」以便下次展开重试,并记录错误供 UI 展示
payablePayments[payableId] = nil
payableHistoryErrors.insert(payableId)
}
} catch is CancellationError {
// 任务被取消(如 stale 行滚出视口中断自动重试):保持 stale 待重取语义,不计为失败
return
} catch {
guard payableHistoryRevision[payableId] == revision else { return }
// 保持「未加载」以便下次展开重试,并记录错误供 UI 展示
payablePayments[payableId] = nil
payableHistoryErrors.insert(payableId)
// 真实失败时清除 stale,否则 UI 的 stale 分支先于失败分支命中,
// 行将停留在没有重试入口的「加载中…」
payableHistoryStale.remove(payableId)
}

Comment on lines +858 to +861
payablePayments[item.id] = nil
expandedPayableIds.remove(item.id)
payableHistoryErrors.remove(item.id)
payableHistoryRevision[item.id] = nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
deletePayable 清理了 payablePayments、expandedPayableIds、payableHistoryErrors、payableHistoryRevision 四份状态,唯独遗漏 payableHistoryStale。若该行此前在 refreshPayables 后被标记 stale,删除后 stale 集合残留已删除的 id;refreshPayables 成功时会用 expandedPayableIds 整体覆盖而自愈,但刷新失败/跳过时残留仍在——用户重新展开该行会触发 stale 自动重试,向服务端请求一笔已删除固定支出的历史(返回空列表或错误),产生多余请求与「加载中」闪现。建议与其他清理对齐补上 stale 移除。

Suggestion:

Suggested change
payablePayments[item.id] = nil
expandedPayableIds.remove(item.id)
payableHistoryErrors.remove(item.id)
payableHistoryRevision[item.id] = nil
payablePayments[item.id] = nil
expandedPayableIds.remove(item.id)
payableHistoryErrors.remove(item.id)
payableHistoryRevision[item.id] = nil
payableHistoryStale.remove(item.id)

Comment on lines +1023 to +1025
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= 60 { return "最近 60 笔还款" }
return "历史还款 \(records.count) 笔"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
硬编码 60 与服务端 lib/api/payables.shared.ts 的 PAYABLE_HISTORY_LIMIT = 60(本次已核对一致)形成跨语言契约耦合:iOS 侧无法引用该 TS 常量,服务端将来调整上限后此处的「最近 N 笔」文案会静默失真(超过新上限仍显示「历史还款 N 笔」),无编译期保护也无测试锁定。建议至少将 60 提取为命名常量(如 payableHistoryLimit)并在注释中锚定来源文件与常量名,或在 iOS 测试 bundle 中加 fixture 断言与服务端上限对齐。

Suggestion:

Suggested change
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= 60 { return "最近 60 笔还款" }
return "历史还款 \(records.count) 笔"
guard let records, !records.isEmpty else { return "历史还款" }
// 与服务端 lib/api/payables.shared.ts PAYABLE_HISTORY_LIMIT 对齐,调整时需同步
let payableHistoryLimit = 60
if records.count >= payableHistoryLimit { return "最近 \(payableHistoryLimit) 笔还款" }
return "历史还款 \(records.count) 笔"

- 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
Comment on lines +191 to +193
setPayablePayments({})
setPayableHistoryErrors({})
expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
loadData 的缓存失效会被 loadPayableHistory 的在途去重绕过:清空 payablePayments 后,若某展开行的请求是在本次刷新之前发起且仍在途,去重逻辑会复用旧 Promise,其成功回调会把刷新前取到的旧记录写回刚清空的缓存。该旧记录若早于外部变更(如 iOS 端/其他设备登记的还款——本次更新恰好新增了 iOS 端 fetchPayments),展开行会一直展示过期历史:再次展开因缓存已存在(handleTogglePayableHistory 中 !payablePayments[payableId] 不成立)不会重拉,直到下一次无在途请求的 loadData 才自愈。handlePayPayable 已针对同一竞态做了防护(先 await 在途请求再清缓存,注释明确「否则它的成功回调会把不含新还款的记录写回」),loadData 缺少等价处理。建议清缓存前先排干在途请求(它们会在 finally 中自行从 map 删除),或引入刷新代数(epoch)令牌丢弃过期写回。

Suggestion:

Suggested change
setPayablePayments({})
setPayableHistoryErrors({})
expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) })
// 全量刷新:先等在途历史请求落定(否则去重会复用旧请求,其成功回调
// 会把刷新前取到的旧记录写回刚清空的缓存),再清空并重拉
await Promise.allSettled([...payableHistoryInFlight.current.values()])
setPayablePayments({})
setPayableHistoryErrors({})
expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) })

Comment on lines +655 to +657
payablePayments = [:]
payableHistoryErrors = []
payableHistoryStale = expandedPayableIds

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
payPayable 用 async let 并发执行历史重取与 refreshPayables,但刷新成功路径在此处整表清空 payablePayments 并重置 payableHistoryStale,且不递增 payableHistoryRevision 作废在途请求。当历史请求先于列表刷新返回(单条 LIMIT 查询通常更快)时,刚写入的 records 会被清空、该行重新标记 stale,BillsView stale 分支的 .task 随即自动重取——同一次还款触发两次历史请求并伴随「加载中…」闪烁。版本号防护目前只覆盖还款路径,未覆盖刷新路径。

Suggestion:

Suggested change
payablePayments = [:]
payableHistoryErrors = []
payableHistoryStale = expandedPayableIds
payablePayments = [:]
payableHistoryErrors = []
// 递增在途历史请求版本号:payPayable 会并发重取历史,若不作废,
// 历史先写回后被本次整表清空并重新置 stale,触发 .task 二次重取
for id in expandedPayableIds { payableHistoryRevision[id, default: 0] += 1 }
payableHistoryStale = expandedPayableIds

Comment on lines +848 to +855
} catch {
guard payableHistoryRevision[payableId] == revision else { return }
// 保持「未加载」以便下次展开重试,并记录错误供 UI 展示;
// 同时清 stale,否则 stale 分支会反复自动重试形成死循环
payablePayments[payableId] = nil
payableHistoryErrors.insert(payableId)
payableHistoryStale.remove(payableId)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
catch 未区分任务取消:BillsView stale 分支的 .task(id:) 在用户收起行、滚动离屏或离开页面时会被 SwiftUI 取消,fetchPayments 经 URLSession 抛出 CancellationError 或 URLError.cancelled,此处会把取消误标为真实失败(插入 payableHistoryErrors),用户回到该行看到「加载失败,点此重试」。本文件已有区分取消的惯例(refreshPayables 中 catch is CancellationError 与 URLError.code == .cancelled),建议对齐:取消时保持「未加载」状态、不记错误,由下次展开/复现 stale 分支静默重试。

Suggestion:

Suggested change
} catch {
guard payableHistoryRevision[payableId] == revision else { return }
// 保持「未加载」以便下次展开重试,并记录错误供 UI 展示;
// 同时清 stale,否则 stale 分支会反复自动重试形成死循环
payablePayments[payableId] = nil
payableHistoryErrors.insert(payableId)
payableHistoryStale.remove(payableId)
}
} catch {
guard payableHistoryRevision[payableId] == revision else { return }
// 收起行/离页导致的取消不是故障:保持「未加载」,下次展开静默重试
if error is CancellationError || (error as? URLError)?.code == .cancelled {
return
}
// 保持「未加载」以便下次展开重试,并记录错误供 UI 展示;
// 同时清 stale,否则 stale 分支会反复自动重试形成死循环
payablePayments[payableId] = nil
payableHistoryErrors.insert(payableId)
payableHistoryStale.remove(payableId)
}

Comment on lines +1023 to +1025
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= 60 { return "最近 60 笔还款" }
return "历史还款 \(records.count) 笔"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
阈值 60 与服务端 PAYABLE_HISTORY_LIMIT = 60(lib/api/payables.shared.ts)双写:Web 端 PayableList 通过导入共享常量判断截断态,iOS 端为硬编码魔法数字。服务端上调上限后,实际已截断的列表会仍显示「历史还款 N 笔」而非「最近 N 笔」,且 60 在函数内出现两次更易漂移。建议至少收敛为命名常量并保留锚点注释;更彻底的做法是让服务端在响应中携带 limit。

Suggestion:

Suggested change
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= 60 { return "最近 60 笔还款" }
return "历史还款 \(records.count) 笔"
/// 与服务端 PAYABLE_HISTORY_LIMIT(lib/api/payables.shared.ts)对齐:
/// 达到上限时改称「最近 N 笔」;调整服务端上限时需同步修改此处。
private static let payableHistoryLimit = 60
private func payableHistoryLabel(_ records: [PayablePaymentRecord]?) -> String {
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= Self.payableHistoryLimit {
return "最近 \(Self.payableHistoryLimit) 笔还款"
}
return "历史还款 \(records.count) 笔"
}

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1105 to +1109
} else {
Text("加载中…")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
末尾 else { Text("加载中…") } 为不可达分支:records 是 Optional,records == nil 与 if let records 已穷尽全部取值,该分支永远不会执行,且与 nil 分支文案相同,后续条件调整时容易掩盖逻辑错误。建议删除,或将前两个分支合并为单一的 if let records {…} else {…} 结构。

Suggestion:

Suggested change
} else {
Text("加载中…")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
}
} else if let records {
if records.isEmpty {
Text("还没有历史还款记录")
.font(.caption2)
.foregroundStyle(WCColors.textSecondary)
} else {
VStack(spacing: 6) {
// …记录行…
}
}
}

…cellation

- 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
Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +170 to +172
// 只清理自己这条:若期间已被 loadData 清空并重新发起,不能误删新任务
// 用 token 而非 task 引用比对(task 在 IIFE 内部尚未赋值)
if (payableHistoryInFlight.current.get(payableId) === current) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

documentation · low
注释提及的「token」「task」变量在代码中并不存在,实际是用发起时捕获的 Promise 引用 current 做比对,属重构残留说明,会误导后续维护者去寻找不存在的机制。建议改写为描述当前实现。另外此处与 handlePayPayable 中的「等在途请求落定 + 清缓存」逻辑存在重复,可考虑提取公共辅助函数。

Suggestion:

Suggested change
// 只清理自己这条:若期间已被 loadData 清空并重新发起,不能误删新任务
// 用 token 而非 task 引用比对(task 在 IIFE 内部尚未赋值)
if (payableHistoryInFlight.current.get(payableId) === current) {
// 只清理自己这条:用发起时捕获的 Promise 引用比对,
// 若期间已被 loadData 清空并重新发起(Map 中已是新 Promise),不会误删新任务
if (payableHistoryInFlight.current.get(payableId) === current) {

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +196 to +201
// 全量刷新:历史缓存可能过期。先丢弃在途请求(否则其成功回调会把刷新前的旧数据写回),
// 再清空缓存并对仍展开的行重拉,避免停在「加载中」
payableHistoryInFlight.current.clear()
setPayablePayments({})
setPayableHistoryErrors({})
expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
竞态防护不完整,注释宣称的保证并未实现:payableHistoryInFlight.current.clear() 只是从 Map 中移除引用,无法阻止已被丢弃的在途请求在成功回调里无条件执行 setPayablePayments(prev => ({ ...prev, [payableId]: records })) 把刷新前的旧数据写回缓存(若旧响应晚于新响应落定,过期数据将覆盖新数据)。同理,旧请求 finally 中 setPayableHistoryLoading 的无条件 delete 也会误删 loadData 刚重发的新请求的加载态。建议引入代次 token(如 historyEpochRef 计数器):loadData 刷新时递增代次,loadPayableHistory 在发起时捕获代次,成功回调写缓存前与 finally 清 loading 前均校验代次是否仍为当前值,过期请求直接丢弃。

Suggestion:

Suggested change
// 全量刷新:历史缓存可能过期。先丢弃在途请求(否则其成功回调会把刷新前的旧数据写回),
// 再清空缓存并对仍展开的行重拉,避免停在「加载中」
payableHistoryInFlight.current.clear()
setPayablePayments({})
setPayableHistoryErrors({})
expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) })
// 全量刷新:历史缓存可能过期。递增代次使旧在途请求的结果作废(仅 clear Map
// 拦不住旧请求成功回调里的无条件写回),再清空缓存并对仍展开的行重拉
historyEpochRef.current += 1
payableHistoryInFlight.current.clear()
setPayablePayments({})
setPayableHistoryErrors({})
expandedPayableIdsRef.current.forEach(id => { void loadPayableHistory(id) })

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +485 to +488
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running
setPayablePayments(prev => omitRecordKey(prev, payable.id))
// 等待期间用户可能收起/展开,重取前重新读取展开状态

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
注释写明「再清缓存并重取」「重取前重新读取展开状态」,但代码只执行了 omitRecordKey 清缓存,没有任何重取调用,也没有读取展开状态。后果:若该笔固定支出的历史区正处于展开态,清缓存后 payments 变为 undefined、无在途请求、无错误,展开区将停留在「加载中…」假象(配合 PayableList 中 undefined 分支的加载中文案),直到用户手动收起再展开才恢复。建议清缓存后通过 expandedPayableIdsRef.current(ref 而非 state 快照)判断是否仍展开,是则调用 loadPayableHistory(payable.id) 重取。

Suggestion:

Suggested change
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running
setPayablePayments(prev => omitRecordKey(prev, payable.id))
// 等待期间用户可能收起/展开,重取前重新读取展开状态
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running
setPayablePayments(prev => omitRecordKey(prev, payable.id))
// 清缓存后立即重取:若该行仍展开,避免 payments=undefined 且无在途请求而停在「加载中…」
if (expandedPayableIdsRef.current.has(payable.id)) {
void loadPayableHistory(payable.id)
}

Comment on lines +54 to +56
if (payments === undefined) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
payments === undefined 的语义是「尚未加载」,这里却渲染「加载中…」,把两种状态混为一谈。当 historyLoading 为 false 且缓存被清空(例如付款后只清缓存未重取)时,该分支会成为没有任何在途请求支撑的永久假加载态,误导用户。正常交互路径(展开即触发加载)不会走到这里,落到此分支的都是异常残留,建议渲染为空态或不渲染,而不是伪装成加载中。

Suggestion:

Suggested change
if (payments === undefined) {
return <p className='mt-1.5 text-[11px] text-d-muted'>加载中…</p>
}
// 未加载且无在途请求:正常展开路径必然伴随 loading,落到此处多为缓存被清后未重取,
// 不应伪装成「加载中…」误导用户
if (payments === undefined) {
return null
}

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
/// 与服务端 PAYABLE_HISTORY_LIMIT 对齐:达到上限时改称「最近 N 笔」。
private func payableHistoryLabel(_ records: [PayablePaymentRecord]?) -> String {
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= 60 { return "最近 60 笔还款" }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
60 是跨栈复制的魔数,与服务端 lib/api/payables.shared.ts 的 PAYABLE_HISTORY_LIMIT = 60 构成隐式契约。若服务端调整上限,iOS 会在 61~N 笔时静默显示错误的文案(如「历史还款 61 笔」而非「最近 N 笔」),且无任何编译期或运行期提示。建议至少将 60 提取为本文件(或 WorldCreditCore)内的具名常量并在注释中标注来源与同步责任;更稳妥的做法是让服务端在响应中附带截断标记,由数据驱动文案。

Comment thread ios/WorldCredit/Views/BillsView.swift Outdated
Comment on lines +1069 to +1071
.task(id: payable.id) {
await appState.retryPayableHistory(payable.id)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
stale 自动重取依赖 .task(id: payable.id),但该 id 在行已处于 stale 分支时不会变化,任务不会重新触发。存在可达的卡死路径:自动重取请求在途时,第二次 refreshPayables(下拉刷新 / payPayable 里并发的 refreshPayables / 后台 sync)落地 → refreshPayables 递增 revision 作废该在途响应并重新写入 payableHistoryStale → loadPayableHistory 的 guard payableHistoryRevision[payableId] == revision 判定失败后静默 return,stale 仍为 true、分支内容未变 → .task(id:) 不重启,该行永久显示「加载中…」,直到用户手动收起再展开。建议:由 AppState 维护一个仅在 stale 被(重新)标记时递增的 per-id epoch(refreshPayables 写 stale 时 +1),.task(id:) 以该 epoch 为 key,保证每次重新标记 stale 都会重启重取。注意不能用 payableHistoryRevision 作 key——loadPayableHistory 自身会递增它,会造成自动重试死循环。

Suggestion:

Suggested change
.task(id: payable.id) {
await appState.retryPayableHistory(payable.id)
}
+ Text("加载中…")
+ .font(.caption2)
+ .foregroundStyle(WCColors.textSecondary)
+ .task(id: appState.payableHistoryStaleEpoch(payable.id)) {
+ await appState.retryPayableHistory(payable.id)
+ }

…ad paths

- 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
Comment on lines +76 to +82
/** 不可变地从 Record 中删除一个 key(无该 key 时返回原对象)。 */
function omitRecordKey<T>(record: Record<string, T>, key: string): Record<string, T> {
if (!(key in record)) return record
const next = { ...record }
delete next[key]
return next
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
key in record 会沿原型链查找(如 'toString'、'constructor' 始终返回 true),与该工具函数「判断自有 key」的语义不符:当传入的 key 恰好命中 Object.prototype 上的属性名时,会走删除分支并返回一个新对象而非原对象。当前调用方传入的都是服务端生成的 UUID,实际不可触达,故仅为低风险加固;但这是模块级通用工具函数,建议改用 Object.hasOwn(record, key) 以匹配自身属性的语义。

Suggestion:

Suggested change
/** 不可变地从 Record 中删除一个 key(无该 key 时返回原对象)。 */
function omitRecordKey<T>(record: Record<string, T>, key: string): Record<string, T> {
if (!(key in record)) return record
const next = { ...record }
delete next[key]
return next
}
/** 不可变地从 Record 中删除一个 key(无该 key 时返回原对象)。 */
function omitRecordKey<T>(record: Record<string, T>, key: string): Record<string, T> {
if (!Object.hasOwn(record, key)) return record
const next = { ...record }
delete next[key]
return next
}

Comment on lines +176 to +186
} finally {
// 只清理自己这条:被新任务顶替时不能误删
if (payableHistoryInFlight.current.get(payableId) === current) {
payableHistoryInFlight.current.delete(payableId)
}
setPayableHistoryLoading(prev => {
const next = new Set(prev)
next.delete(payableId)
return next
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
loading 清理缺少与上方在途 Map 相同的守卫,存在竞态:loadData 会递增代次、clear() 在途 Map 并为展开行立即重发新请求;此时旧请求落定,其 finally 虽因 map.get(id) !== current 跳过 Map 删除,却仍无条件把同一 payableId 从 payableHistoryLoading 中删除,导致新请求仍在途时加载态被提前移除,展开区会短暂显示「展开以加载历史」而非「加载中…」。建议让 loading 清理与 Map 删除共用同一判定,只有自己仍是该 payableId 的在途请求时才清理两种状态。

Suggestion:

Suggested change
} finally {
// 只清理自己这条:被新任务顶替时不能误删
if (payableHistoryInFlight.current.get(payableId) === current) {
payableHistoryInFlight.current.delete(payableId)
}
setPayableHistoryLoading(prev => {
const next = new Set(prev)
next.delete(payableId)
return next
})
}
} finally {
// 只清理自己这条:loading 与在途 Map 用同一判定,被新任务顶替时不误删新请求的加载态
if (payableHistoryInFlight.current.get(payableId) === current) {
payableHistoryInFlight.current.delete(payableId)
setPayableHistoryLoading(prev => {
const next = new Set(prev)
next.delete(payableId)
return next
})
}
}

Comment thread app/(mobile)/bills/page.tsx Outdated
Comment on lines +489 to +500
// 新还款落库:先等在途旧请求落定(否则它的成功回调会把不含新还款的记录写回),
// 再清缓存并重取
// 递增代次:作废还款前发起的请求;随后清缓存
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)
}
// 等待期间用户可能收起/展开,重取前重新读取展开状态

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
此处的显式重取是冗余的:函数末尾的 await loadData() 会再次递增代次、清空 payablePayments 并对仍展开的行统一重拉(见 loadData 内 expandedPayableIdsRef.current.forEach 分支),刚取回的结果随即被作废清掉,白费一次 RPC 且产生「加载→数据→再加载」闪烁,也是 loading 竞态的触发路径之一。同时该段注释有三处问题:开头两段注释语义重复;「重取前重新读取展开状态」描述的是 if 块的行为却置于其后,易误导维护者。建议删除显式重取、合并注释,统一交给 loadData 收尾。

Suggestion:

Suggested change
// 新还款落库:先等在途旧请求落定(否则它的成功回调会把不含新还款的记录写回),
// 再清缓存并重取
// 递增代次:作废还款前发起的请求;随后清缓存
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)
}
// 等待期间用户可能收起/展开,重取前重新读取展开状态
// 新还款落库:递增代次作废还款前的在途请求并等待其落定,
// 避免旧成功回调把不含新还款的记录写回缓存;随后清缓存
payableHistoryGeneration.current += 1
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running
setPayablePayments(prev => omitRecordKey(prev, payable.id))
// 历史记录无需在此重取:下方 loadData 会递增代次、清缓存并对仍展开的行统一重拉

Comment on lines +69 to +72
<span className='min-w-0 flex-1 truncate text-[11px] text-d-text'>
{record.paid_at.slice(5)}
{record.note ? ' · ' + record.note : ''}
</span>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
record.paid_at.slice(5) 隐式依赖后端返回 'YYYY-MM-DD…' 的 ISO 字符串布局才能截出 'MM-DD',格式一旦变化会静默渲染出错误日期。项目内既有惯例是 date-fns 格式化(如 BillsView.tsx 中下期还款日 format(new Date(x), 'MM-dd')),建议保持一致以获得语义化且抗格式变化的写法。另:historyLabel 以「返回条数 >= PAYABLE_HISTORY_LIMIT」推断被截断的文案已与服务端查询核对(ORDER BY period DESC, created_at DESC LIMIT PAYABLE_HISTORY_LIMIT),推断成立,无需调整。

Suggestion:

Suggested change
<span className='min-w-0 flex-1 truncate text-[11px] text-d-text'>
{record.paid_at.slice(5)}
{record.note ? ' · ' + record.note : ''}
</span>
<span className='min-w-0 flex-1 truncate text-[11px] text-d-text'>
{format(new Date(record.paid_at), 'MM-dd')}
{record.note ? ' · ' + record.note : ''}
</span>

Comment thread ios/WorldCredit/AppState.swift Outdated
Comment on lines +791 to +795
// 历史重取与列表刷新互不依赖,并发执行减少一次往返等待
async let history: Void = expandedPayableIds.contains(item.id)
? loadPayableHistory(item.id) : ()
async let refreshed: Void = refreshPayables()
_ = await (history, refreshed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
并发执行 loadPayableHistory 与 refreshPayables 后,历史预取的结果必然被作废:refreshPayables 成功后会无条件对 expandedPayableIds 中的所有 id 递增 payableHistoryRevision、清空 payablePayments 并将全部已展开项置为 stale。无论哪个先完成——历史先返回则被 refresh 整体清掉;refresh 先返回则版本号 guard 直接丢弃响应——最终该行都停在 stale 态,用户还款成功后必须手动点「点击加载最新历史」才能看到新记录,与上方注释「已展开则立即重取,避免显示空的旧缓存」的意图相反,且每次还款白白多消耗一次 RPC 往返。建议改为先 await refreshPayables()(由其置 stale),再对已展开项顺序调用 loadPayableHistory(item.id) 完成自动重取并清除 stale。

Suggestion:

Suggested change
// 历史重取与列表刷新互不依赖,并发执行减少一次往返等待
async let history: Void = expandedPayableIds.contains(item.id)
? loadPayableHistory(item.id) : ()
async let refreshed: Void = refreshPayables()
_ = await (history, refreshed)
// 先刷新列表(其内部会把已展开项标记为待重取并作废旧缓存),
// 随后对已展开项自动重取历史,保证还款后无需手动点击即可看到最新记录
await refreshPayables()
if expandedPayableIds.contains(item.id) {
await loadPayableHistory(item.id)
}

Comment on lines +851 to +854
} catch is CancellationError {
// 视图取消(收起/离屏):不是失败,保持待重取状态
guard payableHistoryRevision[payableId] == revision else { return }
payablePayments[payableId] = nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
取消分支的注释声称「保持待重取状态」,但实现只把 payablePayments 置 nil,没有 payableHistoryStale.insert(payableId)。一旦取消真实发生(当前调用方虽为按钮内非结构化 Task 暂难触达,但 payPayable 的 async let 子任务在父任务被取消时会走到这里;未来若按 BillsView 注释设想改回 .task(id:) 也会触达),该行将处于 expanded + 非 failed + 非 stale + records == nil 的组合态:UI 永远显示「加载中…」而实际已无在途请求,没有失败/stale 按钮可点,只能靠收起再展开或一次无关的 refreshPayables 成功来自愈。下一个 URLError.cancelled 分支存在同样问题。建议在两个取消分支中改为 payableHistoryStale.insert(payableId)(与注释「保持待重取状态」一致),让 UI 落入 stale 分支展示「点击加载最新历史」的重试入口。

Suggestion:

Suggested change
} catch is CancellationError {
// 视图取消(收起/离屏):不是失败,保持待重取状态
guard payableHistoryRevision[payableId] == revision else { return }
payablePayments[payableId] = nil
} catch is CancellationError {
// 视图取消(收起/离屏):不是失败,保持待重取状态
guard payableHistoryRevision[payableId] == revision else { return }
payablePayments[payableId] = nil
payableHistoryStale.insert(payableId)

Comment on lines +1023 to +1025
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= 60 { return "最近 60 笔还款" }
return "历史还款 \(records.count) 笔"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
裸字面量 60 与服务端 lib/api/payables.shared.ts 的 PAYABLE_HISTORY_LIMIT(getPayablePayments 的 LIMIT)构成跨语言隐式契约,当前取值一致,但两端无任何编译期或运行期关联,仅靠注释维系;服务端调整上限后 iOS 会在未截断时误显示「最近 60 笔还款」或漏改文案。建议至少在本文件收敛为命名常量以便统一修改与检索,更彻底的做法是让 getPayablePayments 在响应中带上 limit 或 truncated 标记,由数据驱动文案而非双端各自硬编码。

Suggestion:

Suggested change
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= 60 { return "最近 60 笔还款" }
return "历史还款 \(records.count) 笔"
/// 需与服务端 PAYABLE_HISTORY_LIMIT(lib/api/payables.shared.ts)同步修改。
private static let payableHistoryServerLimit = 60
private func payableHistoryLabel(_ records: [PayablePaymentRecord]?) -> String {
guard let records, !records.isEmpty else { return "历史还款" }
if records.count >= Self.payableHistoryServerLimit {
return "最近 \(Self.payableHistoryServerLimit) 笔还款"
}
return "历史还款 \(records.count) 笔"
}

- 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
Comment on lines +179 to +182
if (
payableHistoryInFlight.current.get(payableId) === current &&
payableHistoryGeneration.current === generation
) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
清理条件中的「代次一致」判断会让已落定请求的在途条目永久残留。失败链路:handlePayPayable 先递增代次再 await running,旧请求落定时因代次不匹配跳过本 finally(Map 条目与 loading 标记残留);正常由紧随的 loadData 的 clear() 兜底,但若那次 loadData 失败(Promise.all 抛错走 catch,既不递增代次也不清 Map),此后收起再展开该行时 loadPayableHistory 开头的去重会直接返回这个已落定的 Promise——不发请求、不设错误,历史区永久停在「加载中…」且看不到新登记的还款,只能等下次成功的全量刷新才能恢复。建议清理条件去掉代次约束,只保留「Map 中仍是自己」:被新请求顶替时 get(payableId) !== current 自然跳过,不会误删新请求的 loading 态。

Suggestion:

Suggested change
if (
payableHistoryInFlight.current.get(payableId) === current &&
payableHistoryGeneration.current === generation
) {
// 只要 Map 里仍是自己就清理;被新请求顶替时 get() !== current,自然跳过,
// 不会误清新请求的 loading 态。不再要求代次一致:还款路径递增代次后旧请求
// 落定会残留条目与 loading 态,若随后的 loadData 失败(catch 不作废 Map),
// 去重会一直返回已落定的 Promise,该行历史区将永久卡在「加载中…」。
if (payableHistoryInFlight.current.get(payableId) === current) {
payableHistoryInFlight.current.delete(payableId)
setPayableHistoryLoading(prev => {
const next = new Set(prev)
next.delete(payableId)
return next
})
}

Comment on lines +496 to +499
payableHistoryGeneration.current += 1
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running
setPayablePayments(prev => omitRecordKey(prev, payable.id))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
这里对「紧随其后的 loadData 一定执行且成功」存在隐式依赖:本行缓存清理后,在途条目的作废完全依赖 loadData 内的 clear() + 重拉(loadData 失败路径不会清 Map)。若 loadData 失败,本行的去重 Map 将残留已落定的 Promise,重新展开只会立即返回旧结果,无法重取。当前代码行为正确,但正确性建立在跨函数的执行顺序契约上;建议在 await 落定后显式删除本行条目并清掉该行 loading,消除这条隐性契约(与 finally 清理条件的评审意见互为补充)。

Suggestion:

Suggested change
payableHistoryGeneration.current += 1
const running = payableHistoryInFlight.current.get(payable.id)
if (running) await running
setPayablePayments(prev => omitRecordKey(prev, payable.id))
payableHistoryGeneration.current += 1
const running = payableHistoryInFlight.current.get(payable.id)
if (running) {
await running
// 显式移除已落定条目并清掉该行 loading:不依赖随后的 loadData 必须
// 成功执行 clear(),失败时本行仍可再次展开重取
payableHistoryInFlight.current.delete(payable.id)
setPayableHistoryLoading(prev => {
const next = new Set(prev)
next.delete(payable.id)
return next
})
}
setPayablePayments(prev => omitRecordKey(prev, payable.id))

Comment on lines +55 to +58
if (payments === undefined) {
// 无在途请求却仍为 undefined:说明缓存被清空但未重取,提示可再次展开
return <p className='mt-1.5 text-[11px] text-d-muted'>展开以加载历史</p>
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

other · low
该分支只在 historyOpen === true(面板已展开)时才会渲染,但文案「展开以加载历史」引导的却是一个已生效的动作,用户会困惑;且该状态实际可达——例如登记付款成功后 handlePayPayable 先清掉该行缓存、loadData 尚在 Promise.all 阶段未重拉期间,展开的面板里就会显示这条提示。建议改为准确描述恢复动作的文案,如「收起后重新展开以加载」。

Suggestion:

Suggested change
if (payments === undefined) {
// 无在途请求却仍为 undefined:说明缓存被清空但未重取,提示可再次展开
return <p className='mt-1.5 text-[11px] text-d-muted'>展开以加载历史</p>
}
if (payments === undefined) {
// 无在途请求却仍为 undefined:说明缓存被清空但未重取,提示收起再展开触发重试
return <p className='mt-1.5 text-[11px] text-d-muted'>收起后重新展开以加载历史</p>
}

Comment on lines +70 to +73
<span className='min-w-0 flex-1 truncate text-[11px] text-d-text'>
{format(new Date(record.paid_at), 'MM-dd')}
{record.note ? ' · ' + record.note : ''}
</span>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
paid_at 在服务端以「YYYY-MM-DD」纯日期字符串落库(payables.server.ts 中 INSERT 写入 ${y}-${m}-${d})。new Date('YYYY-MM-DD') 按 ECMAScript 规范会被解析为 UTC 零点,在 UTC 负偏移时区(如美东)本地日期会退回前一天,format(..., 'MM-dd') 展示的还款日期将差一天。同文件细节行对同类纯日期值已有安全的处理约定(p.due_date.slice(5) 字符串切片,不受时区影响),此处建议保持一致;改为 record.paid_at.slice(5, 10) 对未来变成完整 ISO 时间戳也兼容。注意:改后顶部的 import { format } from 'date-fns' 将不再被使用,应一并移除。

Suggestion:

Suggested change
<span className='min-w-0 flex-1 truncate text-[11px] text-d-text'>
{format(new Date(record.paid_at), 'MM-dd')}
{record.note ? ' · ' + record.note : ''}
</span>
<span className='min-w-0 flex-1 truncate text-[11px] text-d-text'>
{record.paid_at.slice(5, 10)}
{record.note ? ' · ' + record.note : ''}
</span>

Comment on lines +655 to +658
for id in expandedPayableIds {
payableHistoryRevision[id] = (payableHistoryRevision[id] ?? 0) + 1
}
payablePayments = [:]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
刷新时的版本号作废只遍历 expandedPayableIds,但 payablePayments = [:] 清空的是全部缓存。若某行在展开发起历史请求后、刷新完成前被收起(id 已不在 expandedPayableIds),其在途响应不会被作废:请求成功返回时 revision 仍匹配,会把刷新前的旧数据写回刚清空的缓存。之后用户重新展开时因 records != nil 直接走缓存分支不再重拉,且该行无 stale 标记、无手动刷新入口,会一直显示过期历史(例如其他设备在刷新前后新登记的还款缺失),直到下一次「展开状态下刷新」才自愈。这与注释「先作废所有在途历史请求(否则其回调会把刷新前的旧数据写回)」的意图不符。建议对 payableHistoryRevision 的全部 key 递增版本号(或维护在途请求 id 集合),确保任何在途历史响应都被刷新作废。

Suggestion:

Suggested change
for id in expandedPayableIds {
payableHistoryRevision[id] = (payableHistoryRevision[id] ?? 0) + 1
}
payablePayments = [:]
// 对所有发起过历史请求的 id 递增版本号:收起后的在途请求同样要作废,
// 否则其回调会在清空缓存后把刷新前的旧数据写回
for id in payableHistoryRevision.keys {
payableHistoryRevision[id] = (payableHistoryRevision[id] ?? 0) + 1
}
payablePayments = [:]

Comment on lines +838 to +841
let revision = (payableHistoryRevision[payableId] ?? 0) + 1
payableHistoryRevision[payableId] = revision
// 重试在途:先清旧错误,UI 显示「加载中」而不是上次的失败文案
payableHistoryErrors.remove(payableId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
点击「点击加载最新历史」后,loadPayableHistory 开始时未清除 payableHistoryStale,请求在途期间 stale 仍为 true。BillsView 的判断顺序是 failed → stale → records == nil,因此加载期间 UI 仍显示可点击的「点击加载最新历史」按钮而非「加载中…」,用户可以连续重复点击,每次都会再发起一次网络请求(旧请求靠 revision 作废,无数据损坏,但产生重复请求且加载态不可见)。建议请求发出时同步移除 stale,使 UI 在加载期间正确进入加载态;失败/取消分支会按现有逻辑重新写入 error/stale,不会形成自动重试死循环。

Suggestion:

Suggested change
let revision = (payableHistoryRevision[payableId] ?? 0) + 1
payableHistoryRevision[payableId] = revision
// 重试在途:先清旧错误,UI 显示「加载中」而不是上次的失败文案
payableHistoryErrors.remove(payableId)
let revision = (payableHistoryRevision[payableId] ?? 0) + 1
payableHistoryRevision[payableId] = revision
// 重试在途:先清旧错误与 stale,UI 显示「加载中」而不是上次的失败文案或可重复点击的 stale 按钮
payableHistoryErrors.remove(payableId)
payableHistoryStale.remove(payableId)

@hubo1989
hubo1989 merged commit 3c24935 into main Nov 3, 2026
4 checks passed
@hubo1989
hubo1989 deleted the feat/payable-history branch November 4, 2026 06:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant