Skip to content

feat(notifications): 概览当日待还总金额、主动通知增强、通知中心与全通知项开关(Web + iOS) - #56

Merged
hubo1989 merged 3 commits into
mainfrom
feat/notification-center-due-today
Nov 21, 2026
Merged

hubo1989 merged 3 commits into
mainfrom
feat/notification-center-due-today

Conversation

@hubo1989

Copy link
Copy Markdown
Owner

变更概览

  1. 概览页增加当日待还总金额(Web + iOS)

    • 统计口径:当天到期(days_until_due === 0)且未结清的信用卡账单剩余待还 + 当天到期且未结清的固定支出(recurring_payables)剩余金额,跟随持卡人筛选联动,按原币种分组折算至 displayCurrency,缺汇率外币记入 unconvertedCurrencies(不 1:1 混加)。
    • Web 与 iOS 概览页顶部副指标新增「当日待还」,「今天需还款」卡片汇总当日待还总金额与笔数,同时列出当日账单与固定支出(iOS 支持直接点击「标记已付」)。
  2. 主动通知增强(当日待还 + 今日新增最长免息期账单)

    • 当日待还主动通知(due_today_summary:YYYY-MM-DD)汇总当日到期的信用卡账单(受 bill_due_today 开关控制)与固定支出(受 payable_due_today 开关控制),展示分币种总额与逐笔明细。
    • 今日新增最长免息期账单(grace_longest:YYYY-MM-DD)按「账单日次日触发」规则(含小月/2 月月末钳制,如 billing_day = 31 于 3/1 触发,同合并账户多卡去重,排除贷款卡及非活跃卡),受 grace_period_longest 开关控制;iOS 本地调度器同步支持。
    • worker/cron.ts 接入 user_preferences.reminder_config、覆盖到期日/覆盖金额/已还扣除、isInQuietHours 免打扰判断、push_sent_at 单次下发与无订阅仍写入站内通知。
  3. 通知中心与全通知项独立开关(Web + iOS)

    • 新增 D1 迁移 migrations/d1/0033_notification_center.sql(category、target_url、metadata_json、read_at、deleted_at、push_sent_at)。
    • 新增 6 个 bindUser: 0 会话隔离 RPC(getNotifications、getUnreadNotificationCount、markNotificationRead、markAllNotificationsRead、deleteNotification、deleteAllNotifications),采用 deleted_at 软删除保留 (user_id, notification_key) 唯一去重,避免当日已删通知复活。
    • Web(/notifications、/settings)与 iOS(NotificationsCenterView、NotificationSettingsView、DashboardView、SettingsView)均支持通知中心全量正文/结构化明细查看、单条/全部已读、单条/全部删除(Obsidian ConfirmDialog / SwiftUI confirmationDialog 二次确认)以及全部 12 项独立开关(存量缺省全开,且 opportunity_reset / opportunity_booking 与 opportunities.reset_enabled / booking_enabled 双向同步)。

数据与安全说明

  • D1 迁移提示:上线部署前需执行 wrangler d1 migrations apply worldcredit --remote 以应用 0033_notification_center.sql。
  • 隔离与兼容:所有 notifications.* RPC 在注册表统一配置 bindUser: 0;存量无 items 字段的用户偏好默认全部通知项开启;useUserPreferences.ts 增加 getSafeStorage() 安全包装避免非标准存储环境报错。

本地验证结果

  • npm run typecheck:通过(0 错误)
  • npm run lint:通过(0 警告)
  • npm test:通过(103 个测试文件;1158 通过、1 既有跳过 lib/__tests__/cmb-statement-phase3.test.ts)
  • npx vinext build:通过(含 /notifications 路由与 dist/sw.js)
  • bash design/openpencil/verify-batch.sh --source-only:通过(baoyu-design 4 项门禁与 .op 冻结检查全 PASS)
  • swift test(ios/Packages/WorldCreditCore):通过(25 suites / 184 tests 全过)
  • xcodebuild -project ios/WorldCredit.xcodeproj -scheme WorldCredit -destination 'generic/platform=iOS Simulator' CODE_SIGNING_ALLOWED=NO build:** BUILD SUCCEEDED **

@coderabbitai

