Skip to content

feat: unified credit-account model, card/settings redesign, and bill/payable fixes - #55

Merged
hubo1989 merged 28 commits into
mainfrom
fix/bugs
Nov 6, 2026
Merged

hubo1989 merged 28 commits into
mainfrom
fix/bugs

Conversation

@hubo1989

@hubo1989 hubo1989 commented Nov 5, 2026

Copy link
Copy Markdown
Owner

变更

六条工作流,10 个提交,109 文件 +17,878/−1,286:

  • 账单周期/逾期(A):账单列表排序改为 bill_month 倒序,修复已还完旧账单(如 202608)抢占当前期;详情页「待出账且已还款」不再显示逾期天数(存量 paid 不再被 payments 流水误翻案)
  • 信用额度/还款日(B):未获取额度显示「未获取」并支持手动输入持久化/回显(0029_credit_limit_override);还款日四类缺失原因(邮件未提供/解析失败/日期模糊/未同步)分类汇总,卡详情入口
  • 固定支出(C):支持每月/每 X 月/每年三周期 + 自定义分类(去重、持久化、iOS 同步兼容,0030_payable_cycles_and_custom_categories)
  • 卡片重构(D):卡定义/人+卡两层模型——账单信息去掉银行/卡片、关联卡片不显示持卡人/尾号、卡片名称可改(name_override)、换银行=换绑卡产品(同币种限制)、账单日合并回 billing_day、登录用户可自建持卡人、双端新增卡片向导(0031_default_bank_card_products)
  • 统一账单模型(E):credit_accounts + bills.account_id + bill_card_subtotals,保守回填(碰撞组不删不改,界面合并向导手动确认),招行/民生/上海/北京 statement_mode='merged' 落库,额度去重(0032_unified_credit_accounts);招行邮件解析器按真实样本实现(账户级总额 + 尾号列分卡小计 + 未归卡差额呈现)
  • 设置页重设计(F):明暗双主题 token、移动端 BottomSheet 三抽屉 + 4-Tab 底栏(WcIcon)、后台统一保存/维护模式确认/防覆写;设计源迁移至 design/baoyu/(baoyu-design 唯一真源),OpenPencil 目录冻结存档,verify-batch.sh 平滑升级为 baoyu 门禁,AGENTS.md 已同步

影响

  • D1 迁移 0029–0032:部署时需按序应用后再 npx vinext deploy
  • iOS:swift test 通过;xcodebuild 全量构建在开发机验证通过
  • 兼容:同步接口新增字段向后兼容,旧客户端忽略不崩;bills.card_id 保持 NOT NULL(锚点语义),零表重建
  • 数据安全:招行真实样本仅存 /tmp 开发验证,测试用同构合成 fixture,个人金额/尾号零入库(grep 零命中)

测试

  • npm run typecheck ✅ npm run lint(0 警告)✅ npm test:96 文件 / 1074 用例全过 ✅
  • iOS swift test:180 用例 / 24 套件全过 ✅
  • 设计门禁 verify-batch.sh --source-only:五项全 PASS(画板契约/Token 零漂移/热区对比度/无原生弹窗/存档保护)✅
  • 招行解析:真实样本字段提取 100% 吻合(runIf 本地验证),多尾号聚合与未归卡差额由合成 fixture 覆盖

Review 重点

  • lib/api/bills.server.ts(统一账户读取口径与去重)
  • lib/email-core/cmb.ts + email-worker 归并入库
  • migrations/d1/0032_unified_credit_accounts.sql(保守回填逻辑)
  • design/openpencil/verify-batch.sh → design/baoyu/verify-design.py 门禁切换

@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-05T01:18:30.400688Z
We couldn’t complete this review. Comment @codex review to try again.
744acce 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 5, 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: cfb8eb2f-fc8b-4200-9423-f7a125d2e511
  • 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

@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 5, 2026 •

Copy link
Copy Markdown

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

  • ✅ Successfully posted inline: 21 comment(s)

⚠️ 5 warning(s) occurred during review.


⚠️ Warnings:

  • app/(mobile)/bills/[id]/page.tsx,app/(mobile)/bills/page.tsx,components/mobile/BottomNav.tsx,components/mobile/PayableForm.tsx,components/mobile/PayableList.tsx,components/mobile/QuickActionSheet.tsx,components/obsidian/BillsView.tsx,lib/bills-view-model.ts (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task
  • app/(mobile)/bills/[id]/page.tsx (token_budget_reached): stopped group "app/(mobile)/bills/[id]/page.tsx,app/(mobile)/bills/page.tsx,components/mobile/BottomNav.tsx,components/mobile/PayableForm.tsx,components/mobile/PayableList.tsx,components/mobile/QuickActionSheet.tsx,components/obsidian/BillsView.tsx,lib/bills-view-model.ts" mid-review: used 2093717 tokens exceeds budget 2000000
  • db/schema.sql (token_budget_reached): stopped dispatch: used 2093717 tokens + group estimate 346520 = projected 2440237 exceeds budget 2000000
  • app/(mobile)/cards/[id]/page.tsx,app/(mobile)/cards/page.tsx,components/mobile/AccountMergeWizardModal.tsx,components/mobile/CardAccountModal.tsx,components/mobile/CardCreateModal.tsx,components/mobile/CardDefinitionModal.tsx,components/mobile/CardForm.tsx,components/mobile/CreditCardItem.tsx,components/mobile/CreditCardVisual.tsx,components/mobile/card-form-shared.ts (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task
  • app/(mobile)/settings/page.tsx,app/admin/settings/page.tsx,app/globals.css,app/layout.tsx,components/settings/DisplayPreferencesCard.tsx,components/settings/ReminderPreferencesCard.tsx,components/settings/shared.ts,lib/api/admin.server.ts,lib/hooks/useTheme.ts,lib/hooks/useUserPreferences.ts (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task

Comment thread app/(mobile)/bills/[id]/page.tsx Outdated
Comment on lines +37 to +46
} else if (status === 'overdue') {
// 待出账保护:未到出账日绝无逾期
const isUnissued = Boolean(
(bill.statement_date && new Date(bill.statement_date).getTime() > Date.now()) ||
(bill.statement_end && new Date(bill.statement_end).getTime() > Date.now())
)
if (isUnissued) {
status = 'unpaid'
}
}

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
此处基于 epoch 毫秒比较 date-only 字符串(如 '2026-11-05' 按 UTC 午夜解析)存在时区缺陷:东八区出账日当天 00:00–08:00 会被误判为「未出账」,进而把真实逾期降级为 unpaid、隐藏逾期提示。这正是 lib/utils.ts diffInCalendarDays 注释中点名禁止的反模式(应先归一到本地零点再比较日历日)。此外,服务端 bills.server.ts 的 computeStatus 已实现同样的「paid 短路 + 待出账保护」且口径为本地零点 daysUntil,这里在 computePaymentDrivenStatus 之上再内联一套保护,形成了服务端落库/仪表盘/详情页三套状态口径,列表与详情可能出现不一致。建议把该保护逻辑抽取到 lib/utils 共享函数(内部用 diffInCalendarDays 做日历日比较),服务端与详情页共用一份。

Suggestion:

Suggested change
} else if (status === 'overdue') {
// 待出账保护:未到出账日绝无逾期
const isUnissued = Boolean(
(bill.statement_date && new Date(bill.statement_date).getTime() > Date.now()) ||
(bill.statement_end && new Date(bill.statement_end).getTime() > Date.now())
)
if (isUnissued) {
status = 'unpaid'
}
}
// lib/utils.ts:共享的待出账判定(与服务端 computeStatus 同口径)
export function isBillUnissued(bill: {
statement_date?: string | null
statement_end?: string | null
}): boolean {
const stmt = bill.statement_date || bill.statement_end
return Boolean(stmt && diffInCalendarDays(stmt) > 0)
}
// 页面内:
} else if (status === 'overdue' && isBillUnissued(bill)) {
status = 'unpaid'
}

