Repository navigation
feat(notifications): 概览当日待还总金额、主动通知增强、通知中心与全通知项开关(Web + iOS) - #56
Conversation
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| if (prefRow?.reminder_config) { | ||
| try { | ||
| const parsed = JSON.parse(prefRow.reminder_config) as Partial<UserReminderConfig> |
There was a problem hiding this comment.
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 👍 / 👎.
| // 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) { |
There was a problem hiding this comment.
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 👍 / 👎.
| const ACTIVITY_DAY_CHOICES = [1, 3, 7, 15] | ||
| const TASK_DAY_CHOICES = [0, 1, 3, 7] |
There was a problem hiding this comment.
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 👍 / 👎.
| private func persist(_ next: UserReminderPreferences) { | ||
| saveError = nil | ||
| Task { | ||
| do { | ||
| try await appState.updateReminderPreferences(next) |
There was a problem hiding this comment.
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 👍 / 👎.
| const res = await getNotifications({ filter: nextFilter, limit: 100, syncToday: true }) | ||
| setItems(res.items) | ||
| setUnreadCount(res.unread_count) | ||
| setTotalCount(res.total_count) |
There was a problem hiding this comment.
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 👍 / 👎.
| Section { | ||
| if item.isUnread { | ||
| Button("标记为已读") { | ||
| Task { | ||
| await performMarkRead(item.id) | ||
| selectedNotification = item.markingRead(at: ISO8601DateFormatter().string(from: Date())) | ||
| } | ||
| } | ||
| } | ||
| Button("删除此通知", role: .destructive) { |
There was a problem hiding this comment.
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 👍 / 👎.
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
| if (daysUntil === 0 && !switches.bill_due_today) continue | ||
| if (daysUntil > 0 && !switches.bill_due_advance) continue |
There was a problem hiding this comment.
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 👍 / 👎.
|
🔍 OpenCodeReview found 18 issue(s) in this PR.
|
| getRecurringPayables(user.id).catch(() => []), | ||
| getUnreadNotificationCount().catch(() => 0), |
There was a problem hiding this comment.
getRecurringPayables().catch(() => []) 与 getUnreadNotificationCount().catch(() => 0) 静默吞掉错误:固定支出加载失败时,「今天需还款/当日待还」会基于空数组展示不完整金额,且界面无任何降级提示,财务数据失真且难以排查。建议至少记录错误日志,并为固定支出加载失败补充降级提示(如部分加载 toast/横幅)。
Suggestion:
| 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; | |
| }), |
| const handlePayPayable = async (e: React.MouseEvent, payable: PayableWithStatus) => { | ||
| e.stopPropagation(); | ||
| try { |
There was a problem hiding this comment.
handlePayPayable 无防重复提交保护:未设置 loading/disabled 状态,请求发出前也没有进行中的守卫。用户快速连点「标记已付」会并发多次调用 payRecurringPayable,同一期固定支出可能被重复登记付款。建议参照 handlePayAllOverdue 已有的 setPaying 守卫模式(或按 payable.id 粒度)增加互斥,并确认后端对重复付款是否有幂等保护。
Suggestion:
| 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 { |
| const remaining = Math.max(0, Number(payable.amount) - Number(payable.paid_amount)); | ||
| if (remaining <= 0) return; | ||
| await payRecurringPayable(payable.id, remaining); |
There was a problem hiding this comment.
剩余金额计算缺少 || 0 兜底:若 paid_amount 为 undefined/null,Number() 返回 NaN,而 NaN <= 0 为 false,提前返回守卫失效,会把 NaN 作为付款金额传给 payRecurringPayable。这是资金操作路径,NaN 一旦落库即为异常付款金额。DashboardView.tsx 与 dashboard-metrics.ts 中同公式均带 || 0 兜底,此处应保持一致。
Suggestion:
| 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); |
| .catch(() => { | ||
| if (!cancelled) setUnreadNotifications(0) | ||
| }) |
There was a problem hiding this comment.
未读角标请求失败时静默置 0,网络异常/鉴权失败会向用户展示"全部已读"的误导性状态;且初始值即为 0,加载完成前同样显示"全部已读"。另外仅在挂载时拉取一次,从通知中心标记已读后返回设置页角标不会刷新。建议用 number | null 三态区分"未加载/失败"与"确实为 0"(null 时隐藏角标),并可在页面重新可见(visibilitychange/focus)时重新拉取。
Suggestion:
| .catch(() => { | |
| if (!cancelled) setUnreadNotifications(0) | |
| }) | |
| const [unreadNotifications, setUnreadNotifications] = useState<number | null>(null) | |
| ... | |
| .catch(() => { | |
| if (!cancelled) setUnreadNotifications(null) | |
| }) | |
| // 渲染时:unreadNotifications === null 则不渲染角标,> 0 显示未读数,=== 0 显示"全部已读" |
| if (sent > 0) { | ||
| const ts = new Date().toISOString() | ||
| await db | ||
| .prepare( | ||
| `INSERT INTO notification_history |
There was a problem hiding this comment.
新增的历史落库缺少错误处理:若这条 D1 写入失败(例如迁移 0033 尚未生效导致缺列,或瞬时 DB 错误),整个 POST 会以 500 失败,而此时推送实际已成功发送——前端无法区分「通道可用但落库失败」与「推送失败」,测试结论被误导。测试推送的历史记录属非关键数据,建议 try/catch 降级:落库失败仅记录日志或在响应中附加警告,不影响推送结果的返回。
Suggestion:
| 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) | |
| } | |
| } |
| 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, | ||
| ) |
There was a problem hiding this comment.
首次推送落库使用裸 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:
| 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`, | |
| ) |
| const channels = legacy.enabled_channels as string[] | undefined | ||
| const webPushGloballyEnabled = | ||
| channels !== undefined | ||
| ? Array.isArray(channels) && channels.includes('web_push') | ||
| : config.web_push_enabled !== false |
There was a problem hiding this comment.
这里内联重复实现了 worker/cron.ts 中 isUserWebPushEnabled 的存量兼容规则(enabled_channels 优先,未设置时回退 opportunities.web_push_enabled),而 cron.ts 已把该规则注释为「统一存量兼容口径与迁移判断」。账单通知与权益通知的 Web Push 开关判定现在各有一份实现,后续规则演进(如新增渠道键、调整回退顺序)只要一处漏改,两个 cron 的判定口径就会互相矛盾。建议将判定函数下沉到 lib/notifications.shared.ts,两侧共用。
Suggestion:
| 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) |
| if (deliveryKey.includes(':reset:') || deliveryKey.startsWith('op:reset:')) return 'opportunity_reset' | ||
| if (deliveryKey.includes('claim')) return 'opportunity_claim' |
There was a problem hiding this comment.
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:
| 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' |
| 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 |
There was a problem hiding this comment.
「用户主动关闭 Web Push」跳过场景复用了 skipped_no_subscription 计数器,指标语义失真:运营侧会把偏好关闭误读为「无订阅」。last_error 字段区分了原因('web_push_disabled'),但 ScanReport 汇总没有对应区分。建议为 ScanReport 增加 skipped_web_push_disabled 字段单独计数,或在注释中明确该计数器的混合口径。
Suggestion:
| 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 |
| `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) |
There was a problem hiding this comment.
回写 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:
| `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) |
|
已于提交 主要修复清单
明确拒绝(刻意保留原设计)
本次验证结果
|
| await payRecurringPayable(payable.id, remaining); | ||
| setToast({ | ||
| open: true, | ||
| message: `🎉 已登记 ${payable.name} 本期付款(${formatMoney(remaining, payable.currency || displayCurrency)})!`, | ||
| severity: "success", | ||
| }); | ||
| await loadData(); |
| push_sent_at = excluded.push_sent_at, | ||
| read_at = NULL, | ||
| deleted_at = NULL` |
There was a problem hiding this comment.
ON CONFLICT 分支将 read_at / deleted_at 置空,会复活用户已读或已删除的同日测试通知,与 worker/cron.ts(“已删除/已读/已推送绝不复活”)和 worker/opportunity-cron.ts(deleted_at IS NULL 守卫)对 notification_history 执行的软删除/已读不变量相反。由于测试推送由用户在设置页显式重触发,复活大概率是有意设计,但此处缺少意图说明,后续维护者容易把该模式照搬到自动通知写入路径造成真问题。建议补充注释说明这是测试场景的特例,或与其他写入路径统一守卫语义。
Suggestion:
| 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` |
| const effectiveDueDate = row.due_date_override ?? row.due_date; | ||
| const effectiveStatementDate = row.statement_date_override ?? row.statement_date; |
There was a problem hiding this comment.
BillJoinRow 新增的 due_date_override/statement_date_override/min_payment_override 三个字段需与底层 join 查询的 SELECT 列同步更新,但本 diff 未包含查询构造的变更;若 SQL 未补充选择这三列,row 中对应键恒为 undefined(Record<string, unknown> 绕过了类型检查),用户手填的到期日/账单日将被静默忽略,直接影响当日待还金额与还款决策。另外 due_date 用 ?? 兜底时空字符串 "" 会穿透为生效值,建议与 bill_amount 的 != null 精确判空口径保持一致。
| 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, |
There was a problem hiding this comment.
| }; | ||
| const paidAmount = payments.reduce((sum, p) => sum + Number(p.amount || 0), 0); | ||
| const amount = effectiveBillAmount(bill); | ||
| const days = diffInCalendarDays(effectiveDueDate); |
There was a problem hiding this comment.
| const nowDate = | ||
| _event && typeof _event.scheduledTime === "number" && Number.isFinite(_event.scheduledTime) | ||
| ? new Date(_event.scheduledTime) | ||
| : new Date(); |
There was a problem hiding this comment.
参数 _event 在本次变更中已被实际读取(scheduledTime),而下划线前缀的惯例是标记“有意不使用的参数”,命名与实际用途矛盾,建议连同 handleScheduled 签名一起改名为 scheduledEvent(_ctx 保持未用可不动)。
Suggestion:
| 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(); |
| const { context, candidates } = await buildDailyNotificationCandidates(db, userId, today); | ||
| if (!candidates.length) continue; |
There was a problem hiding this comment.
重构后对 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:
| 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; |
| if (deliveredAny) sentCount++; | ||
| else inboxCount++; |
There was a problem hiding this comment.
此处的 inboxCount++ 无条件累加,与上方 skipped 分支(第 165 行 Number(insertRes.meta?.changes ?? 0) > 0 才计数)的口径不一致:当 upsert 的 WHERE 守卫(read_at / deleted_at / push_sent_at 在预读与写入之间并发变化)拒绝更新、changes 为 0 时仍被计入站内信数,日志统计偏大。建议捕获 run() 结果并同样校验 meta.changes,保持两处计数口径一致。
Suggestion:
| if (deliveredAny) sentCount++; | |
| else inboxCount++; | |
| const changed = Number(upsertRes.meta?.changes ?? 0) > 0; | |
| if (deliveredAny) sentCount++; | |
| else if (changed) inboxCount++; |
| if ( | ||
| userWorld && | ||
| (!userWorld.config.enabled || | ||
| !isOpportunitySwitchEnabled(userWorld.rawConfig, inboxCategory) || | ||
| (inboxCategory === 'opportunity_reset' && !userWorld.config.reset_enabled) || | ||
| (inboxCategory === 'opportunity_booking' && !userWorld.config.booking_enabled)) | ||
| ) { |
There was a problem hiding this comment.
领取阶段的开关门槛与扫描期 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:
| 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(...)) |
| `UPDATE notification_history | ||
| SET status = ?, push_sent_at = COALESCE(push_sent_at, ?), error = ? | ||
| WHERE user_id = ? AND notification_key = ? AND deleted_at IS NULL`, |
There was a problem hiding this comment.
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:
| `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`, |
…tching, timezone)
|
已于提交 已修复项
核实为误报(无需修改)
本次验证结果
|
| getUnreadNotificationCount(shouldSyncUnread) | ||
| .then((count) => { | ||
| if (shouldSyncUnread) unreadSyncedRef.current = true; | ||
| return count; | ||
| }) |
There was a problem hiding this comment.
首载 getUnreadNotificationCount(shouldSyncUnread=true) 会触发服务端 ensureDailyNotificationsForUser → buildDailyNotificationCandidates(账单/固定支出/卡片/免息期/权益多表重查询),且嵌在首屏 Promise.all 关键路径上,可能拖慢首屏;而 NotificationCenterView 持有独立的 syncedTodayRef,用户随后打开通知中心会再次完整执行同一同步(INSERT OR IGNORE 幂等,但候选构建成本翻倍)。服务端 cron 已负责每日生成通知,建议仪表盘改为 syncToday=false,把同步职责留给通知中心首载或 cron。另注意 unreadSyncedRef 置 true 后永不重置,应用驻留跨天时客户端不再触发当日同步(有 cron 兜底,影响较小)。
Suggestion:
| getUnreadNotificationCount(shouldSyncUnread) | |
| .then((count) => { | |
| if (shouldSyncUnread) unreadSyncedRef.current = true; | |
| return count; | |
| }) | |
| // 仅拉取未读数;当日通知生成交给服务端 cron / 通知中心首载, | |
| // 避免重量级同步阻塞首屏关键路径 | |
| getUnreadNotificationCount(false) | |
| .then((count) => { | |
| return count; | |
| }) |
| } finally { | ||
| setLoading(false); | ||
| if (!silent) { | ||
| setLoading(false); | ||
| } | ||
| } |
There was a problem hiding this comment.
silent 模式下 catch 分支仍无条件 setError:handlePayPayable 付款成功后执行 loadData({ silent: true }),一旦静默刷新失败,界面会同时出现「🎉 已登记付款」成功 toast 和整页「加载失败,请下拉重试」错误横幅,误导用户以为付款失败。建议 silent 失败时仅 console.warn,不打扰已成功的操作反馈。
Suggestion:
| } 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); | |
| } | |
| } |
| const metrics = useMemo( | ||
| () => computeMetrics(visibleBills, futureRange, displayCurrency, fxRates), | ||
| [visibleBills, futureRange, displayCurrency, fxRates], | ||
| () => computeMetrics(visibleBills, futureRange, displayCurrency, fxRates, visiblePayables), | ||
| [visibleBills, futureRange, displayCurrency, fxRates, visiblePayables], | ||
| ); |
There was a problem hiding this comment.
逾期固定支出在仪表盘上完全不可见:computeMetrics 的「含逾期」只统计账单(overdueBills),而 getDueTodayPayables 只取 days_until_due === 0 的固定支出,days_until_due < 0(status='overdue')的固定支出既进不了「含逾期」也进不了「当日待还」。而通知引擎(bill_overdue 开关描述为「账单或固定支出已过到期日仍未结清时每日提醒」)会持续为逾期固定支出生成提醒,形成通知中心有提醒、仪表盘看不到的对立。用户被提醒后回到首页却找不到对应条目。建议让 metrics 口径把逾期固定支出纳入 overdueAmount/逾期明细,或在「今天需还款」中同时列出 status==='overdue' 的固定支出。
Suggestion:
| 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], | |
| ); |
| window.addEventListener('focus', onFocus) | ||
| document.addEventListener('visibilitychange', onVisibility) |
There was a problem hiding this comment.
同时监听 window focus 与 document visibilitychange:Tab 切回时两个事件通常先后触发 refreshUnreadCount,产生重复网络请求且无任何节流。visibilitychange(配合 visibilityState === 'visible' 判断)已完整覆盖 focus 场景,建议只保留 visibilitychange,或增加时间戳节流。
Suggestion:
| 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}项开` |
There was a problem hiding this comment.
权益总开关关闭时摘要计数口径自相矛盾:countEnabledNotificationItems 在 opportunities.enabled === false 时把 6 项权益分项开关从 enabled 中剔除,但 total 恒为 12,徽标会显示「6/12项开」——这 6 项并非被单独关闭,只是随父级开关隐藏,分项开关本身可能全为开。用户会误以为有 6 个通知项被单独关掉了。建议总开关关闭时展示「权益已关」文案,或让 total 动态只统计当前生效分支(如 6/6)。
Suggestion:
| 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}项开` |
| export async function getUnreadNotificationCount(userId: string, syncToday = true): Promise<number> { | ||
| const db = getDb() | ||
| if (syncToday !== false) { | ||
| await ensureDailyNotificationsForUser(db, userId) | ||
| } | ||
| return countUnreadForUser(db, userId) | ||
| } |
There was a problem hiding this comment.
getUnreadNotificationCount 默认 syncToday=true,使最轻量的「未读角标」请求每次都执行整套候选生成(bills 全量扫描含逐账单 payments 子查询、固定支出聚合、免息期卡查询)并尝试批量写库。Web 侧调用方均已显式传参(dashboard 首载显式传 true、settings/加载更多传 false),真正依赖隐式默认值的是 iOS 端 fetchUnreadCount(不传该参数)——即每次角标刷新(登录首载、下拉刷新、跨日刷新、还款后)都会触发重查询。建议默认值改为 false(纯计数),需要补齐当日通知的调用方显式传 true,让最高频路径走轻量查询;角标新鲜度由每日 cron 与通知中心打开时的同步兜底。
Suggestion:
| 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) | |
| } |
| 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), | ||
| ]) |
There was a problem hiding this comment.
未读计数 SQL 与 countUnreadForUser 中的字符串完全重复,两处需同步维护(如后续口径加入时间过滤就会漏改),建议提取为共享常量或让 softMutateNotifications 复用同一模板。另外 COALESCE 幂等写法下,重复标记已读/重复删除时 changes=0,接口返回 updated=false / deleted=false,调用方容易把「幂等成功」误判为「操作失败」(当前 Web/iOS 均未消费该字段,属潜在误用点),建议注释明确语义或改名为 changed。
Suggestion:
| 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), | |
| ]) |
| } | ||
| return true | ||
| } | ||
| export { isWebPushChannelEnabled } from '../notifications.shared' |
| if (user?.id) { | ||
| try { | ||
| await updateUserPreferences(user.id, { reminder_config: nextReminder }) | ||
| await updateUserPreferences(user.id, { reminder_config: updates }) |
There was a problem hiding this comment.
行为变更:此处由原先上送完整合并后的 nextReminder 改为仅上送原始 updates(部分更新),由服务端基于其持久化配置做 syncItemSwitchesWithOpportunities 合并;而客户端乐观状态/缓存用的是基于本地 reminderConfig 的合并结果。两侧行为一致的前提是:1) syncItemSwitchesWithOpportunities 对 items 与 opportunities 子树均为深合并,部分字段更新不会整体覆盖丢失其余开关;2) 客户端本地缓存与服务端持久化一致——若缓存过期(如其他设备已改),乐观 UI 与实际落库结果将漂移,且保存成功后不会回读校正。请确认 notifications.shared.ts 中该函数的部分更新语义,并评估保存成功后是否需要回读同步。
| const context = await loadUserNotificationContext(db, userId, options?.prefetched) | ||
| const effectiveToday = todayStr ?? getLocalTodayString(context.timeZone, options?.now) |
There was a problem hiding this comment.
到期/逾期判定的日历日基准用 context.timeZone(用户可配置的 opportunities.time_zone),而 bills/payables 列表与仪表盘统一通过 diffInCalendarDays 归一到硬编码的 Asia/Shanghai 业务时区(lib/utils.ts 注明「全站唯一定义」)。当用户配置了非默认时区时,引擎对「今日待还/逾期/提前 N 天」的判定会比页面口径漂移最多一天(如东京时区用户凌晨就会收到「今日待还」,而 dashboard 当日待还列表仍显示为明天)。同时 parseCivilDateUTC/diffCivilDays/civilDateFromTodayStr 与 lib/utils.ts 既有实现重复。建议到期/逾期类判定与 diffInCalendarDays 同口径(复用或让其接受时区参数),仅免打扰时段等推送时机保留用户时区。
Suggestion:
| 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) |
变更概览
概览页增加当日待还总金额(Web + iOS)
days_until_due === 0)且未结清的信用卡账单剩余待还 + 当天到期且未结清的固定支出(recurring_payables)剩余金额,跟随持卡人筛选联动,按原币种分组折算至displayCurrency,缺汇率外币记入unconvertedCurrencies(不 1:1 混加)。主动通知增强(当日待还 + 今日新增最长免息期账单)
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单次下发与无订阅仍写入站内通知。通知中心与全通知项独立开关(Web + iOS)
migrations/d1/0033_notification_center.sql(category、target_url、metadata_json、read_at、deleted_at、push_sent_at)。bindUser: 0会话隔离 RPC(getNotifications、getUnreadNotificationCount、markNotificationRead、markAllNotificationsRead、deleteNotification、deleteAllNotifications),采用deleted_at软删除保留(user_id, notification_key)唯一去重,避免当日已删通知复活。/notifications、/settings)与 iOS(NotificationsCenterView、NotificationSettingsView、DashboardView、SettingsView)均支持通知中心全量正文/结构化明细查看、单条/全部已读、单条/全部删除(ObsidianConfirmDialog/ SwiftUIconfirmationDialog二次确认)以及全部 12 项独立开关(存量缺省全开,且opportunity_reset/opportunity_booking与opportunities.reset_enabled/booking_enabled双向同步)。数据与安全说明
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 **