coderabbitai Bot commented Nov 20, 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: 903727c9-338e-4e6f-8ef7-8dc34fd2668b
  • 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

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T15:15:15.988322Z e6285fd PR opened
🔒 Security Review ✅ Completed 2026-11-20T15:12:42.925994Z e6285fd 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e6285fd286

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +122 to +124
if (prefRow?.reminder_config) {
try {
const parsed = JSON.parse(prefRow.reminder_config) as Partial<UserReminderConfig>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve legacy notification opt-outs

When a user has any valid user_preferences.reminder_config—including the schema's default JSON—this branch returns before reading notification_preferences. Existing users whose legacy bill_due_enabled or overdue_enabled is false therefore get resolveNotificationSwitches(parsed) defaults of true and begin receiving reminders they explicitly disabled; the legacy flags need to be merged whenever the new per-item keys are absent, not only when the entire reminder config is missing or corrupt.

Useful? React with 👍 / 👎.

Comment on lines +488 to +490
// 4.6 Respect user's Web Push channel preference (and switch state) before pushing
const userWorld = usersById.get(job.user_id)
if (userWorld && !userWorld.webPushGloballyEnabled) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recheck opportunity switches before retrying claimed jobs

If an opportunity job is left pending or partial after a failed delivery and the user disables that opportunity category before the next 15-minute scan, the job is still claimed and sent: switch checks only run while creating new jobs, while this delivery-time guard checks only the global Web Push channel. Re-evaluate the current global and per-category opportunity switches for each claimed job so disabling a reminder also cancels outstanding retries.

Useful? React with 👍 / 👎.

Comment on lines +30 to +31
const ACTIVITY_DAY_CHOICES = [1, 3, 7, 15]
const TASK_DAY_CHOICES = [0, 1, 3, 7]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wire activity and task day choices into the cron

The new activity and task advance-day controls persist activity_days_before and task_days_before, but buildDueDeliveries never reads either array: threshold nodes are generated only for cycle_expiry and claim_window_deadline using expiry_days_before or claim_days_before, while task/activity events receive only their date-of-event node. Consequently changing either new control has no effect on delivered notifications; the cron must generate the corresponding dN steps from these settings.

Useful? React with 👍 / 👎.

Comment on lines +216 to +220
private func persist(_ next: UserReminderPreferences) {
saveError = nil
Task {
do {
try await appState.updateReminderPreferences(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.

P2 Badge Serialize iOS reminder preference saves

Each toggle starts an independent task that sends the entire UserReminderPreferences value, while the controls remain interactive during the request. If a user changes two switches quickly, both requests run concurrently and the earlier snapshot can finish last, overwriting the newer server state and assigning its stale response back to reminderPreferences; a failure can similarly roll back a later successful change. Queue/cancel saves or use a revision check before applying responses and rollbacks.

Useful? React with 👍 / 👎.

Comment on lines +112 to +115
const res = await getNotifications({ filter: nextFilter, limit: 100, syncToday: true })
setItems(res.items)
setUnreadCount(res.unread_count)
setTotalCount(res.total_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.

P2 Badge Add pagination to the notification center

Once a user has more than 100 non-deleted notifications, this request permanently exposes only the newest 100 even though total_count reports the larger number; there is no load-more or offset path in this view. The iOS client uses the same fixed limit: 100, offset: 0, so older notifications cannot be viewed, marked individually, or followed on either client. Implement pagination or an infinite-loading path instead of presenting this capped result as the complete notification history.

Useful? React with 👍 / 👎.

Comment on lines +254 to +263
Section {
if item.isUnread {
Button("标记为已读") {
Task {
await performMarkRead(item.id)
selectedNotification = item.markingRead(at: ISO8601DateFormatter().string(from: Date()))
}
}
}
Button("删除此通知", role: .destructive) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Route iOS notification targets

The server supplies target_url for bill, card, dashboard, and benefit notifications and the iOS DTO decodes it, but the native detail actions only offer mark-read and delete and never use item.targetUrl. The push delegate also has no notification-response handler, so tapping an APNs notification containing the new url custom data merely opens the app without reaching its target. Add a shared native routing path for both notification-center actions and push taps.

Useful? React with 👍 / 👎.

Comment thread worker/cron.ts Outdated
Comment on lines +106 to +111
const canSendWebPush =
!inQuiet && userSubs.length > 0 && isUserWebPushEnabled(context.reminderConfigRaw);
const canSendApns =
!inQuiet &&
userDevices.length > 0 &&
Boolean(env.APNS_KEY_P8 && env.APNS_KEY_ID && env.APNS_TEAM_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.

P1 Badge Apply the push-channel opt-out to APNs

When an iOS user disables the new “Web Push / 站外推送” setting, enabled_channels no longer contains web_push, so canSendWebPush becomes false, but canSendApns ignores the same preference and remains true whenever a device token and APNs credentials exist. Those users therefore continue receiving every bill notification through APNs after opting out; gate APNs with the resolved channel preference as well.

Useful? React with 👍 / 👎.

Comment thread lib/reminders.ts Outdated
Comment on lines +155 to +156
if (daysUntil === 0 && !switches.bill_due_today) continue
if (daysUntil > 0 && !switches.bill_due_advance) continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor selected advance days for loan reminders

For loan cards, keeping bill_due_advance enabled is the only condition applied here; the user's remind_days_before set is never consulted. A user who removes the 3-day or 1-day node—while retaining another advance node—will still receive the hard-coded loan reminder on those deselected days. Pass the allowed-day set into checkLoanReminders and require membership just as the normal bill loop does.

Useful? React with 👍 / 👎.

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

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

  • ✅ Successfully posted inline: 18 comment(s)

⚠️ 4 warning(s) occurred during review.


⚠️ Warnings:

  • lib/api/notifications.server.ts (token_budget_reached): skipped round 2 of group "lib/api/notifications.server.ts,lib/api/notifications.ts,lib/api/registry.ts,lib/dashboard-metrics.ts,lib/notifications-engine.server.ts,lib/notifications.shared.ts,lib/reminders.ts,lib/types.ts": used 2050322 tokens exceeds budget 2000000
  • ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/DashboardMetrics.swift (token_budget_reached): stopped dispatch: used 2050322 tokens + group estimate 176760 = projected 2227082 exceeds budget 2000000
  • app/(mobile)/dashboard/page.tsx,app/(mobile)/notifications/page.tsx,app/(mobile)/settings/page.tsx,components/mobile/NotificationCenterView.tsx,components/obsidian/DashboardView.tsx,components/settings/ReminderPreferencesCard.tsx (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task
  • app/api/push/test/route.ts,lib/api/bills.server.ts,lib/api/preferences.server.ts,lib/api/preferences.shared.ts,lib/api/push.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)/dashboard/page.tsx Outdated
Comment on lines +122 to +123
getRecurringPayables(user.id).catch(() => []),
getUnreadNotificationCount().catch(() => 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
getRecurringPayables().catch(() => []) 与 getUnreadNotificationCount().catch(() => 0) 静默吞掉错误:固定支出加载失败时,「今天需还款/当日待还」会基于空数组展示不完整金额,且界面无任何降级提示,财务数据失真且难以排查。建议至少记录错误日志,并为固定支出加载失败补充降级提示(如部分加载 toast/横幅)。

Suggestion:

Suggested change
getRecurringPayables(user.id).catch(() => []),
getUnreadNotificationCount().catch(() => 0),
getRecurringPayables(user.id).catch((err) => {
console.error("Failed to load recurring payables:", err);
return [];
}),
getUnreadNotificationCount().catch((err) => {
console.error("Failed to load unread notification count:", err);
return 0;
}),

Comment on lines +217 to +219
const handlePayPayable = async (e: React.MouseEvent, payable: PayableWithStatus) => {
e.stopPropagation();
try {

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 无防重复提交保护:未设置 loading/disabled 状态,请求发出前也没有进行中的守卫。用户快速连点「标记已付」会并发多次调用 payRecurringPayable,同一期固定支出可能被重复登记付款。建议参照 handlePayAllOverdue 已有的 setPaying 守卫模式(或按 payable.id 粒度)增加互斥,并确认后端对重复付款是否有幂等保护。

Suggestion:

Suggested change
const handlePayPayable = async (e: React.MouseEvent, payable: PayableWithStatus) => {
e.stopPropagation();
try {
const handlePayPayable = async (e: React.MouseEvent, payable: PayableWithStatus) => {
e.stopPropagation();
if (payingPayableId) return; // 防重复提交,与 handlePayAllOverdue 的 paying 守卫保持一致
setPayingPayableId(payable.id);
try {

Comment thread app/(mobile)/dashboard/page.tsx Outdated
Comment on lines +220 to +222
const remaining = Math.max(0, Number(payable.amount) - Number(payable.paid_amount));
if (remaining <= 0) return;
await payRecurringPayable(payable.id, remaining);

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
剩余金额计算缺少 || 0 兜底:若 paid_amount 为 undefined/null,Number() 返回 NaN,而 NaN <= 0 为 false,提前返回守卫失效,会把 NaN 作为付款金额传给 payRecurringPayable。这是资金操作路径,NaN 一旦落库即为异常付款金额。DashboardView.tsx 与 dashboard-metrics.ts 中同公式均带 || 0 兜底,此处应保持一致。

Suggestion:

Suggested change
const remaining = Math.max(0, Number(payable.amount) - Number(payable.paid_amount));
if (remaining <= 0) return;
await payRecurringPayable(payable.id, remaining);
const remaining = Math.max(0, (Number(payable.amount) || 0) - (Number(payable.paid_amount) || 0));
if (remaining <= 0) return;
await payRecurringPayable(payable.id, remaining);

Comment thread app/(mobile)/settings/page.tsx Outdated
Comment on lines +135 to +137
.catch(() => {
if (!cancelled) setUnreadNotifications(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 · low
未读角标请求失败时静默置 0,网络异常/鉴权失败会向用户展示"全部已读"的误导性状态;且初始值即为 0,加载完成前同样显示"全部已读"。另外仅在挂载时拉取一次,从通知中心标记已读后返回设置页角标不会刷新。建议用 number | null 三态区分"未加载/失败"与"确实为 0"(null 时隐藏角标),并可在页面重新可见(visibilitychange/focus)时重新拉取。

Suggestion:

Suggested change
.catch(() => {
if (!cancelled) setUnreadNotifications(0)
})
const [unreadNotifications, setUnreadNotifications] = useState<number | null>(null)
...
.catch(() => {
if (!cancelled) setUnreadNotifications(null)
})
// 渲染时:unreadNotifications === null 则不渲染角标,> 0 显示未读数,=== 0 显示"全部已读"

Comment thread app/api/push/test/route.ts Outdated
Comment on lines +68 to +72
if (sent > 0) {
const ts = new Date().toISOString()
await db
.prepare(
`INSERT INTO notification_history

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 写入失败(例如迁移 0033 尚未生效导致缺列,或瞬时 DB 错误),整个 POST 会以 500 失败,而此时推送实际已成功发送——前端无法区分「通道可用但落库失败」与「推送失败」,测试结论被误导。测试推送的历史记录属非关键数据,建议 try/catch 降级:落库失败仅记录日志或在响应中附加警告,不影响推送结果的返回。

Suggestion:

Suggested change
if (sent > 0) {
const ts = new Date().toISOString()
await db
.prepare(
`INSERT INTO notification_history
if (sent > 0) {
const ts = new Date().toISOString()
try {
await db.prepare(/* … */).bind(/* … */).run()
} catch (err) {
console.warn('[push/test] notification_history insert failed:', err)
}
}

Comment thread worker/cron.ts Outdated
Comment on lines 238 to 243
await db
.prepare(
"INSERT INTO notification_history (id, user_id, notification_key, title, body, status, error) VALUES (?, ?, ?, ?, ?, ?, ?)",
`INSERT INTO notification_history
(id, user_id, notification_key, category, title, body, target_url, metadata_json, sent_at, status, push_sent_at, error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)

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
首次推送落库使用裸 INSERT,而同表其他写入方(lib/api/notifications.server.ts 读取侧幂等补齐、本文件免打扰分支、opportunity-cron.ts 4.5 步)统一使用 INSERT OR IGNORE。上面 SELECT 去重与这条 INSERT 之间存在并发窗口:若用户此刻打开通知中心,读取侧 ensureDailyNotificationsForUser 会先对同 (user_id, notification_key) 插入 'skipped' 行,此处 INSERT 将撞 UNIQUE 约束直接抛错;叠加本文件缺乏按用户错误隔离,一次竞态即可中断全天扫描。建议改为 ON CONFLICT DO UPDATE(与已有 existing 行的 UPDATE 分支保持同一语义),或至少 INSERT OR IGNORE。

Suggestion:

Suggested change
await db
.prepare(
"INSERT INTO notification_history (id, user_id, notification_key, title, body, status, error) VALUES (?, ?, ?, ?, ?, ?, ?)",
`INSERT INTO notification_history
(id, user_id, notification_key, category, title, body, target_url, metadata_json, sent_at, status, push_sent_at, error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
await db
.prepare(
`INSERT INTO notification_history
(id, user_id, notification_key, category, title, body, target_url, metadata_json, sent_at, status, push_sent_at, error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(user_id, notification_key) DO UPDATE SET
status = excluded.status, push_sent_at = excluded.push_sent_at, error = excluded.error`,
)

Comment thread worker/opportunity-cron.ts Outdated
Comment on lines +232 to +236
const channels = legacy.enabled_channels as string[] | undefined
const webPushGloballyEnabled =
channels !== undefined
? Array.isArray(channels) && channels.includes('web_push')
: config.web_push_enabled !== false

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
这里内联重复实现了 worker/cron.ts 中 isUserWebPushEnabled 的存量兼容规则(enabled_channels 优先,未设置时回退 opportunities.web_push_enabled),而 cron.ts 已把该规则注释为「统一存量兼容口径与迁移判断」。账单通知与权益通知的 Web Push 开关判定现在各有一份实现,后续规则演进(如新增渠道键、调整回退顺序)只要一处漏改,两个 cron 的判定口径就会互相矛盾。建议将判定函数下沉到 lib/notifications.shared.ts,两侧共用。

Suggestion:

Suggested change
const channels = legacy.enabled_channels as string[] | undefined
const webPushGloballyEnabled =
channels !== undefined
? Array.isArray(channels) && channels.includes('web_push')
: config.web_push_enabled !== false
// 统一口径:与 worker/cron.ts isUserWebPushEnabled 同源,见 lib/notifications.shared.ts
const webPushGloballyEnabled = isWebPushChannelEnabled(raw)

Comment thread worker/opportunity-cron.ts Outdated
Comment on lines +267 to +268
if (deliveryKey.includes(':reset:') || deliveryKey.startsWith('op:reset:')) return 'opportunity_reset'
if (deliveryKey.includes('claim')) return 'opportunity_claim'

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
notificationCategoryForDeliveryKey 通过对整个 delivery_key 做子串匹配反推分类,而 delivery_key 的构成为 op:<type>:<object_id>:<cycle_or_grant_key>:<hash>:<step>(见 lib/opportunities/reminders.ts §10.1)。object_id / cycle_or_grant_key 是业务自由串,一旦其中含 'claim'、'task'、'booking'、'reward' 等词根(如 booking 事件的 object_id 含 'claim'),分类会被靠前的 includes 分支错挂,进而影响收件箱按分类的过滤/统计维度。event_key 的第二段 <type> 才是事件类型的权威来源,建议改为解析 event_key 的 type 段做精确映射,并与 opportunitySwitchKeyForEvent 的映射保持同构。

Suggestion:

Suggested change
if (deliveryKey.includes(':reset:') || deliveryKey.startsWith('op:reset:')) return 'opportunity_reset'
if (deliveryKey.includes('claim')) return 'opportunity_claim'
// event_key = op:<type>:<object_id>:<cycle_or_grant_key>:<hash>,type 段才是权威来源
const eventType = deliveryKey.split(':')[1] ?? ''
if (eventType === 'reset' || deliveryKey.startsWith('op:reset:')) return 'opportunity_reset'
if (eventType === 'claim_window_open' || eventType === 'claim_window_deadline') return 'opportunity_claim'

Comment thread worker/opportunity-cron.ts Outdated
Comment on lines +491 to +497
await db
.prepare(
`UPDATE opportunity_notification_jobs SET status = 'skipped', last_error = 'web_push_disabled', updated_at = ? WHERE id = ?`,
)
.bind(nowIso, job.id)
.run()
report.skipped_no_subscription += 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.

maintainability · low
「用户主动关闭 Web Push」跳过场景复用了 skipped_no_subscription 计数器,指标语义失真:运营侧会把偏好关闭误读为「无订阅」。last_error 字段区分了原因('web_push_disabled'),但 ScanReport 汇总没有对应区分。建议为 ScanReport 增加 skipped_web_push_disabled 字段单独计数,或在注释中明确该计数器的混合口径。

Suggestion:

Suggested change
await db
.prepare(
`UPDATE opportunity_notification_jobs SET status = 'skipped', last_error = 'web_push_disabled', updated_at = ? WHERE id = ?`,
)
.bind(nowIso, job.id)
.run()
report.skipped_no_subscription += 1
// …同上 UPDATE…
report.skipped_web_push_disabled += 1

Comment thread worker/opportunity-cron.ts Outdated
Comment on lines +588 to +592
`UPDATE notification_history
SET status = ?, push_sent_at = COALESCE(push_sent_at, ?)
WHERE user_id = ? AND notification_key = ?`,
)
.bind(status === 'sent' ? 'sent' : 'skipped', nowIso, job.user_id, inboxKey)

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
回写 notification_history 存在两个问题:1) status === 'sent' ? 'sent' : 'skipped' 将 'partial'(部分设备成功)折叠为 'skipped',站内收件箱状态失真——用户实际已收到推送却被标记为未推送;2) UPDATE 仅按 (user_id, notification_key) 匹配,未排除 deleted_at IS NULL,当用户已软删该通知而 job 因 'partial' 重试时,会篡改已删除行的 status/push_sent_at,违背 cron.ts 中「已删除绝不复活或篡改」的既定语义。建议 WHERE 增加 AND deleted_at IS NULL,并对 partial 状态给出可辨识的处理(至少不应把已投递记录标为 'skipped')。

Suggestion:

Suggested change
`UPDATE notification_history
SET status = ?, push_sent_at = COALESCE(push_sent_at, ?)
WHERE user_id = ? AND notification_key = ?`,
)
.bind(status === 'sent' ? 'sent' : 'skipped', nowIso, job.user_id, inboxKey)
`UPDATE notification_history
SET status = ?, push_sent_at = COALESCE(push_sent_at, ?)
WHERE user_id = ? AND notification_key = ? AND deleted_at IS NULL`,
)
.bind(status === 'sent' ? 'sent' : 'skipped', nowIso, job.user_id, inboxKey)

@hubo1989

Copy link
Copy Markdown
Owner Author

已于提交 fc9e3f4 完成首轮 Codex Review(#1–#8)与 OpenCodeReview 已确认问题的逐项修复并补充回归测试:

主要修复清单

  1. 偏好继承与通道开关一致性(Engine / Cron)
  2. 日期边界与数据访问(Engine / RPC / Test Push / SW)
  3. Web 端(概览 / 设置 / 通知中心)
  4. iOS 原生端(AppState / PushNotificationManager / Views)
    • updateReminderPreferences 按序串行化提交并基于 lastConfirmedReminderPreferences 与版本号安全回滚;两处会话清理路径同步复位通知分页与待跳转状态。
    • 通知中心补充 limit = 50 + "加载更多" 分页,详情页补充 "前往查看" 站内路由;PushNotificationManager 实现 didReceive 点击回调经 handleNotificationRoute 安全跳转对应 Tab / 详情或 WebView 目的地。

明确拒绝(刻意保留原设计)

本次验证结果

  • npm run typecheck:0 errors
  • npm run lint:0 warnings / 0 errors
  • npm test:103 files passed,1163 passed | 1 skipped (1164)(1 条既有 skip 在 cmb-statement-phase3.test.ts)
  • npx vinext build:exit 0
  • bash design/openpencil/verify-batch.sh --source-only:PASS
  • cd ios/Packages/WorldCreditCore && swift test:184 tests in 25 suites passed
  • xcodebuild -project ios/WorldCredit.xcodeproj -scheme WorldCredit -destination 'generic/platform=iOS Simulator' ... build:** BUILD SUCCEEDED **

Comment thread app/(mobile)/dashboard/page.tsx Outdated
Comment on lines +237 to +243
await payRecurringPayable(payable.id, remaining);
setToast({
open: true,
message: `🎉 已登记 ${payable.name} 本期付款(${formatMoney(remaining, payable.currency || displayCurrency)})!`,
severity: "success",
});
await loadData();

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() 全量刷新会重新触发整页 loading 造成页面闪烁;且 loadData 内固定支出加载失败分支会再次弹出「固定支出加载失败」toast,连续登记多笔付款时若刷新失败会重复提示同一信息。建议改为局部刷新 payables 列表,或对同类 toast 做去重/节流。

Comment on lines +84 to +86
push_sent_at = excluded.push_sent_at,
read_at = NULL,
deleted_at = 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
ON CONFLICT 分支将 read_at / deleted_at 置空,会复活用户已读或已删除的同日测试通知,与 worker/cron.ts(“已删除/已读/已推送绝不复活”)和 worker/opportunity-cron.ts(deleted_at IS NULL 守卫)对 notification_history 执行的软删除/已读不变量相反。由于测试推送由用户在设置页显式重触发,复活大概率是有意设计,但此处缺少意图说明,后续维护者容易把该模式照搬到自动通知写入路径造成真问题。建议补充注释说明这是测试场景的特例,或与其他写入路径统一守卫语义。

Suggestion:

Suggested change
push_sent_at = excluded.push_sent_at,
read_at = NULL,
deleted_at = NULL`
push_sent_at = excluded.push_sent_at,
-- 测试推送由用户显式重触发:有意复活同日记录,
-- 与 cron 写入路径“已读/已删除绝不复活”不变量不同,勿照搬到自动通知
read_at = NULL,
deleted_at = NULL`

Comment thread lib/api/bills.server.ts Outdated
Comment on lines +126 to +127
const effectiveDueDate = row.due_date_override ?? row.due_date;
const effectiveStatementDate = row.statement_date_override ?? row.statement_date;

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
BillJoinRow 新增的 due_date_override/statement_date_override/min_payment_override 三个字段需与底层 join 查询的 SELECT 列同步更新,但本 diff 未包含查询构造的变更;若 SQL 未补充选择这三列,row 中对应键恒为 undefined(Record<string, unknown> 绕过了类型检查),用户手填的到期日/账单日将被静默忽略,直接影响当日待还金额与还款决策。另外 due_date 用 ?? 兜底时空字符串 "" 会穿透为生效值,建议与 bill_amount 的 != null 精确判空口径保持一致。

Comment thread lib/api/bills.server.ts Outdated
bill_amount_override: row.bill_amount_override != null ? row.bill_amount_override : undefined,
min_payment: row.min_payment || undefined,
due_date: row.due_date,
min_payment: effectiveMinPayment || 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.

bug · medium
effectiveMinPayment 已通过 override != null 精确判空得到,但此处再用 || undefined 会把手填的 0(表示无最低还款)归一化为 undefined,丢失用户手填值,与上方 bill_amount 的口径相悖。建议改用 ?? undefined 仅在 null/undefined 时兜底。

Suggestion:

Suggested change
min_payment: effectiveMinPayment || undefined,
min_payment: effectiveMinPayment ?? undefined,

Comment thread lib/api/bills.server.ts
};
const paidAmount = payments.reduce((sum, p) => sum + Number(p.amount || 0), 0);
const amount = effectiveBillAmount(bill);
const days = diffInCalendarDays(effectiveDueDate);

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
本地 daysUntil 已删除并改用 diffInCalendarDays,但 diff 中未见新增对应 import;若该函数此前未在本文件定义或导入,服务端账单查询路径将构建失败或运行时抛 ReferenceError,导致整个仪表盘账单加载崩溃,请确认导入已补齐。另需核对时区口径:旧实现按本地时区取 0 点(setHours(0,0,0,0))后按毫秒差计算,若 diffInCalendarDays 采用 UTC 或其他时区基准,days_until_due 会整体偏移一天,直接影响「今天需还款」判定与免息天数展示。

Comment thread worker/cron.ts
Comment on lines +75 to +78
const nowDate =
_event && typeof _event.scheduledTime === "number" && Number.isFinite(_event.scheduledTime)
? new Date(_event.scheduledTime)
: new Date();

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
参数 _event 在本次变更中已被实际读取(scheduledTime),而下划线前缀的惯例是标记“有意不使用的参数”,命名与实际用途矛盾,建议连同 handleScheduled 签名一起改名为 scheduledEvent(_ctx 保持未用可不动)。

Suggestion:

Suggested change
const nowDate =
_event && typeof _event.scheduledTime === "number" && Number.isFinite(_event.scheduledTime)
? new Date(_event.scheduledTime)
: new Date();
const nowDate =
scheduledEvent &&
typeof scheduledEvent.scheduledTime === "number" &&
Number.isFinite(scheduledEvent.scheduledTime)
? new Date(scheduledEvent.scheduledTime)
: new Date();

Comment thread worker/cron.ts Outdated
Comment on lines +119 to +120
const { context, candidates } = await buildDailyNotificationCandidates(db, userId, today);
if (!candidates.length) continue;

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
重构后对 users UNION user_preferences UNION notification_preferences 的全量用户逐个串行执行:loadUserNotificationContext(2 次查询)+ buildDailyNotificationCandidates(3~5 次查询)+ loadExistingHistoryByKey(1+ 次查询),即使无订阅、无账单、无偏好的用户也产生 ~6-8 次 D1 查询;旧实现是循环前 6 次批量查询 + 内存过滤。用户规模增长时 cron 的 D1 查询量与行读取费用按用户数线性膨胀,存在执行时长与费用风险。建议:将 loadUserNotificationContext 内的 user_preferences / notification_preferences 两条查询提升为循环前的两次批量查询(与旧实现一致),通过参数传入单用户上下文构建,可立即将每用户查询数减少一半;有条件的话再对账单/固定支出做批量预取。

Suggestion:

Suggested change
const { context, candidates } = await buildDailyNotificationCandidates(db, userId, today);
if (!candidates.length) continue;
const { context, candidates } = await buildDailyNotificationCandidates(
db,
userId,
today,
prefetchedPrefsByUser.get(userId),
);
if (!candidates.length) continue;

Comment thread worker/cron.ts Outdated
Comment on lines +269 to +270
if (deliveredAny) sentCount++;
else inboxCount++;

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
此处的 inboxCount++ 无条件累加,与上方 skipped 分支(第 165 行 Number(insertRes.meta?.changes ?? 0) > 0 才计数)的口径不一致:当 upsert 的 WHERE 守卫(read_at / deleted_at / push_sent_at 在预读与写入之间并发变化)拒绝更新、changes 为 0 时仍被计入站内信数,日志统计偏大。建议捕获 run() 结果并同样校验 meta.changes,保持两处计数口径一致。

Suggestion:

Suggested change
if (deliveredAny) sentCount++;
else inboxCount++;
const changed = Number(upsertRes.meta?.changes ?? 0) > 0;
if (deliveredAny) sentCount++;
else if (changed) inboxCount++;

Comment thread worker/opportunity-cron.ts Outdated
Comment on lines +475 to +481
if (
userWorld &&
(!userWorld.config.enabled ||
!isOpportunitySwitchEnabled(userWorld.rawConfig, inboxCategory) ||
(inboxCategory === 'opportunity_reset' && !userWorld.config.reset_enabled) ||
(inboxCategory === 'opportunity_booking' && !userWorld.config.booking_enabled))
) {

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
领取阶段的开关门槛与扫描期 buildDueDeliveries(第 303-307 行 isOpportunitySwitchEnabled + reset_enabled/booking_enabled)逻辑重复,且事件→开关键的推导存在两条并行路径:opportunitySwitchKeyForEvent 按事件 kind、notificationCategoryForDeliveryKey 按 delivery_key 字符串 split 解析。新增事件类型时需要同步维护 kind 映射、delivery-key 映射和此处的内联门槛共三处,极易漂移(例如 kind 与 delivery key 第 2 段命名已不一致:cycle_expiry 事件在 key 中是 'expiry')。建议提取统一的『事件/投递键 → 开关键 → 门槛校验』帮助函数供两条路径复用。

Suggestion:

Suggested change
if (
userWorld &&
(!userWorld.config.enabled ||
!isOpportunitySwitchEnabled(userWorld.rawConfig, inboxCategory) ||
(inboxCategory === 'opportunity_reset' && !userWorld.config.reset_enabled) ||
(inboxCategory === 'opportunity_booking' && !userWorld.config.booking_enabled))
) {
function isOpportunityInboxEnabled(userWorld: UserWorld, switchKey: OpportunitySwitchKey): boolean {
return (
Boolean(userWorld.config.enabled) &&
isOpportunitySwitchEnabled(userWorld.rawConfig, switchKey) &&
!(switchKey === 'opportunity_reset' && !userWorld.config.reset_enabled) &&
!(switchKey === 'opportunity_booking' && !userWorld.config.booking_enabled)
)
}
// 扫描期与领取期均调用:isOpportunityInboxEnabled(user, opportunitySwitchKeyForEvent(...))

Comment thread worker/opportunity-cron.ts Outdated
Comment on lines +617 to +619
`UPDATE notification_history
SET status = ?, push_sent_at = COALESCE(push_sent_at, ?), error = ?
WHERE user_id = ? AND notification_key = ? AND deleted_at IS 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
WHERE 仅守卫 deleted_at,未与 worker/cron.ts 的 upsert 一样同时守卫 read_at / push_sent_at:用户已读的站内信条目仍会被覆写 status 与 error(重复 claim 或部分失败转成功时)。COALESCE 保护了 push_sent_at,但整体与 cron.ts『已读/已推送绝不改写』的不变量口径不一致,容易在后续维护中被误当作可任意更新的记录。建议补齐 read_at IS NULL 等守卫以统一语义。

Suggestion:

Suggested change
`UPDATE notification_history
SET status = ?, push_sent_at = COALESCE(push_sent_at, ?), error = ?
WHERE user_id = ? AND notification_key = ? AND deleted_at IS NULL`,
`UPDATE notification_history
SET status = ?, push_sent_at = COALESCE(push_sent_at, ?), error = ?
WHERE user_id = ? AND notification_key = ?
AND deleted_at IS NULL AND read_at IS NULL`,

@hubo1989

Copy link
Copy Markdown
Owner Author

已于提交 ea75f83 完成第二轮 OpenCodeReview 反馈核查与修复,并补充回归测试:

已修复项

  1. public/sw.js 路径穿越防护(security · medium):使用 new URL(raw, self.location.origin).pathname 对目标 URL 做归一化后再校验前缀与精确白名单,阻断 /bills/../settings 等遍历路径。
  2. lib/api/bills.server.ts 覆盖值处理(bug · medium):min_payment 改用 effectiveMinPayment ?? undefined,避免用户显式覆盖最低还款为 0 时丢失;effectiveDueDate / effectiveStatementDate 改用 || 忽略空字符串覆盖。
  3. lib/api/notifications.server.ts 原子批处理 + dashboard/page.tsx 静默局部刷新:softMutateNotifications 使用 db.batch() 同批次完成状态更新与 unread_count 查询;概览页首载同步当日未读后,handlePayPayable / QuickActionSheet 回调支持 loadData({ silent: true }) 静默刷新且不再重复触发全量 syncToday 与固定支出重复错误 toast。
  4. lib/notifications-engine.server.ts & lib/notifications.shared.ts 时区对齐与函数复用:提取公共 formatMoneySingle;buildDailyNotificationCandidates 在读取用户偏好后以 getLocalTodayString(context.timeZone, options?.now) 计算当日日界,统一免打扰与日期口径。
  5. worker/cron.ts & worker/opportunity-cron.ts:handleScheduled 将 _event 改名为 scheduledEvent、在用户循环前并发预取 user_preferences / notification_preferences、并以 upsertRes.meta?.changes 严格门控 inboxCount++;worker/opportunity-cron.ts 抽取共用 isOpportunityInboxEnabled 并在第 7 步写回补齐 AND read_at IS NULL。
  6. lib/dashboard-metrics.ts & app/api/push/test/route.ts:补充 SETTLED_AMOUNT_EPSILON(0.01)与测试推送显式重触发复活机制说明注释。

核实为误报(无需修改)

  • lib/api/bills.server.ts:197(缺少 diffInCalendarDays 导入):diffInCalendarDays 已在本文件第 14 行明确导入,typecheck / vitest / vinext build 均通过。
  • lib/api/bills.server.ts:127(SQL 未查 due_date_override 等列):getRecentBills 与 getBillDashboardItems 均使用 SELECT b.*,覆盖列已完整返回。

本次验证结果

  • npm run typecheck:0 errors
  • npm run lint:0 warnings / 0 errors
  • npm test:全量测试通过(含时区与 min_payment_override = 0 新回归用例)
  • npx vinext build:exit 0
  • bash design/openpencil/verify-batch.sh --source-only:PASS

Comment on lines +140 to +144
getUnreadNotificationCount(shouldSyncUnread)
.then((count) => {
if (shouldSyncUnread) unreadSyncedRef.current = true;
return 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.

performance · medium
首载 getUnreadNotificationCount(shouldSyncUnread=true) 会触发服务端 ensureDailyNotificationsForUser → buildDailyNotificationCandidates(账单/固定支出/卡片/免息期/权益多表重查询),且嵌在首屏 Promise.all 关键路径上,可能拖慢首屏;而 NotificationCenterView 持有独立的 syncedTodayRef,用户随后打开通知中心会再次完整执行同一同步(INSERT OR IGNORE 幂等,但候选构建成本翻倍)。服务端 cron 已负责每日生成通知,建议仪表盘改为 syncToday=false,把同步职责留给通知中心首载或 cron。另注意 unreadSyncedRef 置 true 后永不重置,应用驻留跨天时客户端不再触发当日同步(有 cron 兜底,影响较小)。

Suggestion:

Suggested change
getUnreadNotificationCount(shouldSyncUnread)
.then((count) => {
if (shouldSyncUnread) unreadSyncedRef.current = true;
return count;
})
// 仅拉取未读数;当日通知生成交给服务端 cron / 通知中心首载,
// 避免重量级同步阻塞首屏关键路径
getUnreadNotificationCount(false)
.then((count) => {
return count;
})

Comment on lines 162 to 166
} finally {
setLoading(false);
if (!silent) {
setLoading(false);
}
}

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
silent 模式下 catch 分支仍无条件 setError:handlePayPayable 付款成功后执行 loadData({ silent: true }),一旦静默刷新失败,界面会同时出现「🎉 已登记付款」成功 toast 和整页「加载失败,请下拉重试」错误横幅,误导用户以为付款失败。建议 silent 失败时仅 console.warn,不打扰已成功的操作反馈。

Suggestion:

Suggested change
} finally {
setLoading(false);
if (!silent) {
setLoading(false);
}
}
} catch (err) {
console.error("Dashboard load failed:", err);
// 静默刷新(如付款后同步)失败不打扰已成功的操作反馈
if (!silent) {
setError(err instanceof Error ? err.message : "加载失败,请下拉重试");
}
} finally {
if (!silent) {
setLoading(false);
}
}

Comment on lines 327 to 330
const metrics = useMemo(
() => computeMetrics(visibleBills, futureRange, displayCurrency, fxRates),
[visibleBills, futureRange, displayCurrency, fxRates],
() => computeMetrics(visibleBills, futureRange, displayCurrency, fxRates, visiblePayables),
[visibleBills, futureRange, displayCurrency, fxRates, visiblePayables],
);

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
逾期固定支出在仪表盘上完全不可见:computeMetrics 的「含逾期」只统计账单(overdueBills),而 getDueTodayPayables 只取 days_until_due === 0 的固定支出,days_until_due < 0(status='overdue')的固定支出既进不了「含逾期」也进不了「当日待还」。而通知引擎(bill_overdue 开关描述为「账单或固定支出已过到期日仍未结清时每日提醒」)会持续为逾期固定支出生成提醒,形成通知中心有提醒、仪表盘看不到的对立。用户被提醒后回到首页却找不到对应条目。建议让 metrics 口径把逾期固定支出纳入 overdueAmount/逾期明细,或在「今天需还款」中同时列出 status==='overdue' 的固定支出。

Suggestion:

Suggested change
const metrics = useMemo(
() => computeMetrics(visibleBills, futureRange, displayCurrency, fxRates),
[visibleBills, futureRange, displayCurrency, fxRates],
() => computeMetrics(visibleBills, futureRange, displayCurrency, fxRates, visiblePayables),
[visibleBills, futureRange, displayCurrency, fxRates, visiblePayables],
);
// 口径备注:computeMetrics 目前仅将 days_until_due === 0 的固定支出计入当日待还,
// 逾期(status='overdue')固定支出不进 overdueAmount/当日待还,需与通知引擎口径对齐。
const metrics = useMemo(
() => computeMetrics(visibleBills, futureRange, displayCurrency, fxRates, visiblePayables),
[visibleBills, futureRange, displayCurrency, fxRates, visiblePayables],
);

Comment on lines +150 to +151
window.addEventListener('focus', onFocus)
document.addEventListener('visibilitychange', onVisibility)

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
同时监听 window focus 与 document visibilitychange:Tab 切回时两个事件通常先后触发 refreshUnreadCount,产生重复网络请求且无任何节流。visibilitychange(配合 visibilityState === 'visible' 判断)已完整覆盖 focus 场景,建议只保留 visibilitychange,或增加时间戳节流。

Suggestion:

Suggested change
window.addEventListener('focus', onFocus)
document.addEventListener('visibilitychange', onVisibility)
// visibilitychange 已覆盖切回场景,避免与 focus 重复触发请求
document.addEventListener('visibilitychange', onVisibility)

const switchCounts = countEnabledNotificationItems(reminderConfig)
const billDaysLabel = billDays.length > 0 ? `提前${billDays.join('/')}天` : '未设提醒'
const reminderSummary = `${billDaysLabel} · 权益${oppEnabled ? '开' : '关'}`
const reminderSummary = `${billDaysLabel} · ${switchCounts.enabled}/${switchCounts.total}项开`

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
权益总开关关闭时摘要计数口径自相矛盾:countEnabledNotificationItems 在 opportunities.enabled === false 时把 6 项权益分项开关从 enabled 中剔除,但 total 恒为 12,徽标会显示「6/12项开」——这 6 项并非被单独关闭,只是随父级开关隐藏,分项开关本身可能全为开。用户会误以为有 6 个通知项被单独关掉了。建议总开关关闭时展示「权益已关」文案,或让 total 动态只统计当前生效分支(如 6/6)。

Suggestion:

Suggested change
const reminderSummary = `${billDaysLabel} · ${switchCounts.enabled}/${switchCounts.total}项开`
const oppGlobalOn = reminderConfig?.opportunities?.enabled !== false
const reminderSummary = oppGlobalOn
? `${billDaysLabel} · ${switchCounts.enabled}/${switchCounts.total}项开`
: `${billDaysLabel} · 权益已关 · ${switchCounts.enabled}/${switchCounts.total}项开`

Comment on lines +107 to +113
export async function getUnreadNotificationCount(userId: string, syncToday = true): Promise<number> {
const db = getDb()
if (syncToday !== false) {
await ensureDailyNotificationsForUser(db, userId)
}
return countUnreadForUser(db, userId)
}

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
getUnreadNotificationCount 默认 syncToday=true,使最轻量的「未读角标」请求每次都执行整套候选生成(bills 全量扫描含逐账单 payments 子查询、固定支出聚合、免息期卡查询)并尝试批量写库。Web 侧调用方均已显式传参(dashboard 首载显式传 true、settings/加载更多传 false),真正依赖隐式默认值的是 iOS 端 fetchUnreadCount(不传该参数)——即每次角标刷新(登录首载、下拉刷新、跨日刷新、还款后)都会触发重查询。建议默认值改为 false(纯计数),需要补齐当日通知的调用方显式传 true,让最高频路径走轻量查询;角标新鲜度由每日 cron 与通知中心打开时的同步兜底。

Suggestion:

Suggested change
export async function getUnreadNotificationCount(userId: string, syncToday = true): Promise<number> {
const db = getDb()
if (syncToday !== false) {
await ensureDailyNotificationsForUser(db, userId)
}
return countUnreadForUser(db, userId)
}
// 默认纯计数,不做当日通知补齐;需要同步的调用方(如 dashboard 首载)显式传 true。
export async function getUnreadNotificationCount(userId: string, syncToday = false): Promise<number> {
const db = getDb()
if (syncToday) {
await ensureDailyNotificationsForUser(db, userId)
}
return countUnreadForUser(db, userId)
}

Comment on lines +121 to +128
const [res, countRes] = await db.batch([
db.prepare(sql).bind(...bindings),
db
.prepare(
'SELECT COUNT(*) AS cnt FROM notification_history WHERE user_id = ? AND deleted_at IS NULL AND read_at IS NULL'
)
.bind(userId),
])

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
未读计数 SQL 与 countUnreadForUser 中的字符串完全重复,两处需同步维护(如后续口径加入时间过滤就会漏改),建议提取为共享常量或让 softMutateNotifications 复用同一模板。另外 COALESCE 幂等写法下,重复标记已读/重复删除时 changes=0,接口返回 updated=false / deleted=false,调用方容易把「幂等成功」误判为「操作失败」(当前 Web/iOS 均未消费该字段,属潜在误用点),建议注释明确语义或改名为 changed。

Suggestion:

Suggested change
const [res, countRes] = await db.batch([
db.prepare(sql).bind(...bindings),
db
.prepare(
'SELECT COUNT(*) AS cnt FROM notification_history WHERE user_id = ? AND deleted_at IS NULL AND read_at IS NULL'
)
.bind(userId),
])
const UNREAD_COUNT_SQL =
'SELECT COUNT(*) AS cnt FROM notification_history WHERE user_id = ? AND deleted_at IS NULL AND read_at IS NULL'
async function countUnreadForUser(db: D1Database, userId: string): Promise<number> {
const row = await db.prepare(UNREAD_COUNT_SQL).bind(userId).first<{ cnt: number }>()
return Number(row?.cnt ?? 0)
}
// ...
const [res, countRes] = await db.batch([
db.prepare(sql).bind(...bindings),
db.prepare(UNREAD_COUNT_SQL).bind(userId),
])

Comment thread lib/api/push.ts
}
return true
}
export { isWebPushChannelEnabled } from '../notifications.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.

maintainability · low
收敛到单一真源后,请确认 notifications.shared 中的新实现与旧口径完全兼容:enabled_channels 显式设置时以其为准(含空数组视为关闭);未显式设置时回落旧 opportunities.web_push_enabled === false 判定。否则存量调用点(cron/worker 等其他改动文件)的推送判定结果会静默漂移。

if (user?.id) {
try {
await updateUserPreferences(user.id, { reminder_config: nextReminder })
await updateUserPreferences(user.id, { reminder_config: updates })

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
行为变更:此处由原先上送完整合并后的 nextReminder 改为仅上送原始 updates(部分更新),由服务端基于其持久化配置做 syncItemSwitchesWithOpportunities 合并;而客户端乐观状态/缓存用的是基于本地 reminderConfig 的合并结果。两侧行为一致的前提是:1) syncItemSwitchesWithOpportunities 对 items 与 opportunities 子树均为深合并,部分字段更新不会整体覆盖丢失其余开关;2) 客户端本地缓存与服务端持久化一致——若缓存过期(如其他设备已改),乐观 UI 与实际落库结果将漂移,且保存成功后不会回读校正。请确认 notifications.shared.ts 中该函数的部分更新语义,并评估保存成功后是否需要回读同步。

Comment on lines +253 to +254
const context = await loadUserNotificationContext(db, userId, options?.prefetched)
const effectiveToday = todayStr ?? getLocalTodayString(context.timeZone, options?.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.

bug · low
到期/逾期判定的日历日基准用 context.timeZone(用户可配置的 opportunities.time_zone),而 bills/payables 列表与仪表盘统一通过 diffInCalendarDays 归一到硬编码的 Asia/Shanghai 业务时区(lib/utils.ts 注明「全站唯一定义」)。当用户配置了非默认时区时,引擎对「今日待还/逾期/提前 N 天」的判定会比页面口径漂移最多一天(如东京时区用户凌晨就会收到「今日待还」,而 dashboard 当日待还列表仍显示为明天)。同时 parseCivilDateUTC/diffCivilDays/civilDateFromTodayStr 与 lib/utils.ts 既有实现重复。建议到期/逾期类判定与 diffInCalendarDays 同口径(复用或让其接受时区参数),仅免打扰时段等推送时机保留用户时区。

Suggestion:

Suggested change
const context = await loadUserNotificationContext(db, userId, options?.prefetched)
const effectiveToday = todayStr ?? getLocalTodayString(context.timeZone, options?.now)
const context = await loadUserNotificationContext(db, userId, options?.prefetched)
// 与 bills/payables 的 days_until_due 同口径(业务时区 Asia/Shanghai),
// 避免 opportunities.time_zone 非默认时通知与页面判定漂移一天;
// 免打扰时段等推送时机仍由 isUserInQuietHours 按用户时区处理。
const effectiveToday = todayStr ?? getLocalTodayString('Asia/Shanghai', options?.now)

@hubo1989
hubo1989 merged commit 8ac0d40 into main Nov 21, 2026
4 checks passed
@hubo1989
hubo1989 deleted the feat/notification-center-due-today branch November 21, 2026 02:06
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