Comment thread app/(mobile)/bills/[id]/page.tsx Outdated
Comment on lines +39 to +42
const isUnissued = Boolean(
(bill.statement_date && new Date(bill.statement_date).getTime() > Date.now()) ||
(bill.statement_end && new Date(bill.statement_end).getTime() > Date.now())
)

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
isUnissued 判定表达式与 computeBillProgress 内的第 39-42 行完全相同(重复实现),后续调整出账判定规则时极易只改一处,造成状态徽章与逾期提示口径不一致。建议让 computeBillProgress 一并返回 isUnissued(或抽取共享助手函数),渲染体直接复用。

Suggestion:

Suggested change
const isUnissued = Boolean(
(bill.statement_date && new Date(bill.statement_date).getTime() > Date.now()) ||
(bill.statement_end && new Date(bill.statement_end).getTime() > Date.now())
)
// computeBillProgress 返回值扩展为 { paid, remaining, status, isUnissued }
const { paid, remaining, status, isUnissued } = computeBillProgress(bill)

Comment on lines +248 to +255
<Row
label='今日刷卡免息'
value={
graceWindow > 0
? `${graceWindow} 天`
: '—'
}
/>

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
「今日刷卡免息」取的是本期「出账日 → 还款日」的固定窗口 graceWindow(与今天无关,见上方注释自述),与本页下方「免息还款期」行是同一个值,同页重复展示;而账单列表页 BillsView 同名词用的是 calculateCardGracePeriod 的今日动态口径(今天距下期还款日天数)。同一标签两页两种语义会误导用户(例:出账日已过 20 天、还款日还剩 30 天时,此处显示 50 天,列表页显示的是另一个数)。建议改用与列表页一致的今日动态免息天数,或改掉标签(如「最长免息期」)并去掉与「免息还款期」行的重复。

Suggestion:

Suggested change
<Row
label='今日刷卡免息'
value={
graceWindow > 0
? `${graceWindow} 天`
: '—'
}
/>
<Row
label='最长免息期'
value={graceWindow > 0 ? `${graceWindow} 天` : '—'}
/>

Comment thread app/(mobile)/bills/[id]/page.tsx Outdated
<Row label='出账日' value={bill.statement_date ? format(new Date(bill.statement_date), 'yyyy-MM-dd') : '—'} />
<Row label='账单周期' value={periodStart && periodEnd ? periodStart + ' – ' + periodEnd : '—'} />
<Row label='持卡人' value={holderName || '—'} />
<Row label='卡片尾号' value={last4 ? `尾号 ${last4}` : '—'} />

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
行标签已是「卡片尾号」,值又带「尾号 」前缀,页面会渲染成「卡片尾号 尾号 1234」,语义重复。建议 value 直接使用 last4。

Suggestion:

Suggested change
<Row label='卡片尾号' value={last4 ? `尾号 ${last4}` : '—'} />
<Row label='卡片尾号' value={last4 || '—'} />

Comment thread app/(mobile)/bills/[id]/page.tsx Outdated
Comment on lines +280 to +282
card && getEffectiveCreditLimit(card) != null
? `¥${Number(getEffectiveCreditLimit(card)).toLocaleString()}`
: '—'

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
违反严格相等规范(禁止 !=,应使用 !==);且同一 JSX 表达式内 getEffectiveCreditLimit(card) 被调用两次,存在冗余计算。建议在渲染前提取一次结果并判空。

Suggestion:

Suggested change
card && getEffectiveCreditLimit(card) != null
? `¥${Number(getEffectiveCreditLimit(card)).toLocaleString()}`
: '—'
// 组件体内先取值:
const creditLimit = card ? getEffectiveCreditLimit(card) : null
// JSX 中:
<Row
label='信用额度'
value={creditLimit !== null ? `¥${creditLimit.toLocaleString()}` : '—'}
/>

Comment thread components/mobile/PayableForm.tsx Outdated
Comment on lines +315 to +316
const amountLabel =
cycleType === 'yearly' ? '每年金额' : cycleType === 'every_n_months' ? '每期金额' : '每月金额'

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
违反团队「禁止嵌套三元表达式」规范:根据 cycleType 推导金额标签时三层条件串联,可读性差,且后续新增周期类型时容易漏改某一层。建议改为映射表或普通函数。

Suggestion:

Suggested change
const amountLabel =
cycleType === 'yearly' ? '每年金额' : cycleType === 'every_n_months' ? '每期金额' : '每月金额'
const AMOUNT_LABEL_BY_CYCLE: Record<PayableCycleType, string> = {
monthly: '每月金额',
every_n_months: '每期金额',
yearly: '每年金额',
}
const amountLabel = AMOUNT_LABEL_BY_CYCLE[cycleType]

