Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 85 additions & 11 deletions app/(mobile)/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import { useEffect, useState, useCallback, useMemo } from "react";
import { useEffect, useState, useCallback, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import {
getBillDashboardItems,
Expand All @@ -10,13 +10,20 @@ import {
} from "@/lib/api/bills";
import { getHolders } from "@/lib/api/holders";
import { getCardsBasicByHolders } from "@/lib/api/cards";
import {
getRecurringPayables,
payRecurringPayable,
type PayableWithStatus,
} from "@/lib/api/payables";
import { getUnreadNotificationCount } from "@/lib/api/notifications";
import {
type HolderFilter,
type FutureRange,
billCurrency,
computeMetrics,
countCardsByHolder,
formatMoney,
payableRemaining,
} from "@/lib/dashboard-metrics";
import { useUserPreferences } from "@/lib/hooks/useUserPreferences";
import { fetchRates, type FxRates } from "@/lib/fx";
Expand Down Expand Up @@ -61,7 +68,10 @@ export default function DashboardPage() {
const [error, setError] = useState<string | null>(null);
const [holders, setHolders] = useState<CardHolder[]>([]);
const [bills, setBills] = useState<BillDashboardItem[]>([]);
const [payables, setPayables] = useState<PayableWithStatus[]>([]);
const [unreadNotificationCount, setUnreadNotificationCount] = useState(0);
const [cards, setCards] = useState<Array<{ id: string; holder_id: string }>>([]);
const unreadSyncedRef = useRef(false);

// ---- 交互状态 ----
const [holderFilter, setHolderFilter] = useState<HolderFilter>("all");
Expand All @@ -88,6 +98,7 @@ export default function DashboardPage() {
// 一键还款与 Toast 状态
const [payAllOpen, setPayAllOpen] = useState(false);
const [paying, setPaying] = useState(false);
const [payingPayableId, setPayingPayableId] = useState<string | null>(null);
const [toast, setToast] = useState<{
open: boolean;
message: string;
Expand All @@ -102,15 +113,39 @@ export default function DashboardPage() {
const blurClass = privacyOn ? "privacy-blur" : "privacy-clear";

// ---- 数据加载 ----
const loadData = useCallback(async () => {
const loadData = useCallback(async (opts?: { silent?: boolean }) => {
if (!user?.id) return;
setLoading(true);
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
}
setError(null);
const shouldSyncUnread = !unreadSyncedRef.current;
try {
// 并行:持卡人 / 账单;卡片依赖持卡人 id,随后批量查询
const [holderList, allBills] = await Promise.all([
// 并行:持卡人 / 账单 / 固定支出 / 未读通知数(仅首载同步当日通知);卡片依赖持卡人 id
const [holderList, allBills, payableList, unreadCount] = await Promise.all([
getHolders(user.id),
getBillDashboardItems(200, user.id),
getRecurringPayables(user.id).catch((err) => {
console.warn("[dashboard] Failed to load recurring payables:", err);
if (!silent) {
setToast({
open: true,
message: "固定支出加载失败,当日待还金额暂不含固定支出",
severity: "info",
});
}
return [];
}),
getUnreadNotificationCount(shouldSyncUnread)
.then((count) => {
if (shouldSyncUnread) unreadSyncedRef.current = true;
return count;
})
Comment on lines +140 to +144

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;
})

.catch((err) => {
console.warn("[dashboard] Failed to load unread notification count:", err);
return 0;
}),
]);
holderList.sort((a, b) => a.created_at.localeCompare(b.created_at));
const holderIds = holderList.map((h) => h.id);
Expand All @@ -119,11 +154,15 @@ export default function DashboardPage() {
setHolders(holderList);
setCards(cardsRes);
setBills(allBills);
setPayables(payableList);
setUnreadNotificationCount(unreadCount);
} catch (err) {
console.error("Dashboard load failed:", err);
setError(err instanceof Error ? err.message : "加载失败,请下拉重试");
} finally {
setLoading(false);
if (!silent) {
setLoading(false);
}
}
Comment on lines 162 to 166

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);
}
}

}, [user?.id]);

Expand Down Expand Up @@ -202,6 +241,31 @@ export default function DashboardPage() {
}
};

const handlePayPayable = async (e: React.MouseEvent, payable: PayableWithStatus) => {
e.stopPropagation();
if (payingPayableId === payable.id) return;
const remaining = payableRemaining(payable);
if (remaining <= 0) return;
setPayingPayableId(payable.id);
try {
Comment on lines +244 to +250

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 {

await payRecurringPayable(payable.id, remaining);
setToast({
open: true,
message: `🎉 已登记 ${payable.name} 本期付款(${formatMoney(remaining, payable.currency || displayCurrency)})!`,
severity: "success",
});
await loadData({ silent: true });
} catch (err) {
setToast({
open: true,
message: "登记付款失败: " + (err instanceof Error ? err.message : String(err)),
severity: "error",
});
} finally {
setPayingPayableId((curr) => (curr === payable.id ? null : curr));
}
};

const handlePayAllOverdue = async () => {
if (!user?.id) return;
setPaying(true);
Expand Down Expand Up @@ -240,22 +304,29 @@ export default function DashboardPage() {
const closeToast = useCallback(() => setToast((prev) => ({ ...prev, open: false })), []);
const goToBills = useCallback(() => router.push("/bills"), [router]);
const goToPromos = useCallback(() => router.push("/promos"), [router]);
const goToNotifications = useCallback(() => router.push("/notifications"), [router]);

// 当前选中持卡人下的账单
const visibleBills = useMemo(() => {
if (holderFilter === "all") return bills;
return bills.filter((b) => b.card?.holder_id === holderFilter);
}, [bills, holderFilter]);

// 当前选中持卡人下的固定支出
const visiblePayables = useMemo(() => {
if (holderFilter === "all") return payables;
return payables.filter((p) => p.holder_id === holderFilter);
}, [payables, holderFilter]);

// 当前选中持卡人下的卡片
const visibleCards = useMemo(() => {
if (holderFilter === "all") return cards;
return cards.filter((c) => c.holder_id === holderFilter);
}, [cards, holderFilter]);

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

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],
);


const cardsByHolder = useMemo(() => countCardsByHolder(cards), [cards]);
Expand Down Expand Up @@ -353,11 +424,14 @@ export default function DashboardPage() {
onTogglePrivacy={togglePrivacyMode}
amountClass={amountClass}
displayCurrency={displayCurrency}
visibleBills={visibleBills}
onPaySingle={handlePaySingle}
onPayPayable={handlePayPayable}
payingPayableId={payingPayableId}
onPayAllOpen={openPayAllConfirm}
onNavBills={goToBills}
onNavPromos={goToPromos}
onNavNotifications={goToNotifications}
unreadNotificationCount={unreadNotificationCount}
totalCardCount={totalCardCount}
holders={holders}
cardsByHolder={cardsByHolder}
Expand All @@ -380,13 +454,13 @@ export default function DashboardPage() {
toast={toast}
onToastClose={closeToast}
error={error}
onRetry={loadData}
onRetry={() => void loadData()}
/>

<QuickActionSheet
open={quickSheetOpen}
onClose={closeQuickSheet}
onChanged={loadData}
onChanged={() => void loadData({ silent: true })}
initialAction={quickInitialAction}
/>
</>
Expand Down
5 changes: 5 additions & 0 deletions app/(mobile)/notifications/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { NotificationCenterView } from '@/components/mobile/NotificationCenterView'

export default function NotificationsPage() {
return <NotificationCenterView />
}
71 changes: 69 additions & 2 deletions app/(mobile)/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { DisplayPreferencesCard } from '@/components/settings/DisplayPreferences
import { ReminderPreferencesCard } from '@/components/settings/ReminderPreferencesCard'
import { GmailConnectPanel } from '@/components/mobile/GmailConnectPanel'
import { getGmailConnection, type GmailConnectionStatus } from '@/lib/api/gmail'
import { getUnreadNotificationCount } from '@/lib/api/notifications'
import { countEnabledNotificationItems } from '@/lib/notifications.shared'
import {
UserIcon,
PromoIcon,
Expand Down Expand Up @@ -98,6 +100,7 @@ export default function SettingsPage() {
const [showDisplaySheet, setShowDisplaySheet] = useState(false)
const [showLogoutDialog, setShowLogoutDialog] = useState(false)
const [loggingOut, setLoggingOut] = useState(false)
const [unreadNotifications, setUnreadNotifications] = useState<number | null>(null)

const [notice, setNotice] = useState<{ open: boolean; message: string; severity: 'success' | 'error' | 'info' }>({
open: false,
Expand All @@ -123,6 +126,47 @@ export default function SettingsPage() {
void loadGmail()
}, [loadGmail])

const refreshUnreadCount = useCallback(async () => {
try {
const count = await getUnreadNotificationCount(false)
setUnreadNotifications(count)
} catch (err) {
console.warn('[settings] failed to fetch unread notification count:', err)
setUnreadNotifications(null)
}
}, [])

useEffect(() => {
void refreshUnreadCount()
if (typeof window === 'undefined') return
const onFocus = () => {
void refreshUnreadCount()
}
const onVisibility = () => {
if (document.visibilityState === 'visible') {
void refreshUnreadCount()
}
}
window.addEventListener('focus', onFocus)
document.addEventListener('visibilitychange', onVisibility)
Comment on lines +150 to +151

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)

return () => {
window.removeEventListener('focus', onFocus)
document.removeEventListener('visibilitychange', onVisibility)
}
}, [refreshUnreadCount])

useEffect(() => {
if (typeof window === 'undefined') return
const params = new URLSearchParams(window.location.search)
if (params.get('open') === 'reminders') {
setShowReminderSheet(true)
params.delete('open')
const qs = params.toString()
const cleanUrl = window.location.pathname + (qs ? `?${qs}` : '')
window.history.replaceState(null, '', cleanUrl)
}
}, [])

const isAdmin = user?.role === 'admin'
const forwardAddress = user ? 'bills+' + user.id + '@' + DOMAIN : null

Expand Down Expand Up @@ -159,9 +203,9 @@ export default function SettingsPage() {
// 计算偏好摘要胶囊文案(映射表/函数化,去嵌套三元;完整展示已选节点)
const gmailSummary = formatGmailSummary(gmailStatus, gmailLoading, gmailError)
const billDays = reminderConfig?.remind_days_before ?? [3, 1, 0]
const oppEnabled = reminderConfig?.opportunities?.enabled !== false
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}项开`

const displaySummary = `${displayConfig?.default_currency || 'CNY'} · ${displayConfig?.privacy_mode ? '隐私开启' : '隐私关闭'}`

return (
Expand Down Expand Up @@ -268,6 +312,29 @@ export default function SettingsPage() {
数据同步与偏好设置
</p>
<div className='overflow-hidden rounded-2xl border border-d-border bg-d-surface divide-y divide-d-border/60'>
{/* 通知中心 */}
<SettingsMenuRow
icon={<BellIcon size={20} />}
title='通知中心'
subtitle='查看全部通知、标记已读与清理记录'
onClick={() => router.push('/notifications')}
badge={(() => {
if (unreadNotifications === null) return null
if (unreadNotifications > 0) {
return (
<span className='mr-0.5 shrink-0 rounded-full border border-d-danger/40 bg-d-danger-soft px-2.5 py-0.5 text-[11px] font-semibold text-d-danger-ink'>
{unreadNotifications > 99 ? '99+' : `${unreadNotifications} 未读`}
</span>
)
}
return (
<span className='mr-0.5 shrink-0 rounded-full border border-d-border bg-d-subtle px-2.5 py-0.5 text-[11px] font-semibold text-d-muted'>
全部已读
</span>
)
})()}
/>

{/* 邮箱账单导入 */}
<SettingsMenuRow
icon={<ImportIcon size={20} />}
Expand Down
36 changes: 36 additions & 0 deletions app/api/push/test/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import webpush from 'web-push'
import { getDb } from '@/lib/db'
import { getWorkerEnv } from '@/lib/db/client'
import { readSession } from '@/lib/session'
import { getLocalTodayString } from '@/lib/utils'

async function sessionUserId(request: Request): Promise<string | null> {
const session = await readSession(request)
Expand Down Expand Up @@ -65,5 +66,40 @@ export async function POST(request: Request) {
for (const id of staleIds) {
await db.prepare('DELETE FROM push_subscriptions WHERE id = ?').bind(id).run()
}
if (sent > 0) {
const ts = new Date().toISOString()
const todayStr = getLocalTodayString('Asia/Shanghai')

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
时区 'Asia/Shanghai' 硬编码作为去重键 test:${todayStr} 的日期来源。用户偏好中已有 opportunities.time_zone 配置(默认同为 Asia/Shanghai),建议与提醒发送路径使用同一时区来源,避免非上海时区用户在同日不同时区下产生跨日去重键偏移。风险较低,可统一读取用户偏好时区。

try {
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)
VALUES (?, ?, ?, 'system', ?, ?, '/notifications', ?, ?, 'sent', ?)
ON CONFLICT(user_id, notification_key) DO UPDATE SET

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
ON CONFLICT(user_id, notification_key) 依赖 notification_history 表存在 (user_id, notification_key) 的唯一约束/唯一索引;若迁移 0033 未定义(或列顺序不一致),SQLite 会在语句准备阶段直接报错。且下方 catch 仅 console.warn,测试推送仍返回成功但历史记录静默丢失,排障困难。请核对迁移建表语句与唯一索引定义,并考虑将日志级别提升为 error 以便发现问题。

title = excluded.title,
body = excluded.body,
metadata_json = excluded.metadata_json,
sent_at = excluded.sent_at,
status = 'sent',
push_sent_at = excluded.push_sent_at,
-- 测试推送由用户在设置页显式触发,有意重置同日记录阅读/删除状态;勿复制到 Cron 路径
read_at = NULL,
deleted_at = NULL`
Comment on lines +84 to +87

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`

)
.bind(
crypto.randomUUID(),
userId,
`test:${todayStr}`,
'WorldCredit 测试推送',
'推送通道已就绪 ✅ 到期提醒将按时送达。',
JSON.stringify({ kind: 'system_test', sent }),
ts,
ts
)
.run()
} catch (err) {
console.warn('[push/test] failed to record notification_history:', err)
}
}
return Response.json({ data: { subscriptions: subs.length, sent, removed: staleIds.length, errors }, error: null })
}
Loading
Loading