Comment thread components/mobile/PayableList.tsx Outdated
const due = isMonthly ? p.due_date.slice(5) : p.due_date
if (paid) {
const next = payableNextCycleStatus(p.due_day, p.period)
const next = payableNextCycleStatus(p.due_day, p.period, undefined, 30, 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
第 4 个位置参数 30 是业务魔数(下期出账提前天数,对应注释「还款日 − 30」口径),且前置参数以 undefined 占位,调用处参数含义不直观、易错位。建议提取命名常量(如 NEXT_BILL_LEAD_DAYS)并与其在 lib/api/payables.shared.ts 中的默认值保持单一来源,或考虑改为 options 对象参数。

Suggestion:

Suggested change
const next = payableNextCycleStatus(p.due_day, p.period, undefined, 30, p)
const next = payableNextCycleStatus(p.due_day, p.period, undefined, NEXT_BILL_LEAD_DAYS, p)

const mm = String(next.date.getMonth() + 1).padStart(2, '0')
const dd = String(next.date.getDate()).padStart(2, '0')
return `本期已付清 · 下期出账日 ${mm}-${dd}`
const formattedNext = isMonthly ? `${mm}-${dd}` : `${next.date.getFullYear()}-${mm}-${dd}`

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
同一列表内日期口径不一致:月周期项展示 MM-DD(上方逾期/当日应付的 due 亦是),非月周期项展示完整 YYYY-MM-DD。若这是刻意用完整日期区分跨年周期,建议补一行注释说明意图,避免后续维护者误当作不一致而“修复”;否则建议统一格式以便扫读。

Suggestion:

Suggested change
const formattedNext = isMonthly ? `${mm}-${dd}` : `${next.date.getFullYear()}-${mm}-${dd}`
// 非月周期可能跨年,用完整 YYYY-MM-DD 消除年份歧义;月周期保持 MM-DD 简短展示
const formattedNext = isMonthly ? `${mm}-${dd}` : `${next.date.getFullYear()}-${mm}-${dd}`

Comment thread components/obsidian/BillsView.tsx Outdated
</span>
</div>
))}
{b.unallocated_amount != null && (

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
新增代码使用规范禁止的宽松不等比较 !=,应改为严格相等 !==。

Suggestion:

Suggested change
{b.unallocated_amount != null && (
{b.unallocated_amount !== null && b.unallocated_amount !== undefined && (

Comment thread lib/bills-view-model.ts
Comment on lines +19 to +25
// 实体信用账户模式优先(若所属账户为 merged 则直接判定为 multi)
const self = cards.find(
c => c.holder_id === holderId && (c.card.card_product?.bank_name || '') === bankName
)
if (self?.account?.statement_mode) {
return self.account.statement_mode === 'merged' ? 'multi' : 'single'
}

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
新增逻辑以实体账户 statement_mode 优先判定,但函数上方的 JSDoc 仍描述旧口径(「同一持卡人在同一家银行持有 >1 张卡 → multi;否则 single」),两者已矛盾:例如合并账户只含 1 张卡时新逻辑返回 multi。文档与实现不一致易误导后续维护者,建议同步更新 JSDoc,补充「实体账户模式优先、卡数统计兜底」的优先级说明。

Suggestion:

Suggested change
// 实体信用账户模式优先(若所属账户为 merged 则直接判定为 multi)
const self = cards.find(
c => c.holder_id === holderId && (c.card.card_product?.bank_name || '') === bankName
)
if (self?.account?.statement_mode) {
return self.account.statement_mode === 'merged' ? 'multi' : 'single'
}
/**
* 多卡一账户 / 单卡单账户 的展示口径:
* 1. 卡片所属实体账户的 statement_mode 优先(merged → multi,independent → single);
* 2. 无实体账户时回退到 account_mode_override;
* 3. 最后按「同一持卡人同银行 >1 张卡 → multi」兜底。
* 这是展示层推导,不改 schema;同一银行跨持卡人仍算各自独立的账户。
*/

Comment thread app/(mobile)/bills/[id]/page.tsx Outdated
Comment on lines +41 to +47
// 保护:历史存量已还款账单(数据库存 status = 'paid')或无流水但已标记 paid,保留 paid 状态
if (bill.status === 'paid' && paid === 0) {
status = 'paid'
} else if (status === 'overdue' && unissued) {
// 待出账保护:未到出账日绝无逾期
status = 'unpaid'
}

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
该分支无条件把「数据库 status='paid' 且无还款流水」的账单显示为已结清。已核实当前服务端写入路径中,无流水即标 paid 的只有 0 元账单(lib/email-core/bills.ts:453 zeroBill ? 'paid' : 'unpaid'),而 0 元账单 computePaymentDrivenStatus 本身就会返回 paid(0 >= 0 − 0.01),并不需要此覆盖;因此该分支实际只对「金额 > 0 但被标 paid 且无流水」的异常/存量数据生效——这些行的欠款会以「已结清」徽章展示,且 renderGraceRemainingNotice 因 isSettled 被抑制,逾期提醒丢失。这与本函数注释「与服务端落库、还款重算共用同一个状态函数,避免两套口径」的意图相悖,正是 computePaymentDrivenStatus 文档中明确要移除的 DB-status 短路。建议把存量保护收窄到 0 元账单,金额 > 0 时以重算结果为准。

Suggestion:

Suggested change
// 保护:历史存量已还款账单(数据库存 status = 'paid')或无流水但已标记 paid,保留 paid 状态
if (bill.status === 'paid' && paid === 0) {
status = 'paid'
} else if (status === 'overdue' && unissued) {
// 待出账保护:未到出账日绝无逾期
status = 'unpaid'
}
// 保护:0 元账单被邮件同步直接落库为 paid 且无流水(见 lib/email-core/bills.ts),保留 paid;
// 金额 > 0 的行一律以还款驱动的重算结果为准,避免异常数据被显示层永久遮蔽。
if (bill.status === 'paid' && paid === 0 && (Number(bill.bill_amount) || 0) <= 0) {
status = 'paid'
} else if (status === 'overdue' && unissued) {
// 待出账保护:未到出账日绝无逾期
status = 'unpaid'
}

Comment thread app/(mobile)/bills/[id]/page.tsx Outdated
Comment on lines +110 to +112
card_holders: rawCard.card_holder
? { id: rawCard.card_holder.id, name: rawCard.card_holder.name, user_id: '' }
: undefined,

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
服务端 getBillDetail 返回的 card.card_holder 只有 { id, name }(见 bills.server.ts getBillDetail 的 SELECT ch.id AS h_id, ch.name AS h_name),这里为凑齐 CreditCardWithProduct.card_holders 的 CardHolder 类型而硬编码 user_id: '',属于伪造字段。rawCard.holder_id 与 card_holder.id 是同一个值且就在同一对象上,直接复用可避免下游(如 CardAccountModal 等未来消费 card_holders.user_id 的代码)把空串误当成真实 user_id。

Suggestion:

Suggested change
card_holders: rawCard.card_holder
? { id: rawCard.card_holder.id, name: rawCard.card_holder.name, user_id: '' }
: undefined,
card_holders: rawCard.card_holder
? { id: rawCard.card_holder.id, name: rawCard.card_holder.name, user_id: rawCard.holder_id }
: undefined,

Comment thread app/(mobile)/bills/[id]/page.tsx Outdated
return Math.max(0, Math.round((new Date(end).getTime() - new Date(start).getTime()) / 86400000))
})()
const billPaid = status === 'paid'
const isSettled = status === 'paid' || bill.status === 'paid' || remaining <= 0

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
isSettled 无条件信任 bill.status === 'paid':当数据库标记 paid 但实际只有部分还款(0 < paid < 金额,多为错误落库/存量数据)时,状态徽章会按重算结果显示「部分还款」(partial),但本行令 isSettled 为 true,renderGraceRemainingNotice 直接返回 null,免息/逾期提醒被抑制——徽章与提醒口径互相矛盾,且用户看不到还款日警示。computeBillProgress 中已对 DB 旧值做了(应收窄的)存量保护,此处建议只依据重算后的 status 与 remaining 判定。

Suggestion:

Suggested change
const isSettled = status === 'paid' || bill.status === 'paid' || remaining <= 0
const isSettled = status === 'paid' || remaining <= 0

Comment thread app/(mobile)/settings/page.tsx Outdated
Comment on lines +132 to +136
const cycleTheme = () => {
if (theme === 'system') setTheme('dark')
else if (theme === 'dark') setTheme('light')
else setTheme('system')
}

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
主题轮换逻辑与 useTheme 已导出的 cycleTheme 重复实现且顺序漂移:hook 版本为 dark→light→system→dark,本页本地版本为 system→dark→light→system。hook 的 cycleTheme 在本页沦为死代码,两处未来易行为不一致。建议删除本地实现,改为从 hook 解构 cycleTheme(或移除 hook 中未被引用的版本),单一来源维护轮换顺序。

Suggestion:

Suggested change
const cycleTheme = () => {
if (theme === 'system') setTheme('dark')
else if (theme === 'dark') setTheme('light')
else setTheme('system')
}
// 统一使用 useTheme 导出的 cycleTheme,避免两处轮换顺序漂移
const { theme, setTheme, cycleTheme } = useTheme()

Comment thread app/(mobile)/settings/page.tsx Outdated
else setTheme('system')
}

const themeLabel = theme === 'dark' ? '🌙 暗色' : theme === 'light' ? '☀️ 亮色' : '💻 跟随系统'

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
嵌套三元表达式违反项目「禁止嵌套三元」规范(下方 gmailSummary 的 connected ? ... : last_error ? ... : ... 同样如此)。建议用映射表或 if/else 提取,提升可读性并为未来扩展主题模式留出空间。

Suggestion:

Suggested change
const themeLabel = theme === 'dark' ? '🌙 暗色' : theme === 'light' ? '☀️ 亮色' : '💻 跟随系统'
const THEME_LABELS: Record<'system' | 'dark' | 'light', string> = {
system: '💻 跟随系统',
dark: '🌙 暗色',
light: '☀️ 亮色',
}
const themeLabel = THEME_LABELS[theme]

Comment on lines +72 to +77
try {
// 真实触发 POST /api/push/test
await fetch('/api/push/test', { method: 'POST' }).catch(() => null)
} catch {
// ignore network fail, fallback to local Notification
}

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
测试推送请求结果被完全忽略:.catch(() => null) 吞掉网络错误且未检查 res.ok,接口失败时仍提示「测试通知已成功发送至系统通知栏」,测试结果与服务端推送状态不符,用户无法据此判断真实推送链路是否可用。建议保留响应检查并根据结果区分提示;'/api/push/test' 硬编码路径建议收敛到统一的 API 模块。

Comment on lines +174 to +181
<input
type='time'
aria-label='免打扰起始'
disabled={disabled}
value={config.quiet_hours_start || '22:00'}
onChange={(e) => onChange({ quiet_hours_start: e.target.value })}
className='min-h-[44px] w-full rounded-xl border border-d-border bg-d-bg px-3 text-[16px] text-d-text [color-scheme:dark] outline-none focus:border-d-accent disabled:opacity-50'
/>

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
时间类控件硬编码 [color-scheme:dark],而本批已引入亮色主题体系(globals.css 的 .theme-light 块已设置 color-scheme: light)。亮色模式下浏览器原生 time 选择器(日历图标、下拉面板)仍按暗色方案渲染,与新 token 化界面割裂,属新主题特性的适配遗漏。免打扰结束时间与权益每日推送时间两处输入同样硬编码,建议移除逐控件硬编码,改为在 globals.css 的 .theme-dark/:root 与 .theme-light 上统一声明 color-scheme,让原生控件随主题切换。

Suggestion:

Suggested change
<input
type='time'
aria-label='免打扰起始'
disabled={disabled}
value={config.quiet_hours_start || '22:00'}
onChange={(e) => onChange({ quiet_hours_start: e.target.value })}
className='min-h-[44px] w-full rounded-xl border border-d-border bg-d-bg px-3 text-[16px] text-d-text [color-scheme:dark] outline-none focus:border-d-accent disabled:opacity-50'
/>
<input
type='time'
aria-label='免打扰起始'
disabled={disabled}
value={config.quiet_hours_start || '22:00'}
onChange={(e) => onChange({ quiet_hours_start: e.target.value })}
className='min-h-[44px] w-full rounded-xl border border-d-border bg-d-bg px-3 text-[16px] text-d-text outline-none focus:border-d-accent disabled:opacity-50'
/>

Comment thread lib/hooks/useTheme.ts
Comment on lines +13 to +17
useEffect(() => {
if (typeof window === 'undefined') return
const saved = localStorage.getItem(THEME_STORAGE_KEY) as ThemeMode | null
const initialTheme: ThemeMode = saved === 'light' || saved === 'dark' || saved === 'system' ? saved : 'system'
setThemeState(initialTheme)

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
主题仅在组件挂载后的 useEffect 中读取 localStorage 并写入 documentElement,水合前 SSR 首屏仍按 :root 暗色令牌渲染,亮色偏好用户刷新页面会出现暗色→亮色闪切(FOUC),且初始 resolvedTheme 也硬编码为 'dark'。建议在根布局注入水合前执行的内联脚本提前设置 data-theme/class;同时确认该 hook 在根布局层面全局挂载,否则未挂载本 hook 的页面(账单/卡片等)硬刷新后将回落暗色,主题偏好不全局生效。

Comment thread lib/hooks/useTheme.ts Outdated
Comment on lines +62 to +71
setResolvedTheme(resolved)
document.documentElement.setAttribute('data-theme', resolved)
if (resolved === 'light') {
document.documentElement.classList.add('theme-light')
document.documentElement.classList.remove('theme-dark')
} else {
document.documentElement.classList.add('theme-dark')
document.documentElement.classList.remove('theme-light')
}
}, [])

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
主题解析与应用逻辑(resolved 计算 + data-theme/class 写入)在 useEffect 内的 applyTheme 与 setTheme 中完整重复两份,且均以嵌套三元计算 resolved,后续维护易漂移。建议提取 resolveTheme(mode) 与 applyResolvedTheme(resolved) 辅助函数(模块级,非组件内声明)供两处复用。

Comment on lines +134 to 136
refreshPreferences: loadPreferences,
reload: loadPreferences
}

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
reload 与既有 refreshPreferences 指向同一函数、语义完全重复,对外 API 出现两个等价入口,调用方易混淆。建议保留其一(如仅 refreshPreferences 或将其重命名为 reload 并同步既有调用点)。

Comment thread app/(mobile)/bills/[id]/page.tsx Outdated
Comment on lines +110 to +112
card_holders: rawCard.card_holder
? { id: rawCard.card_holder.id, name: rawCard.card_holder.name, user_id: '' }
: undefined,

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
user_id: '' 是凭空造出的占位字段:CardHolder(lib/types.ts)并无 user_id 字段(为 created_by/auth_user_id/managed_by),且该字面量缺少 CardHolder 的多个必填字段(created_by/avatar_color/created_at),全靠外层 as CreditCardWithProduct 断言绕过检查。页面与 CardDefinitionModal/CardAccountModal 实际只消费 name,建议为详情页定义窄类型(如 { id: string; name: string })替代造字段 + 断言,避免下游误以为 holder 携带真实 user_id。

Suggestion:

Suggested change
card_holders: rawCard.card_holder
? { id: rawCard.card_holder.id, name: rawCard.card_holder.name, user_id: '' }
: undefined,
card_holders: rawCard.card_holder
? { id: rawCard.card_holder.id, name: rawCard.card_holder.name }
: undefined,

Comment on lines +64 to +67
export function resolvePayableCategorySelection(
rawCustom: unknown,
fallbackCategory: PayableCategory = 'other'
): ResolvedPayableCategorySelection | null {

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
自定义分类的解析流程(归一化 → 预设收拢 → 回落 other)在本文件与服务端 normalizePayableCategorySelection(payables.server.ts)各维护一份,后续规则调整(如长度上限、预设同义词表)需双处同步,否则前后端校验分叉。核心原语已在 payables.shared,建议把整个选择解析下沉到 shared 供两端复用。另外 resolvePayableCategorySelection / ResolvedPayableCategorySelection 全仓库无外部消费者,可随下沉移除组件文件的导出面。

Comment on lines +139 to +141
.catch(() => {
// 离线或未模拟该 RPC 时保留当前会话内已缓存的自定义分类
})

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
空 catch 会把词典加载的真实故障(网络失败、迁移未执行导致 payable_custom_categories 缺失等)一并吞掉,用户表现为「已保存的自定义分类消失」且无从排查。另外服务端 userId 由 RPC 路由 bindUser 注入(rpc-dispatch.ts 中 finalArgs[entry.bindUser] = user.id),此处传 user?.id 实际会被覆盖,未登录场景不会以 undefined 触达实现。建议至少在开发环境 console.warn 或区分错误类型上报。

Comment on lines +401 to +407
<TextField
type="month"
label="起算月份"
value={anchorPeriod}
onChange={e => setAnchorPeriod(e.target.value)}
helperText="首个应付账期"
/>

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
编辑已有记录时,清空「起算月份」输入框提交会走 trimmedAnchor || payablePeriodOf(),把原锚点静默重置为当前月,周期序列整体平移且用户无从感知;且该输入框未设 min,可提交远期月份(服务端目前也仅校验格式)。建议保留原值或给出确认提示,并加 min={payablePeriodOf()} 之类的边界约束。

type PayableWithStatus,
type PayablePaymentRecord,
} from '@/lib/api/payables'
import { NEXT_BILL_LEAD_DAYS } from '@/lib/api/payables.shared'

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
本文件其余 payables 相关导入均走桶文件 '@/lib/api/payables',唯 NEXT_BILL_LEAD_DAYS 直接引用 payables.shared;且桶文件已再导出 shared 的其它常量(含 PAYABLE_HISTORY_LIMIT)却漏了它,模块边界不一致。建议在 payables.ts 补导出并统一走桶文件。

Suggestion:

Suggested change
import { NEXT_BILL_LEAD_DAYS } from '@/lib/api/payables.shared'
import {
categoryLabel,
payableCycleLabel,
NEXT_BILL_LEAD_DAYS,
PAYABLE_HISTORY_LIMIT,
type PayableWithStatus,
type PayablePaymentRecord,
} from '@/lib/api/payables'

Comment on lines +544 to +549
const rawCustom =
patch.custom_category !== undefined
? patch.custom_category
: patch.category !== undefined
? null
: existing.data.custom_category

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
两层嵌套三元违反团队「禁止嵌套三元」规范(本组客户端 CYCLE_AMOUNT_LABELS 处注释同样明确了该约定),分支优先级不易读,建议拆为 if/else。

Suggestion:

Suggested change
const rawCustom =
patch.custom_category !== undefined
? patch.custom_category
: patch.category !== undefined
? null
: existing.data.custom_category
let rawCustom: unknown
if (patch.custom_category !== undefined) {
rawCustom = patch.custom_category
} else if (patch.category !== undefined) {
rawCustom = null
} else {
rawCustom = existing.data.custom_category
}

return
}

console.log('检测到数据库环境,正在加载卡片与邮件日志...')

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
生产分支检测到 D1 环境后仅打印「正在加载卡片与邮件日志...」即结束,没有任何数据加载、汇总或报告输出逻辑,属误导性死分支——使用者会误以为已执行真实汇总。在实现真实加载逻辑前,应明确输出 NOT IMPLEMENTED 并以非零码退出,或直接移除该分支。

Comment thread worker/cron.ts
Comment on lines +33 to +34
card_number_last4: string | null;
account_statement_mode: string | null;

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
BillWithCard 接口新增并 SELECT 了 cc.card_number_last4,但后续逻辑只使用另行查询得到的 accountCardsMap.firstTail,该字段属声明后未读取的无用字段,可从接口定义与 SELECT 列中一并移除。

Comment thread worker/cron.ts
Comment on lines +153 to +157
// 若为合并账户且有多张 active 卡,文案升级为合并账单口径
const accInfo = bill.account_id ? accountCardsMap[bill.account_id] : null;
const isMultiCardMerged = Boolean(
bill.account_statement_mode === "merged" && accInfo && accInfo.count > 1,
);

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
合并账户(statement_mode='merged')下每张卡的账单行仍各自进入通知循环,去重键仍为 bill:${bill.id}:${today},同一合并账户当天会对每张卡各发一条标题相同的通知;且标题宣称「合并账单(含尾号 X 等 N 张卡)」,正文金额却取单卡 bill_amount,用户极易误读为账户应还总额。历史账单(account_id 为 NULL)经 OR 回退 join 也会命中该分支。建议按账户(或用户+账户)维度合并去重并使用合并总额,或在文案中明确标注为单卡金额。

Suggestion:

Suggested change
// 若为合并账户且有多张 active 卡,文案升级为合并账单口径
const accInfo = bill.account_id ? accountCardsMap[bill.account_id] : null;
const isMultiCardMerged = Boolean(
bill.account_statement_mode === "merged" && accInfo && accInfo.count > 1,
);
const notificationKey = isMultiCardMerged
? `bill:account:${bill.account_id}:${today}`
: `bill:${bill.id}:${today}`;

Comment thread worker/cron.ts
title = `已逾期:${bill.bank_name || ""} ${cardName}`;
body = `账单 ¥${bill.bill_amount} 已逾期 ${Math.abs(daysUntil)} 天`;
title = `已逾期:${cardSubject}`;
body = `${cardSubject}账单 ¥${bill.bill_amount} 已逾期 ${Math.abs(daysUntil)} 天`;

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
通知正文将 cardSubject 与「账单 ¥…」直接拼接,如「…合并账单(含尾号 1234 等 3 张卡)账单 ¥1500 今天到期」,缺少分隔符,可读性较差;cardSubject 为空时开头也会直接是「账单」。建议在标题与正文之间补充空格或标点。

Suggestion:

Suggested change
body = `${cardSubject}账单 ¥${bill.bill_amount} 已逾期 ${Math.abs(daysUntil)} 天`;
body = `${cardSubject} 账单 ¥${bill.bill_amount} 已逾期 ${Math.abs(daysUntil)} 天`;

Comment thread lib/due-date-summary.ts
Comment on lines +169 to +182
if (r.includes('AI 解析失败')) {
items.push({
source: 'email_parse_log',
id: `${log.id}#${i + 1}`,
created_at: createdAt,
from_email: fromEmail,
subject: entry?.label ? `${subject ?? '转发包'} (${entry.label})` : subject,
bank_name: null,
card_last4: null,
reason_code: 'parse_failed',
reason_label: DUE_DATE_ISSUE_LABELS.parse_failed,
detail: r,
})
} else if (r.includes('宽限期') || r.includes('模糊')) {

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
转发包 skipped 分支三段近乎相同的 EmailIssueSummaryItem 对象构造,仅 reason_code / reason_label 不同(id/created_at/subject 等完全一致),属重复代码,建议提取局部工厂函数(如 makeItem(reasonCode, detail))消除重复。

Comment thread lib/due-date-summary.ts
Comment on lines +213 to +220
// 2. 明确的非账单(营销/自动扣款通知/验证邮件)不计入账单还款日缺失
if (
errMsg.startsWith('Gmail 转发验证') ||
errMsg.includes('email_kind=') ||
(parsed && parsed.is_bill === false)
) {
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.

maintainability · medium
四类缺失原因的判定大量依赖 error_msg / skipped reason 的中文子串匹配('宽限期'、'模糊'、'AI 解析失败'、'邮件未提供确切还款日'、'Gmail 转发验证'、'email_kind=' 等),这些文案由 email-worker、lib/gmail/sync.server.ts 等上游以自由文本写入,形成隐式字符串契约:上游措辞一旦微调即导致静默误分类,使还款日统计报告失真,与模块「绝不伪造统计」的目标冲突。建议上游落库时写入机器可读的 reason_code / error_code 字段,本模块按枚举值匹配而非文案子串。

Comment thread lib/due-date-summary.ts
Comment on lines +701 to +707
if (
(entry.explicitCardId && entry.explicitCardId === card.id) ||
matchesCard(card, entry.item)
) {
cardIssues.push(entry.item)
matchedIssueIds.add(`${entry.item.source}:${entry.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.

bug · medium
issue 与卡的匹配逻辑:当 entry.explicitCardId 已设置但与当前卡 id 不相等时,仍会继续走 matchesCard 启发式兜底(尾号相等 + 银行名双向 includes)。用户持有多张同尾号或银行名相近的卡时,同一 issue 会同时计入多张卡的 reason_counts、email_evidences 及全局 by_reason,造成缺失原因重复计数、统计偏大。已显式绑定卡片的 issue 应在 id 不匹配时直接跳过,不再走启发式。

Suggestion:

Suggested change
if (
(entry.explicitCardId && entry.explicitCardId === card.id) ||
matchesCard(card, entry.item)
) {
cardIssues.push(entry.item)
matchedIssueIds.add(`${entry.item.source}:${entry.item.id}`)
}
if (entry.explicitCardId && entry.explicitCardId !== card.id) continue
if (entry.explicitCardId === card.id || matchesCard(card, entry.item)) {
cardIssues.push(entry.item)
matchedIssueIds.add(`${entry.item.source}:${entry.item.id}`)
}

Comment thread lib/due-date-summary.ts
Comment on lines +776 to +779
query<EmailParseLog>(
`SELECT * FROM email_parse_logs WHERE user_id IN (${placeholders}) ORDER BY created_at DESC LIMIT 200`,
ownerIds,
),

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
loadCardDueDateResolution 为单张卡对 email_parse_logs / gmail_sync_messages / bill_import_drafts 各执行一次 LIMIT 200 查询,且 email_parse_logs 使用 SELECT *(含 raw_ai_response 大字段);若在卡片列表等场景逐卡调用会形成重量级 N+1 查询,拖慢接口。此外该函数按 holder 反查 owner 后拉取其全部邮件摘要(发件人/主题),需确认所有调用方均已做用户归属/成员范围校验,否则存在越权读取他人邮件元数据的风险。建议列表场景改用 buildDueDateReasonReport 批量汇总,并只 SELECT 必要列。

Comment thread lib/due-date-summary.ts

const report = buildDueDateReasonReport({
cards: [card],
bills: (billRows ?? []) as Bill[],

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
(billRows ?? []) as Bill[] 的类型断言冗余且方向可疑:billRows 本就是 query 的结果,而 buildDueDateReasonReport 的 bills 参数类型即 BillForDueDateSummary[],直接传 billRows ?? [] 即可;同时可移除仅为该断言引入的 Bill 类型导入。

Suggestion:

Suggested change
bills: (billRows ?? []) as Bill[],
bills: billRows ?? [],

Comment thread app/(mobile)/cards/[id]/page.tsx Outdated
Comment on lines +85 to +87
const [cardDefOpen, setCardDefOpen] = useState(false)
const [cardAccountOpen, setCardAccountOpen] = useState(false)
const [holders, setHolders] = useState<Array<{ id: string; name: string }>>([])

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
本页 cardFormOpen 已无任何置 true 的入口(原「编辑卡片」按钮已改开 CardAccountModal),下方整个 CardForm 区块(含 holder 变更双通道逻辑)成为不可达死代码;而这里的 holders state 与 load() 中新增的 getHolders() 请求仅服务于这个打不开的 CardForm(CardAccountModal 自己会拉取持卡人),导致每次进入详情页都多一次无用的 RPC 请求。建议整体移除 cardFormOpen/holders/getHolders 及 CardForm 渲染块,或明确恢复其入口。

Suggestion:

Suggested change
const [cardDefOpen, setCardDefOpen] = useState(false)
const [cardAccountOpen, setCardAccountOpen] = useState(false)
const [holders, setHolders] = useState<Array<{ id: string; name: string }>>([])
+ const [cardDefOpen, setCardDefOpen] = useState(false)
+ const [cardAccountOpen, setCardAccountOpen] = useState(false)
+ // CardForm 区块已由 CardDefinitionModal/CardAccountModal 取代,
+ // 同步移除 cardFormOpen state、holders state 与 load() 中的 getHolders() 请求

Comment thread app/(mobile)/cards/[id]/page.tsx Outdated
Comment on lines 424 to 425
<a
key={o.account_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.

other · low
/promos 是本应用内的移动端路由(app/(mobile)/promos/page.tsx),其他入口(dashboard/settings)均通过 router.push 或默认保留客户端路由。这里由 next/link 改为原生 会导致整页刷新,丢失 App Router 的客户端导航与预取,属于体验回退;除非有意强制全量刷新,建议恢复 next/link。

Suggestion:

Suggested change
<a
key={o.account_id}
+ <Link
+ key={o.account_id}

Comment thread app/(mobile)/settings/page.tsx Outdated
Comment on lines +67 to +71
function formatGmailSummary(status: GmailConnectionStatus | null): string {
if (status?.connected) return '已连接'
if (status?.last_error) return '需重连'
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
getGmailConnection 请求进行中或加载失败(catch 置 null)时,徽章均显示「未连接」,与真实状态不符;加载失败时会让已连接用户误判为从未连接。建议区分 loading / error / 未连接三态,例如错误态显示「加载失败」并支持重试。

Comment thread app/admin/settings/page.tsx Outdated
Comment on lines +117 to +123
// 1. 提交所有 dirty 字段(逐 key 并行提交)
const results = await Promise.allSettled(
dirtyKeys.map(async (k) => {
await updateSystemSettings(k, formSettings[k] as string | boolean)
return k
})
)

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
多个设置 key 用 Promise.allSettled 并行提交。若服务端 updateSystemSettings 的写入实现是对同一存储(如单行 JSON 文档或聚合 KV 键)读-改-写,并发请求可能互相覆盖导致丢更新,且部分失败后仅能依赖前端 dirty 状态重试。建议确认服务端按 key 独立存储或原子合并;若无法保证,改为串行提交即可(dirty key 数量很小,串行开销可忽略)。

<div className='flex flex-col gap-2'>
{bankCards.map(c => {
const isBelongToTarget = !!targetAccountId && (c.account_id === targetAccountId || c.account?.id === targetAccountId)
const isTargetAnchor = isBelongToTarget && (c.account?.primary_card_id === c.id || bankCards.find(bc => (bc.account_id === targetAccountId || bc.account?.id === targetAccountId))?.id === c.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 · low
锚点卡判定混入了 bankCards.find 兜底:当卡片只有 account_id 而未携带 account 对象(或账户未设置 primary_card_id)时,会把「第一张归属目标账户的卡」标注为锚点卡,可能与真实主卡不一致,向用户传达错误的不可合并对象。建议锚点标注仅以 account.primary_card_id 为准,未设置时不展示该标注(文案可统一为「已在目标账户中」)。

Suggestion:

Suggested change
const isTargetAnchor = isBelongToTarget && (c.account?.primary_card_id === c.id || bankCards.find(bc => (bc.account_id === targetAccountId || bc.account?.id === targetAccountId))?.id === c.id)
+ const isTargetAnchor = isBelongToTarget && c.account?.primary_card_id === c.id

Comment on lines +54 to +57
<select
id='default-currency-select'
value={config.default_currency || 'CNY'}
onChange={(e) => onChange({ default_currency: e.target.value })}

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
币种由自由输入改为 6 项白名单下拉后,若存量数据存储了白名单外的值(如 SGD),原生 select 无匹配 option 时会显示为空白选中项,用户可能误以为未设置而误改配置。建议对白名单外的存量值动态追加一个选项(可参考同文件 ReminderPreferencesCard 对时区白名单外值的合并做法)。

Comment on lines +25 to +31
const TIMEZONE_OPTIONS = [
{ value: 'Asia/Shanghai', label: 'Asia/Shanghai (中国标准时间 UTC+8)' },
{ value: 'America/New_York', label: 'America/New_York (美东时间 UTC-5)' },
{ value: 'Europe/London', label: 'Europe/London (格林威治时间 UTC+0)' },
{ value: 'Asia/Tokyo', label: 'Asia/Tokyo (日本标准时间 UTC+9)' },
{ value: 'Asia/Hong_Kong', label: 'Asia/Hong_Kong (香港时间 UTC+8)' },
]

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
时区选项标注的静态 UTC 偏移未考虑夏令时:America/New_York 夏令时为 UTC-4,Europe/London 夏令时为 UTC+1,标注会随季节误导用户。建议去掉偏移标注或注明「标准时间」,也可改用 Intl.DateTimeFormat 动态生成。

Comment on lines +55 to +58
// 存量用户没有 enabled_channels 字段时,按旧语义默认开启 Web Push
const isWebPushEnabled = (config.enabled_channels ?? ['web_push']).includes('web_push')
const handleToggleWebPush = (enabled: boolean) => {
const currentChannels = config.enabled_channels ?? ['web_push']

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
旧配置字段 opportunities.web_push_enabled 被整体移除,改用顶层 enabled_channels(缺省时默认 ['web_push'])。存量用户此前通过 web_push_enabled=false 关闭过 Web Push 的偏好不会被迁移,升级后将按默认值重新开启推送,属静默行为回退。同时需确认服务端(worker/cron.ts、lib/api/push.ts、preferences 存取)已同步改为读取 enabled_channels,否则 UI 开关与实际推送口径漂移(UI 已关闭但后端仍推送)。建议读取偏好时兼容旧字段,或提供一次性数据迁移。

Suggestion:

Suggested change
// 存量用户没有 enabled_channels 字段时,按旧语义默认开启 Web Push
const isWebPushEnabled = (config.enabled_channels ?? ['web_push']).includes('web_push')
const handleToggleWebPush = (enabled: boolean) => {
const currentChannels = config.enabled_channels ?? ['web_push']
// 兼容旧字段:曾显式关闭 web_push_enabled 的存量用户不应被默认重新开启
const isWebPushEnabled = config.enabled_channels
? config.enabled_channels.includes('web_push')
: config.opportunities?.web_push_enabled !== false
const handleToggleWebPush = (enabled: boolean) => {
const currentChannels = config.enabled_channels
?? (config.opportunities?.web_push_enabled === false ? [] : ['web_push'])

Comment on lines 85 to 89
new Notification('🔔 WorldCredit 适时提醒', {
body: '这是一条测试还款提醒!您的提醒节点与免打扰时间配置已生效。',
icon: '/pwa-192x192.png',
tag: 'worldcredit-test-reminder'
tag: 'worldcredit-test-reminder',
})

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
sendTestPush() 已在服务端真实下发推送(按钮文案标注「真实 /api/push/test」),成功后客户端又本地 new Notification(...),用户很可能收到两条重复通知;此外本地 Notification 绕过了 enabled_channels 关闭 Web Push 的开关语义。建议二选一:服务端发送成功后仅用 Toast 提示,或回退为纯本地预览、不调用服务端接口。另外请核对 lib/api/push.ts 中 sendTestPush 的返回形状与 res.ok/res.error 解构一致。

Comment on lines +85 to +93
} catch (err) {
// Rollback on write failure
setDisplayConfig(prev)
if (typeof window !== 'undefined') {
const currentCache = JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}')
localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...currentCache, display_config: prev }))
}
throw 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.

bug · medium
updateDisplay 写库失败时回滚并 rethrow。本组设置页已 try/catch,但同文件未改动的 togglePrivacyMode 及其它以 fire-and-forget 方式调用 updateDisplay/updateReminder 的调用方(如账单/卡片页的隐私开关)会变成未处理的 Promise rejection,且回滚对用户完全无提示。建议排查全部调用点补充 catch 与错误提示,或让 togglePrivacyMode 内部捕获后自行向上层暴露错误状态。

}
}

const themeLabel = THEME_LABELS[theme] ?? '💻 跟随系统'

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
THEME_LABELS 为 Record<ThemeMode, string> 且 theme 类型恒为 'dark' | 'light' | 'system' 三种字面量,THEME_LABELS[theme] 永不返回 undefined,?? 后的回退分支不可达,属死代码,建议直接使用 THEME_LABELS[theme]。

Suggestion:

Suggested change
const themeLabel = THEME_LABELS[theme] ?? '💻 跟随系统'
const themeLabel = THEME_LABELS[theme]

Comment on lines +287 to +290
<span
role='button'
tabIndex={0}
aria-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.

other · low
「重试」span 设置了 role='button'、tabIndex 并带 onClick/onKeyDown,却嵌套在 SettingsMenuRow 的 内部。HTML 规范禁止 button 内再嵌套交互式内容(浏览器解析会拆解嵌套交互元素,读屏播报与焦点顺序异常),且整行跳转与重试的行为依赖手动 stopPropagation 维持。建议将行容器改为 div(配 role/键盘事件)承载跳转、重试用真实 ;或将「重试」移出该行按钮热区单独成行。

Comment thread app/globals.css
Comment on lines +242 to +245
.theme-light,
[data-theme="light"] {
--color-d-bg: var(--color-d-light-bg);
--color-d-surface: var(--color-d-light-surface);

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
新增亮色覆盖块仅映射了 17 个令牌(bg/surface/subtle/border/text/muted/accent/accent-light/gold/gold-deep/gold-soft/danger/danger-soft/danger-ink/warn-ink/success-soft/success-ink),且亮色变量集未定义 warn(仅 warn-ink)。请核对 :root 既有 --color-d-* 基础令牌全量清单:若还存在本覆盖块未映射的令牌(如 --color-d-warn / --color-d-warn-soft / --color-d-accent-soft 等),它们在亮色模式下会继续取暗色值,导致警告条、提示胶囊等组件在亮色主题下配色错误、对比度下降。建议补齐缺失映射,或显式注释「有意沿用暗色值」的例外清单。

Comment on lines +48 to +55
const bankOptions = useMemo(() => {
const counts: Record<string, number> = {}
for (const c of cards) {
const bName = c.card_product?.bank_name || '其他银行'
counts[bName] = (counts[bName] || 0) + 1
}
return Object.keys(counts).filter(b => counts[b] >= 2)
}, [cards])

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
bankOptions 的注释声称「只有同人、同银行且 >= 2 张卡的才有合并价值」,但分组逻辑未按 holder_id 过滤:同一银行下不同持卡人的卡会被混入同一候选列表,且 >= 2 的计数跨持卡人统计(两位持卡人各持 1 张同银行卡也会显示为可合并)。虽然服务端 mergeCardsIntoAccount 会以「不可跨持卡人合并信用账户与信用卡」拒绝跨人合并(数据不会被污染),但用户按此列表勾选后提交必然失败,且失败点在最后一步,体验上属于契约不符。建议分组键改为 holder_id + 银行(如 ${c.holder_id}|${bName}),或在进入向导时先按持卡人筛选候选卡。

Suggestion:

Suggested change
const bankOptions = useMemo(() => {
const counts: Record<string, number> = {}
for (const c of cards) {
const bName = c.card_product?.bank_name || '其他银行'
counts[bName] = (counts[bName] || 0) + 1
}
return Object.keys(counts).filter(b => counts[b] >= 2)
}, [cards])
const bankOptions = useMemo(() => {
const counts: Record<string, number> = {}
for (const c of cards) {
// 同人 + 同银行才有合并价值;跨持卡人的卡不得计入同一分组
const key = `${c.holder_id}|${c.card_product?.bank_name || '其他银行'}`
counts[key] = (counts[key] || 0) + 1
}
return Object.keys(counts).filter(k => counts[k] >= 2)
}, [cards])

Comment on lines +155 to +156
return (
<Modal open={open} onClose={onClose} title='合并为统一账单账户'>

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
合并是不可逆操作(下方确认文案明示「此操作不可撤销」),但执行期间 Modal 仍为默认 dismissible=true:loading 中用户按 Esc 或点遮罩即可关闭弹窗,mergeCardsIntoAccount 在后台继续执行,完成后 onSuccess() 触发父级刷新——弹窗已关、成功/失败结果均无处展示。Modal 组件的 dismissible 参数注释明确写着「确认中置 false 可禁止 Esc/遮罩关闭」,本组件恰好是应使用的场景。建议在 loading(或 showConfirm)期间禁用误关闭。

Suggestion:

Suggested change
return (
<Modal open={open} onClose={onClose} title='合并为统一账单账户'>
return (
<Modal open={open} onClose={onClose} title='合并为统一账单账户' dismissible={!loading}>

Comment on lines +397 to +398
{b.subtotals.map(sub => (
<div key={sub.card_tail} className='flex justify-between items-center'>

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
分卡小计列表用 card_tail 作为 React key:合并账户(multi)下多张成员卡尾号相同时(如两张卡同为尾号 8888),bill_card_subtotals 会出现多行相同 card_tail,导致 key 重复、渲染异常。BillCardSubtotal.id 为必有字段(lib/types.ts:142),直接用它作为 key 更稳妥。

Suggestion:

Suggested change
{b.subtotals.map(sub => (
<div key={sub.card_tail} className='flex justify-between items-center'>
{b.subtotals.map(sub => (
<div key={sub.id} className='flex justify-between items-center'>

Comment on lines +63 to +68
// 存量迁移写回:读取到 enabled_channels 未设置且旧 opportunities.web_push_enabled === false 时,写回一次
useEffect(() => {
if (config.enabled_channels === undefined && config.opportunities?.web_push_enabled === false) {
onChange({ enabled_channels: [] })
}
}, [config.enabled_channels, config.opportunities?.web_push_enabled, onChange])

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
存量迁移口径在三处重复实现(本 effect、lib/hooks/useUserPreferences.loadPreferences 写回、shared.ts resolveEffectiveChannels),易漂移;且本 effect 依赖 onChange,而调用方(app/(mobile)/settings/page.tsx)传入的是每次渲染重建的内联箭头函数,effect 每轮渲染都会重跑。一旦 updateReminder 写库失败、hook 回滚到 enabled_channels === undefined 且 opportunities.web_push_enabled === false 的旧值,守卫条件重新满足,将形成「触发 → 失败 → 回滚 → 再触发」的循环 API 调用。建议:迁移统一收敛到 hook 层后删除本 effect;若必须保留,请用 useRef 做一次性守卫,并让调用方以 useCallback 稳定 onChange。另外 lib/hooks 反向依赖 @/components/settings/shared 属分层倒置,建议将该工具下沉到 lib 目录。

Suggestion:

Suggested change
// 存量迁移写回:读取到 enabled_channels 未设置且旧 opportunities.web_push_enabled === false 时,写回一次
useEffect(() => {
if (config.enabled_channels === undefined && config.opportunities?.web_push_enabled === false) {
onChange({ enabled_channels: [] })
}
}, [config.enabled_channels, config.opportunities?.web_push_enabled, onChange])
const migratedRef = useRef(false)
useEffect(() => {
if (migratedRef.current) return
if (config.enabled_channels === undefined && config.opportunities?.web_push_enabled === false) {
migratedRef.current = true
onChange({ enabled_channels: [] })
}
}, [config.enabled_channels, config.opportunities?.web_push_enabled, onChange])

Comment thread lib/api/admin.server.ts
}

const dueDate = parsed.due_date ?? parsed.statement_date ?? `${billMonth}-28`
const dueDate = exactDue ?? parsed.statement_date ?? `${billMonth}-28`

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
当账单金额为 0(zeroBill)且邮件无精确还款日时,此处仍回退 statement_date ?? ${billMonth}-28,将含硬编码兜底日(28 号)的编造日期写入账单,与上方「禁止编造还款日」的硬校验口径不一致。若属有意豁免(零账单无需还款、不触发还款提醒),请在注释中显式说明豁免口径,避免后续维护者误判为漏洞;若非有意,建议零账单分支同样要求 exactDue 或存空值。

Comment thread lib/hooks/useTheme.ts
Comment on lines +59 to +61
export function useTheme() {
const [theme, setThemeState] = useState<ThemeMode>(getStoredThemeMode)
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>(getInitialResolvedTheme)

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
useState 初始化器在水合首帧即同步读取 localStorage(getStoredThemeMode)/ DOM(getInitialResolvedTheme),而 SSR 输出恒为 'system'。app/(mobile)/settings/page.tsx 依据 theme 直接渲染「🌙 暗色 / ☀️ 亮色 / 💻 跟随系统」文案,非 system 模式用户首帧即产生水合不一致,React 18 会抛出水合错误并触发整树客户端重渲染(控制台报错 + 首屏闪烁)。app/layout.tsx 的 suppressHydrationWarning 只作用于 单层节点,覆盖不到该文本差异。建议初始值固定为 'system'(与 SSR 一致),在下方已有的 useEffect 中再读存储同步;或让消费方在 mounted 前不渲染依赖主题的文案。

Suggestion:

Suggested change
export function useTheme() {
const [theme, setThemeState] = useState<ThemeMode>(getStoredThemeMode)
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>(getInitialResolvedTheme)
export function useTheme() {
// 首帧固定 'system' 与 SSR 输出一致,避免依赖主题的文案水合不一致;挂载后再同步本地存储
const [theme, setThemeState] = useState<ThemeMode>('system')
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>('light')

Comment on lines +133 to +136
if (typeof window !== 'undefined') {
const currentCache = JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}')
localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...currentCache, display_config: prev }))
}

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
回滚路径(以及 updateDisplay/updateReminder 的乐观写缓存路径)直接 JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}') 且未包 try。loadPreferences 已对缓存损坏做了兜底,说明缓存损坏属预期场景:一旦缓存损坏,这里会在调用 updateUserPreferences 之前抛出,导致乐观态已应用却不走回滚分支、页面弹出误导性「保存失败」且服务端未写入。建议抽取带 try 的安全解析助手统一复用。另外新增的 showToastMessage 用原生 DOM 手工拼装 Toast(含 z-index/定位样式),与项目既有 Toast 组件能力重复,建议复用 Toast 以降低维护成本。

@hubo1989
hubo1989 merged commit 536d920 into main Nov 6, 2026
4 checks passed
@hubo1989
hubo1989 deleted the fix/bugs branch November 6, 2026 03:18
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