@@ -275,8 +322,26 @@ export function ReminderPreferencesCard({ config, onChange, disabled }: Reminder
{(opp?.enabled ?? true) && (
+ {/* 6 项权益与优惠独立开关 */}
+
+ {oppSwitchItems.map((item) => (
+
+
+
{item.label}
+
{item.description}
+
+
handleToggleItemSwitch(item.key, nextVal)}
+ disabled={disabled}
+ ariaLabel={item.label}
+ />
+
+ ))}
+
+
{/* 提醒时区下拉 */}
-
+
@@ -363,6 +428,61 @@ export function ReminderPreferencesCard({ config, onChange, disabled }: Reminder
})}
+
+ {/* 优惠活动提醒节点 */}
+
+
+
+ {ACTIVITY_DAY_CHOICES.map((d) => {
+ const active = (opp?.activity_days_before ?? DEFAULT_ACTIVITY_DAYS).includes(d)
+ return (
+
+ )
+ })}
+
+
+
+ {/* 达标任务提醒节点 */}
+
+
+
+ {TASK_DAY_CHOICES.map((d) => {
+ const active = (opp?.task_days_before ?? DEFAULT_TASK_DAYS).includes(d)
+ const label = d === 0 ? '截止当天' : `提前 ${d} 天`
+ return (
+
+ )
+ })}
+
+
)}
diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/DashboardMetrics.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/DashboardMetrics.swift
index bd0bd3e..fc39098 100644
--- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/DashboardMetrics.swift
+++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/DashboardMetrics.swift
@@ -151,6 +151,8 @@ public struct DashboardMetrics: Equatable, Sendable {
public let totalPending: Double
/// 已逾期(已过还款日且未还清)合计,折算口径同上。
public let overdueAmount: Double
+ /// 当日待还合计(今日到期未结清信用卡账单 + 今日到期未结清固定支出),折算口径同上。
+ public let dueTodayAmount: Double
/// 未来 N 天(含今天)待还合计,折算口径同上。
public let futureAmount: Double
/// 普通未还(当前数据模型仅普通未还,分期/贷款暂未接入)。
@@ -161,6 +163,12 @@ public struct DashboardMetrics: Equatable, Sendable {
public let overdueBills: [BillDisplayItem]
/// 今天到期且未结清的账单(原币金额)。
public let dueTodayBills: [BillDisplayItem]
+ /// 今天到期且未结清的固定支出(原币金额)。
+ public let dueTodayPayables: [PayableItem]
+ /// 今天待还款总笔数(账单 + 固定支出)。
+ public let dueTodayCount: Int
+ /// 当日待还按原币种的小计。
+ public let dueTodayByCurrency: [String: Double]
/// 还款日在今天到 N 天内(含今天)的未还账单。
public let futureBills: [BillDisplayItem]
/// 当前持卡人筛选下的全部账单(与账单页 tab 无关)。
@@ -189,29 +197,37 @@ public struct DashboardMetrics: Equatable, Sendable {
/// - futureDays: 未来 N 天区间(7 / 14 / 30),区间含今天。
/// - displayCurrency: 目标展示币种;rates 缺失时同币种部分仍精确计入。
/// - rates: 汇率快照;nil 时跨币种金额被排除并记入 unconverted 列表。
+ /// - payables: 当期固定支出列表(默认为空以保持调用方兼容)。
public static func compute(
bills: [BillDisplayItem],
cards: [CardDisplayItem],
holderId: String?,
futureDays: Int,
displayCurrency: String,
- rates: FxRates?
+ rates: FxRates?,
+ payables: [PayableItem] = []
) -> DashboardMetrics {
- // 当前持卡人筛选下的账单与卡片(nil = 全部)。
+ // 当前持卡人筛选下的账单、卡片与固定支出(nil = 全部)。
let visibleBills: [BillDisplayItem]
let visibleCards: [CardDisplayItem]
+ let visiblePayables: [PayableItem]
if let holderId {
visibleBills = bills.filter { $0.card.holderId == holderId }
visibleCards = cards.filter { $0.card.holderId == holderId }
+ visiblePayables = payables.filter { $0.holderId == holderId }
} else {
visibleBills = bills
visibleCards = cards
+ visiblePayables = payables
}
// 只统计未还清的账单:已结清(status = paid)或剩余 ≤ 0.01 浮点容差的排除。
let unpaid = visibleBills.filter { $0.bill.status != "paid" && $0.remainingAmount > 0.01 }
let overdueBills = unpaid.filter { $0.daysUntilDue < 0 }
let dueTodayBills = unpaid.filter { $0.daysUntilDue == 0 }
+ let dueTodayPayables = visiblePayables.filter {
+ $0.daysUntilDue == 0 && $0.status != .paid && !$0.isSettled && $0.remainingAmount > 0.01
+ }
let futureBills = unpaid.filter { $0.daysUntilDue >= 0 && $0.daysUntilDue <= futureDays }
func sum(_ list: [BillDisplayItem]) -> (convertedCurrency: String, byCurrency: [String: Double], total: Double,
@@ -225,6 +241,12 @@ public struct DashboardMetrics: Equatable, Sendable {
let pendingSum = sum(unpaid)
let overdueSum = sum(overdueBills)
+ let dueTodaySum = DashboardFx.sumByCurrency(
+ dueTodayBills.map { ($0.remainingAmount, $0.currency) }
+ + dueTodayPayables.map { ($0.remainingAmount, $0.currency) },
+ target: displayCurrency,
+ rates: rates
+ )
let futureSum = sum(futureBills)
// 额度:只算 active 且额度 > 0 的卡(额度未知的外币卡不进分母);
@@ -239,17 +261,22 @@ public struct DashboardMetrics: Equatable, Sendable {
let unconvertedCurrencies = Set(pendingSum.unconvertedCurrencies)
.union(overdueSum.unconvertedCurrencies)
+ .union(dueTodaySum.unconvertedCurrencies)
.union(futureSum.unconvertedCurrencies)
.sorted()
return DashboardMetrics(
totalPending: pendingSum.total,
overdueAmount: overdueSum.total,
+ dueTodayAmount: dueTodaySum.total,
futureAmount: futureSum.total,
plainOwed: pendingSum.total,
unconvertedCurrencies: unconvertedCurrencies,
overdueBills: overdueBills,
dueTodayBills: dueTodayBills,
+ dueTodayPayables: dueTodayPayables,
+ dueTodayCount: dueTodayBills.count + dueTodayPayables.count,
+ dueTodayByCurrency: dueTodaySum.byCurrency,
futureBills: futureBills,
visibleBills: visibleBills,
unpaidCount: unpaid.count,
diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/NotificationScheduler.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/NotificationScheduler.swift
index 386e5b1..6054e2e 100644
--- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/NotificationScheduler.swift
+++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/NotificationScheduler.swift
@@ -20,21 +20,41 @@ public final class NotificationScheduler: Sendable {
self.center = center
}
- /// 重新排布待还账单的本地提醒(按实际触发时间取最早 64 条)。
- public func rescheduleAll(today: Date = Date(), calendar: Calendar = {
- var cal = Calendar(identifier: .gregorian)
- cal.timeZone = TimeZone(identifier: "Asia/Shanghai")!
- return cal
- }()) async throws {
- // Bills, reference data and payment totals must come from one read snapshot.
- let billsWithCards: [(Bill, CreditCard, Bank?, Double)] = try await dbManager.dbWriter.read { db in
+ /// 重新排布待还账单、固定支出与最长免息期卡牌的本地提醒(按实际触发时间取最早 64 条)。
+ public func rescheduleAll(
+ today: Date = Date(),
+ calendar: Calendar = {
+ var cal = Calendar(identifier: .gregorian)
+ cal.timeZone = TimeZone(identifier: "Asia/Shanghai")!
+ return cal
+ }(),
+ payables: [PayableItem] = [],
+ preferences: UserReminderPreferences? = nil
+ ) async throws {
+ let billDueToday = preferences?.items.billDueToday ?? true
+ let billDueAdvance = preferences?.items.billDueAdvance ?? true
+ let payableDueToday = preferences?.items.payableDueToday ?? true
+ let payableDueAdvance = preferences?.items.payableDueAdvance ?? true
+ let gracePeriodLongest = preferences?.items.gracePeriodLongest ?? false
+ let advanceDays: [Int] = {
+ if let configured = preferences?.remindDaysBefore {
+ return Array(Set(configured.filter { $0 > 0 })).sorted()
+ }
+ return [3]
+ }()
+
+ // Bills, cards, reference data and payment totals must come from one read snapshot.
+ let snapshot: (
+ billsWithCards: [(Bill, CreditCard, Bank?, Double)],
+ graceCards: [(CreditCard, CardProduct, Bank?)]
+ ) = try await dbManager.dbWriter.read { db in
let bills = try Bill.filter(Column("status") != "paid").fetchAll(db)
let totals = try Row.fetchAll(db, sql: "SELECT bill_id, SUM(amount) AS total_paid FROM payments GROUP BY bill_id")
var paidByBill: [String: Double] = [:]
for row in totals {
paidByBill[row["bill_id"]] = row["total_paid"]
}
- var result: [(Bill, CreditCard, Bank?, Double)] = []
+ var billRows: [(Bill, CreditCard, Bank?, Double)] = []
for bill in bills {
guard let card = try CreditCard.fetchOne(db, id: bill.cardId) else { continue }
let bank: Bank?
@@ -44,9 +64,26 @@ public final class NotificationScheduler: Sendable {
} else {
bank = nil
}
- result.append((bill, card, bank, paidByBill[bill.id] ?? 0))
+ billRows.append((bill, card, bank, paidByBill[bill.id] ?? 0))
}
- return result
+
+ var graceRows: [(CreditCard, CardProduct, Bank?)] = []
+ if gracePeriodLongest {
+ let activeCards = try CreditCard
+ .filter(Column("status") == "active" && Column("card_type") != "loan")
+ .fetchAll(db)
+ for card in activeCards {
+ guard let product = try CardProduct.fetchOne(db, id: card.cardProductId) else { continue }
+ let bank: Bank?
+ if let bankId = product.bankId {
+ bank = try Bank.fetchOne(db, id: bankId)
+ } else {
+ bank = nil
+ }
+ graceRows.append((card, product, bank))
+ }
+ }
+ return (billRows, graceRows)
}
let df = DateFormatter()
@@ -55,38 +92,129 @@ public final class NotificationScheduler: Sendable {
df.timeZone = calendar.timeZone
var candidates: [(fireDate: Date, request: UNNotificationRequest)] = []
- for (bill, card, bank, totalPaid) in billsWithCards {
- guard let dueDate = df.date(from: bill.dueDate) else { continue }
- let remaining = bill.effectiveAmount - totalPaid
- guard remaining > 0.01 else { continue }
- let cardName = card.nameOverride ?? bank?.shortName ?? bank?.name ?? "信用卡"
- let last4 = card.cardNumberLast4.map { "(\($0))" } ?? ""
-
- for daysBefore in [0, 3] {
- guard let day = calendar.date(byAdding: .day, value: -daysBefore, to: dueDate) else { continue }
- var comp = calendar.dateComponents([.year, .month, .day], from: day)
- comp.calendar = calendar
- comp.timeZone = calendar.timeZone
- comp.hour = 9
- comp.minute = 0
- comp.second = 0
- guard let fireDate = calendar.date(from: comp), fireDate > today else { continue }
+ func makeNineAMComponents(for date: Date) -> DateComponents {
+ var comp = calendar.dateComponents([.year, .month, .day], from: date)
+ comp.calendar = calendar
+ comp.timeZone = calendar.timeZone
+ comp.hour = 9
+ comp.minute = 0
+ comp.second = 0
+ return comp
+ }
- let content = UNMutableNotificationContent()
- let identifier: String
- if daysBefore == 0 {
- identifier = "bill-due-\(bill.id)"
- content.title = "还款日提醒"
- content.body = "\(cardName)\(last4) 今日到期,剩余应还 ¥\(String(format: "%.2f", remaining))"
- } else {
- identifier = "bill-3d-\(bill.id)"
- content.title = "还款提醒"
- content.body = "\(cardName)\(last4) 将在 3 天后(\(bill.dueDate))到期,剩余应还 ¥\(String(format: "%.2f", remaining))"
+ if billDueToday || billDueAdvance {
+ var billOffsets: [Int] = []
+ if billDueToday { billOffsets.append(0) }
+ if billDueAdvance { billOffsets.append(contentsOf: advanceDays) }
+
+ for (bill, card, bank, totalPaid) in snapshot.billsWithCards {
+ guard let dueDate = df.date(from: bill.dueDate) else { continue }
+ let remaining = bill.effectiveAmount - totalPaid
+ guard remaining > 0.01 else { continue }
+ let cardName = card.nameOverride ?? bank?.shortName ?? bank?.name ?? "信用卡"
+ let last4 = card.cardNumberLast4.map { "(\($0))" } ?? ""
+
+ for daysBefore in billOffsets {
+ guard let day = calendar.date(byAdding: .day, value: -daysBefore, to: dueDate) else { continue }
+ let comp = makeNineAMComponents(for: day)
+ guard let fireDate = calendar.date(from: comp), fireDate > today else { continue }
+
+ let content = UNMutableNotificationContent()
+ let identifier: String
+ if daysBefore == 0 {
+ identifier = "bill-due-\(bill.id)"
+ content.title = "还款日提醒"
+ content.body = "\(cardName)\(last4) 今日到期,剩余应还 ¥\(String(format: "%.2f", remaining))"
+ } else {
+ identifier = "bill-\(daysBefore)d-\(bill.id)"
+ content.title = "还款提醒"
+ content.body = "\(cardName)\(last4) 将在 \(daysBefore) 天后(\(bill.dueDate))到期,剩余应还 ¥\(String(format: "%.2f", remaining))"
+ }
+ content.sound = .default
+ let trigger = UNCalendarNotificationTrigger(dateMatching: comp, repeats: false)
+ candidates.append((fireDate, UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)))
+ }
+ }
+ }
+
+ if payableDueToday || payableDueAdvance {
+ var payableOffsets: [Int] = []
+ if payableDueToday { payableOffsets.append(0) }
+ if payableDueAdvance { payableOffsets.append(contentsOf: advanceDays) }
+
+ for payable in payables {
+ guard !payable.isSettled, payable.status != .paid, payable.remainingAmount > 0.01 else { continue }
+ guard let dueDate = df.date(from: payable.dueDate) else { continue }
+ let amountLabel = DashboardMoney.format(payable.remainingAmount, currency: payable.currency)
+
+ for daysBefore in payableOffsets {
+ guard let day = calendar.date(byAdding: .day, value: -daysBefore, to: dueDate) else { continue }
+ let comp = makeNineAMComponents(for: day)
+ guard let fireDate = calendar.date(from: comp), fireDate > today else { continue }
+
+ let content = UNMutableNotificationContent()
+ let identifier: String
+ if daysBefore == 0 {
+ identifier = "payable-due-\(payable.id)"
+ content.title = "固定支出今日到期"
+ content.body = "\(payable.name)(\(payable.category.label))今日到期,剩余应付 \(amountLabel)"
+ } else {
+ identifier = "payable-\(daysBefore)d-\(payable.id)"
+ content.title = "固定支出提醒"
+ content.body = "\(payable.name)(\(payable.category.label))将在 \(daysBefore) 天后(\(payable.dueDate))到期,剩余应付 \(amountLabel)"
+ }
+ content.sound = .default
+ let trigger = UNCalendarNotificationTrigger(dateMatching: comp, repeats: false)
+ candidates.append((fireDate, UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)))
}
+ }
+ }
+
+ if gracePeriodLongest {
+ var todayFirstOfMonthComp = calendar.dateComponents([.year, .month], from: today)
+ todayFirstOfMonthComp.day = 1
+ let todayFirstOfMonth = calendar.date(from: todayFirstOfMonthComp) ?? today
+
+ for (card, product, bank) in snapshot.graceCards {
+ let rawBillingDay = card.overrideBillingDay ?? card.billingDay
+ let clampedBillingDay = max(1, min(rawBillingDay, 31))
+ let cardName = card.nameOverride ?? bank?.shortName ?? bank?.name ?? "信用卡"
+ let last4 = card.cardNumberLast4.map { "(\($0))" } ?? ""
+
+ var matchedFireDate: Date?
+ var matchedComp: DateComponents?
+ for monthOffset in 0...2 {
+ guard let monthStart = calendar.date(byAdding: .month, value: monthOffset, to: todayFirstOfMonth),
+ let monthRange = calendar.range(of: .day, in: .month, for: monthStart) else { continue }
+ var billingComp = calendar.dateComponents([.year, .month], from: monthStart)
+ billingComp.day = min(clampedBillingDay, monthRange.count)
+ billingComp.hour = 9
+ billingComp.minute = 0
+ billingComp.second = 0
+ billingComp.calendar = calendar
+ billingComp.timeZone = calendar.timeZone
+ guard let billingDate = calendar.date(from: billingComp),
+ let dayAfter = calendar.date(byAdding: .day, value: 1, to: billingDate) else { continue }
+ let fireComp = makeNineAMComponents(for: dayAfter)
+ guard let fireDate = calendar.date(from: fireComp), fireDate > today else { continue }
+ matchedFireDate = fireDate
+ matchedComp = fireComp
+ break
+ }
+
+ guard let fireDate = matchedFireDate, let fireComp = matchedComp else { continue }
+ let grace = BillingDateCalculator.calculateCardGracePeriod(
+ card: card,
+ cardProduct: product,
+ today: calendar.startOfDay(for: fireDate)
+ )
+ let content = UNMutableNotificationContent()
+ content.title = "今日最长免息期:\(cardName)\(last4)"
+ content.body = "昨日为账单日,今日刷卡可享本轮最长 \(grace.graceDays) 天免息期(最晚还款日 \(df.string(from: grace.nextDueDate)))。"
content.sound = .default
- let trigger = UNCalendarNotificationTrigger(dateMatching: comp, repeats: false)
- let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
- candidates.append((fireDate, request))
+ let identifier = "grace-longest-\(card.id)-\(df.string(from: fireDate))"
+ let trigger = UNCalendarNotificationTrigger(dateMatching: fireComp, repeats: false)
+ candidates.append((fireDate, UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)))
}
}
diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/NotificationsModels.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/NotificationsModels.swift
new file mode 100644
index 0000000..8eb4e39
--- /dev/null
+++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/NotificationsModels.swift
@@ -0,0 +1,576 @@
+import Foundation
+
+/// 通知分类视觉色调(与 Web 端 `NOTIFICATION_CATEGORY_META` 对齐)。
+public enum NotificationCategoryTone: String, Equatable, Hashable, Sendable {
+ case danger
+ case gold
+ case accent
+ case muted
+}
+
+/// 通知中心分类枚举,保留 `.unknown(String)` 以兼容未来服务端新增分类。
+public enum NotificationCategory: Codable, Equatable, Hashable, Sendable {
+ case billDueToday
+ case payableDueToday
+ case billDueAdvance
+ case payableDueAdvance
+ case billOverdue
+ case gracePeriodLongest
+ case opportunityExpiry
+ case opportunityClaim
+ case opportunityActivity
+ case opportunityTask
+ case opportunityReset
+ case opportunityBooking
+ case system
+ case unknown(String)
+
+ public init(rawValue: String) {
+ switch rawValue {
+ case "bill_due_today": self = .billDueToday
+ case "payable_due_today": self = .payableDueToday
+ case "bill_due_advance": self = .billDueAdvance
+ case "payable_due_advance": self = .payableDueAdvance
+ case "bill_overdue": self = .billOverdue
+ case "grace_period_longest": self = .gracePeriodLongest
+ case "opportunity_expiry": self = .opportunityExpiry
+ case "opportunity_claim": self = .opportunityClaim
+ case "opportunity_activity": self = .opportunityActivity
+ case "opportunity_task": self = .opportunityTask
+ case "opportunity_reset": self = .opportunityReset
+ case "opportunity_booking": self = .opportunityBooking
+ case "system": self = .system
+ default: self = .unknown(rawValue)
+ }
+ }
+
+ public var rawValue: String {
+ switch self {
+ case .billDueToday: return "bill_due_today"
+ case .payableDueToday: return "payable_due_today"
+ case .billDueAdvance: return "bill_due_advance"
+ case .payableDueAdvance: return "payable_due_advance"
+ case .billOverdue: return "bill_overdue"
+ case .gracePeriodLongest: return "grace_period_longest"
+ case .opportunityExpiry: return "opportunity_expiry"
+ case .opportunityClaim: return "opportunity_claim"
+ case .opportunityActivity: return "opportunity_activity"
+ case .opportunityTask: return "opportunity_task"
+ case .opportunityReset: return "opportunity_reset"
+ case .opportunityBooking: return "opportunity_booking"
+ case .system: return "system"
+ case .unknown(let value): return value
+ }
+ }
+
+ public var label: String {
+ switch self {
+ case .billDueToday: return "当日待还"
+ case .payableDueToday: return "固定支出"
+ case .billDueAdvance: return "即将到期"
+ case .payableDueAdvance: return "支出提醒"
+ case .billOverdue: return "已逾期"
+ case .gracePeriodLongest: return "最长免息期"
+ case .opportunityExpiry: return "权益到期"
+ case .opportunityClaim: return "权益领取"
+ case .opportunityActivity: return "优惠活动"
+ case .opportunityTask: return "达标任务"
+ case .opportunityReset: return "周期重置"
+ case .opportunityBooking: return "预约服务"
+ case .system: return "系统通知"
+ case .unknown(let value): return value.isEmpty ? "系统通知" : value
+ }
+ }
+
+ public var tone: NotificationCategoryTone {
+ switch self {
+ case .billOverdue:
+ return .danger
+ case .billDueToday, .payableDueToday, .gracePeriodLongest, .opportunityExpiry:
+ return .gold
+ case .billDueAdvance, .payableDueAdvance, .opportunityClaim, .opportunityActivity,
+ .opportunityTask, .opportunityReset, .opportunityBooking:
+ return .accent
+ case .system, .unknown:
+ return .muted
+ }
+ }
+
+ public init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ let raw = try container.decode(String.self)
+ self = NotificationCategory(rawValue: raw)
+ }
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ try container.encode(rawValue)
+ }
+}
+
+public struct NotificationBillBreakdown: Codable, Equatable, Sendable, Identifiable {
+ public let id: String
+ public let subject: String
+ public let remaining: Double
+ public let currency: String
+ public let dueDate: String
+
+ public init(id: String, subject: String, remaining: Double, currency: String, dueDate: String) {
+ self.id = id
+ self.subject = subject
+ self.remaining = remaining
+ self.currency = currency
+ self.dueDate = dueDate
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case id, subject, remaining, currency
+ case dueDate = "due_date"
+ }
+}
+
+public struct NotificationPayableBreakdown: Codable, Equatable, Sendable, Identifiable {
+ public let id: String
+ public let name: String
+ public let category: String
+ public let remaining: Double
+ public let currency: String
+ public let dueDate: String
+
+ public init(id: String, name: String, category: String, remaining: Double, currency: String, dueDate: String) {
+ self.id = id
+ self.name = name
+ self.category = category
+ self.remaining = remaining
+ self.currency = currency
+ self.dueDate = dueDate
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case id, name, category, remaining, currency
+ case dueDate = "due_date"
+ }
+}
+
+public struct NotificationGraceCardBreakdown: Codable, Equatable, Sendable, Identifiable {
+ public let cardId: String
+ public let label: String
+ public let graceDays: Int
+ public let nextBillingDate: String
+ public let nextDueDate: String
+
+ public var id: String { cardId }
+
+ public init(
+ cardId: String,
+ label: String,
+ graceDays: Int,
+ nextBillingDate: String,
+ nextDueDate: String
+ ) {
+ self.cardId = cardId
+ self.label = label
+ self.graceDays = graceDays
+ self.nextBillingDate = nextBillingDate
+ self.nextDueDate = nextDueDate
+ }
+}
+
+public struct NotificationMetadata: Codable, Equatable, Sendable {
+ public let kind: String?
+ public let totalsByCurrency: [String: Double]?
+ public let bills: [NotificationBillBreakdown]?
+ public let payables: [NotificationPayableBreakdown]?
+ public let cards: [NotificationGraceCardBreakdown]?
+
+ public init(
+ kind: String? = nil,
+ totalsByCurrency: [String: Double]? = nil,
+ bills: [NotificationBillBreakdown]? = nil,
+ payables: [NotificationPayableBreakdown]? = nil,
+ cards: [NotificationGraceCardBreakdown]? = nil
+ ) {
+ self.kind = kind
+ self.totalsByCurrency = totalsByCurrency
+ self.bills = bills
+ self.payables = payables
+ self.cards = cards
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case kind
+ case totalsByCurrency = "totals_by_currency"
+ case bills, payables, cards
+ }
+}
+
+public struct UserNotificationItem: Codable, Equatable, Identifiable, Sendable {
+ public let id: String
+ public let userId: String
+ public let notificationKey: String
+ public let category: NotificationCategory
+ public let title: String
+ public let body: String?
+ public let targetUrl: String?
+ public let metadataJson: String?
+ public let sentAt: String
+ public let status: String
+ public let error: String?
+ public let readAt: String?
+ public let deletedAt: String?
+ public let pushSentAt: String?
+
+ public init(
+ id: String,
+ userId: String,
+ notificationKey: String,
+ category: NotificationCategory,
+ title: String,
+ body: String? = nil,
+ targetUrl: String? = nil,
+ metadataJson: String? = nil,
+ sentAt: String,
+ status: String = "skipped",
+ error: String? = nil,
+ readAt: String? = nil,
+ deletedAt: String? = nil,
+ pushSentAt: String? = nil
+ ) {
+ self.id = id
+ self.userId = userId
+ self.notificationKey = notificationKey
+ self.category = category
+ self.title = title
+ self.body = body
+ self.targetUrl = targetUrl
+ self.metadataJson = metadataJson
+ self.sentAt = sentAt
+ self.status = status
+ self.error = error
+ self.readAt = readAt
+ self.deletedAt = deletedAt
+ self.pushSentAt = pushSentAt
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case id
+ case userId = "user_id"
+ case notificationKey = "notification_key"
+ case category, title, body
+ case targetUrl = "target_url"
+ case metadataJson = "metadata_json"
+ case sentAt = "sent_at"
+ case status, error
+ case readAt = "read_at"
+ case deletedAt = "deleted_at"
+ case pushSentAt = "push_sent_at"
+ }
+
+ public var isUnread: Bool {
+ readAt == nil
+ }
+
+ public var parsedMetadata: NotificationMetadata? {
+ guard let metadataJson, let data = metadataJson.data(using: .utf8) else {
+ return nil
+ }
+ return try? JSONDecoder().decode(NotificationMetadata.self, from: data)
+ }
+
+ /// 返回附加已读时间戳的副本,供乐观 UI 更新使用。
+ public func markingRead(at readAt: String) -> UserNotificationItem {
+ UserNotificationItem(
+ id: id,
+ userId: userId,
+ notificationKey: notificationKey,
+ category: category,
+ title: title,
+ body: body,
+ targetUrl: targetUrl,
+ metadataJson: metadataJson,
+ sentAt: sentAt,
+ status: status,
+ error: error,
+ readAt: self.readAt ?? readAt,
+ deletedAt: deletedAt,
+ pushSentAt: pushSentAt
+ )
+ }
+}
+
+public struct NotificationsPageResult: Codable, Equatable, Sendable {
+ public let items: [UserNotificationItem]
+ public let unreadCount: Int
+ public let totalCount: Int
+
+ public init(items: [UserNotificationItem], unreadCount: Int, totalCount: Int) {
+ self.items = items
+ self.unreadCount = unreadCount
+ self.totalCount = totalCount
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case items
+ case unreadCount = "unread_count"
+ case totalCount = "total_count"
+ }
+}
+
+public struct NotificationReadResult: Codable, Equatable, Sendable {
+ public let updated: Bool
+ public let unreadCount: Int
+
+ enum CodingKeys: String, CodingKey {
+ case updated
+ case unreadCount = "unread_count"
+ }
+}
+
+public struct NotificationBulkReadResult: Codable, Equatable, Sendable {
+ public let updatedCount: Int
+ public let unreadCount: Int
+
+ enum CodingKeys: String, CodingKey {
+ case updatedCount = "updated_count"
+ case unreadCount = "unread_count"
+ }
+}
+
+public struct NotificationDeleteResult: Codable, Equatable, Sendable {
+ public let deleted: Bool
+ public let unreadCount: Int
+
+ enum CodingKeys: String, CodingKey {
+ case deleted
+ case unreadCount = "unread_count"
+ }
+}
+
+public struct NotificationBulkDeleteResult: Codable, Equatable, Sendable {
+ public let deletedCount: Int
+ public let unreadCount: Int
+
+ enum CodingKeys: String, CodingKey {
+ case deletedCount = "deleted_count"
+ case unreadCount = "unread_count"
+ }
+}
+
+/// 12 项通知细粒度独立开关(缺省全开,兼容存量配置)。
+public struct NotificationItemSwitches: Codable, Equatable, Sendable {
+ public var billDueToday: Bool
+ public var payableDueToday: Bool
+ public var billDueAdvance: Bool
+ public var payableDueAdvance: Bool
+ public var billOverdue: Bool
+ public var gracePeriodLongest: Bool
+ public var opportunityExpiry: Bool
+ public var opportunityClaim: Bool
+ public var opportunityActivity: Bool
+ public var opportunityTask: Bool
+ public var opportunityReset: Bool
+ public var opportunityBooking: Bool
+
+ public init(
+ billDueToday: Bool = true,
+ payableDueToday: Bool = true,
+ billDueAdvance: Bool = true,
+ payableDueAdvance: Bool = true,
+ billOverdue: Bool = true,
+ gracePeriodLongest: Bool = true,
+ opportunityExpiry: Bool = true,
+ opportunityClaim: Bool = true,
+ opportunityActivity: Bool = true,
+ opportunityTask: Bool = true,
+ opportunityReset: Bool = true,
+ opportunityBooking: Bool = true
+ ) {
+ self.billDueToday = billDueToday
+ self.payableDueToday = payableDueToday
+ self.billDueAdvance = billDueAdvance
+ self.payableDueAdvance = payableDueAdvance
+ self.billOverdue = billOverdue
+ self.gracePeriodLongest = gracePeriodLongest
+ self.opportunityExpiry = opportunityExpiry
+ self.opportunityClaim = opportunityClaim
+ self.opportunityActivity = opportunityActivity
+ self.opportunityTask = opportunityTask
+ self.opportunityReset = opportunityReset
+ self.opportunityBooking = opportunityBooking
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case billDueToday = "bill_due_today"
+ case payableDueToday = "payable_due_today"
+ case billDueAdvance = "bill_due_advance"
+ case payableDueAdvance = "payable_due_advance"
+ case billOverdue = "bill_overdue"
+ case gracePeriodLongest = "grace_period_longest"
+ case opportunityExpiry = "opportunity_expiry"
+ case opportunityClaim = "opportunity_claim"
+ case opportunityActivity = "opportunity_activity"
+ case opportunityTask = "opportunity_task"
+ case opportunityReset = "opportunity_reset"
+ case opportunityBooking = "opportunity_booking"
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ billDueToday = try c.decodeIfPresent(Bool.self, forKey: .billDueToday) ?? true
+ payableDueToday = try c.decodeIfPresent(Bool.self, forKey: .payableDueToday) ?? true
+ billDueAdvance = try c.decodeIfPresent(Bool.self, forKey: .billDueAdvance) ?? true
+ payableDueAdvance = try c.decodeIfPresent(Bool.self, forKey: .payableDueAdvance) ?? true
+ billOverdue = try c.decodeIfPresent(Bool.self, forKey: .billOverdue) ?? true
+ gracePeriodLongest = try c.decodeIfPresent(Bool.self, forKey: .gracePeriodLongest) ?? true
+ opportunityExpiry = try c.decodeIfPresent(Bool.self, forKey: .opportunityExpiry) ?? true
+ opportunityClaim = try c.decodeIfPresent(Bool.self, forKey: .opportunityClaim) ?? true
+ opportunityActivity = try c.decodeIfPresent(Bool.self, forKey: .opportunityActivity) ?? true
+ opportunityTask = try c.decodeIfPresent(Bool.self, forKey: .opportunityTask) ?? true
+ opportunityReset = try c.decodeIfPresent(Bool.self, forKey: .opportunityReset) ?? true
+ opportunityBooking = try c.decodeIfPresent(Bool.self, forKey: .opportunityBooking) ?? true
+ }
+}
+
+public struct OpportunityReminderPreferences: Codable, Equatable, Sendable {
+ public var enabled: Bool
+ public var webPushEnabled: Bool
+ public var timeZone: String
+ public var localTime: String
+ public var expiryDaysBefore: [Int]
+ public var activityDaysBefore: [Int]
+ public var claimDaysBefore: [Int]
+ public var taskDaysBefore: [Int]
+ public var resetEnabled: Bool
+ public var bookingEnabled: Bool
+
+ public init(
+ enabled: Bool = true,
+ webPushEnabled: Bool = true,
+ timeZone: String = "Asia/Shanghai",
+ localTime: String = "09:00",
+ expiryDaysBefore: [Int] = [3, 1, 0],
+ activityDaysBefore: [Int] = [7, 3, 1],
+ claimDaysBefore: [Int] = [3, 1, 0],
+ taskDaysBefore: [Int] = [3, 1, 0],
+ resetEnabled: Bool = true,
+ bookingEnabled: Bool = true
+ ) {
+ self.enabled = enabled
+ self.webPushEnabled = webPushEnabled
+ self.timeZone = timeZone
+ self.localTime = localTime
+ self.expiryDaysBefore = expiryDaysBefore
+ self.activityDaysBefore = activityDaysBefore
+ self.claimDaysBefore = claimDaysBefore
+ self.taskDaysBefore = taskDaysBefore
+ self.resetEnabled = resetEnabled
+ self.bookingEnabled = bookingEnabled
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case enabled
+ case webPushEnabled = "web_push_enabled"
+ case timeZone = "time_zone"
+ case localTime = "local_time"
+ case expiryDaysBefore = "expiry_days_before"
+ case activityDaysBefore = "activity_days_before"
+ case claimDaysBefore = "claim_days_before"
+ case taskDaysBefore = "task_days_before"
+ case resetEnabled = "reset_enabled"
+ case bookingEnabled = "booking_enabled"
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ enabled = try c.decodeIfPresent(Bool.self, forKey: .enabled) ?? true
+ webPushEnabled = try c.decodeIfPresent(Bool.self, forKey: .webPushEnabled) ?? true
+ timeZone = try c.decodeIfPresent(String.self, forKey: .timeZone) ?? "Asia/Shanghai"
+ localTime = try c.decodeIfPresent(String.self, forKey: .localTime) ?? "09:00"
+ expiryDaysBefore = try c.decodeIfPresent([Int].self, forKey: .expiryDaysBefore) ?? [3, 1, 0]
+ activityDaysBefore = try c.decodeIfPresent([Int].self, forKey: .activityDaysBefore) ?? [7, 3, 1]
+ claimDaysBefore = try c.decodeIfPresent([Int].self, forKey: .claimDaysBefore) ?? [3, 1, 0]
+ taskDaysBefore = try c.decodeIfPresent([Int].self, forKey: .taskDaysBefore) ?? [3, 1, 0]
+ resetEnabled = try c.decodeIfPresent(Bool.self, forKey: .resetEnabled) ?? true
+ bookingEnabled = try c.decodeIfPresent(Bool.self, forKey: .bookingEnabled) ?? true
+ }
+}
+
+public struct UserReminderPreferences: Codable, Equatable, Sendable {
+ public var remindDaysBefore: [Int]
+ public var quietHoursStart: String?
+ public var quietHoursEnd: String?
+ public var enabledChannels: [String]
+ public var customReminderEmail: String?
+ public var items: NotificationItemSwitches
+ public var opportunities: OpportunityReminderPreferences
+
+ public init(
+ remindDaysBefore: [Int] = [3, 1, 0],
+ quietHoursStart: String? = "22:00",
+ quietHoursEnd: String? = "08:00",
+ enabledChannels: [String] = ["web_push"],
+ customReminderEmail: String? = nil,
+ items: NotificationItemSwitches = NotificationItemSwitches(),
+ opportunities: OpportunityReminderPreferences = OpportunityReminderPreferences()
+ ) {
+ self.remindDaysBefore = remindDaysBefore
+ self.quietHoursStart = quietHoursStart
+ self.quietHoursEnd = quietHoursEnd
+ self.enabledChannels = enabledChannels
+ self.customReminderEmail = customReminderEmail
+ self.items = items
+ self.opportunities = opportunities
+ }
+
+ public var webPushChannelEnabled: Bool {
+ enabledChannels.contains("web_push")
+ }
+
+ enum CodingKeys: String, CodingKey {
+ case remindDaysBefore = "remind_days_before"
+ case quietHoursStart = "quiet_hours_start"
+ case quietHoursEnd = "quiet_hours_end"
+ case enabledChannels = "enabled_channels"
+ case customReminderEmail = "custom_reminder_email"
+ case items
+ case opportunities
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ remindDaysBefore = try c.decodeIfPresent([Int].self, forKey: .remindDaysBefore) ?? [3, 1, 0]
+ quietHoursStart = try c.decodeIfPresent(String.self, forKey: .quietHoursStart) ?? "22:00"
+ quietHoursEnd = try c.decodeIfPresent(String.self, forKey: .quietHoursEnd) ?? "08:00"
+ customReminderEmail = try c.decodeIfPresent(String.self, forKey: .customReminderEmail)
+ let decodedOpp = try c.decodeIfPresent(OpportunityReminderPreferences.self, forKey: .opportunities)
+ ?? OpportunityReminderPreferences()
+ opportunities = decodedOpp
+
+ if let channels = try c.decodeIfPresent([String].self, forKey: .enabledChannels) {
+ enabledChannels = channels
+ } else {
+ enabledChannels = decodedOpp.webPushEnabled ? ["web_push"] : []
+ }
+
+ let rawItemsMap = try c.decodeIfPresent([String: Bool].self, forKey: .items)
+ var resolvedItems = try c.decodeIfPresent(NotificationItemSwitches.self, forKey: .items)
+ ?? NotificationItemSwitches()
+ if rawItemsMap?["opportunity_reset"] == nil {
+ resolvedItems.opportunityReset = decodedOpp.resetEnabled
+ }
+ if rawItemsMap?["opportunity_booking"] == nil {
+ resolvedItems.opportunityBooking = decodedOpp.bookingEnabled
+ }
+ items = resolvedItems
+ }
+}
+
+public struct ReminderPreferencesEnvelope: Codable, Equatable, Sendable {
+ public let userId: String
+ public let reminderConfig: UserReminderPreferences
+
+ enum CodingKeys: String, CodingKey {
+ case userId = "user_id"
+ case reminderConfig = "reminder_config"
+ }
+}
diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/NotificationsRemoteService.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/NotificationsRemoteService.swift
new file mode 100644
index 0000000..6fe5d10
--- /dev/null
+++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Network/NotificationsRemoteService.swift
@@ -0,0 +1,113 @@
+import Foundation
+
+/// 通知中心与提醒偏好的远程服务:走 `/api/rpc/notifications/*` 与 `/api/rpc/preferences/*`。
+public actor NotificationsRemoteService {
+ private let apiClient: ApiClient
+
+ public init(apiClient: ApiClient) {
+ self.apiClient = apiClient
+ }
+
+ public func fetchNotifications(
+ filter: String = "all",
+ category: NotificationCategory? = nil,
+ limit: Int = 50,
+ offset: Int = 0,
+ syncToday: Bool = true
+ ) async throws -> NotificationsPageResult {
+ var options: [String: Any] = [
+ "filter": filter == "unread" ? "unread" : "all",
+ "limit": limit,
+ "offset": offset,
+ "syncToday": syncToday,
+ ]
+ if let category {
+ options["category"] = category.rawValue
+ }
+ return try await apiClient.rpc(
+ module: "notifications",
+ function: "getNotifications",
+ args: [AnyCodable(""), AnyCodable(options)]
+ )
+ }
+
+ public func fetchUnreadCount() async throws -> Int {
+ try await apiClient.rpc(
+ module: "notifications",
+ function: "getUnreadNotificationCount",
+ args: [AnyCodable("")]
+ )
+ }
+
+ @discardableResult
+ public func markRead(notificationId: String) async throws -> NotificationReadResult {
+ try await apiClient.rpc(
+ module: "notifications",
+ function: "markNotificationRead",
+ args: [AnyCodable(""), AnyCodable(notificationId)]
+ )
+ }
+
+ @discardableResult
+ public func markAllRead() async throws -> NotificationBulkReadResult {
+ try await apiClient.rpc(
+ module: "notifications",
+ function: "markAllNotificationsRead",
+ args: [AnyCodable("")]
+ )
+ }
+
+ @discardableResult
+ public func delete(notificationId: String) async throws -> NotificationDeleteResult {
+ try await apiClient.rpc(
+ module: "notifications",
+ function: "deleteNotification",
+ args: [AnyCodable(""), AnyCodable(notificationId)]
+ )
+ }
+
+ @discardableResult
+ public func deleteAll() async throws -> NotificationBulkDeleteResult {
+ try await apiClient.rpc(
+ module: "notifications",
+ function: "deleteAllNotifications",
+ args: [AnyCodable("")]
+ )
+ }
+
+ public func fetchReminderPreferences(userId: String) async throws -> UserReminderPreferences {
+ let trimmed = userId.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { throw URLError(.userAuthenticationRequired) }
+ let envelope: ReminderPreferencesEnvelope = try await apiClient.rpc(
+ module: "preferences",
+ function: "getUserPreferences",
+ args: [AnyCodable(trimmed)]
+ )
+ guard envelope.userId == trimmed else { throw URLError(.badServerResponse) }
+ return envelope.reminderConfig
+ }
+
+ @discardableResult
+ public func updateReminderPreferences(
+ userId: String,
+ config: UserReminderPreferences
+ ) async throws -> UserReminderPreferences {
+ let trimmed = userId.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { throw URLError(.userAuthenticationRequired) }
+ let encodedConfig = try jsonValue(config)
+ let payload = AnyCodable(["reminder_config": encodedConfig.value])
+ let envelope: ReminderPreferencesEnvelope = try await apiClient.rpc(
+ module: "preferences",
+ function: "updateUserPreferences",
+ args: [AnyCodable(trimmed), payload]
+ )
+ guard envelope.userId == trimmed else { throw URLError(.badServerResponse) }
+ return envelope.reminderConfig
+ }
+
+ private func jsonValue
(_ value: T) throws -> AnyCodable {
+ let data = try JSONEncoder().encode(value)
+ let object = try JSONSerialization.jsonObject(with: data)
+ return AnyCodable(object)
+ }
+}
diff --git a/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/DashboardMetricsTests.swift b/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/DashboardMetricsTests.swift
index 718ec07..f2cb9e4 100644
--- a/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/DashboardMetricsTests.swift
+++ b/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/DashboardMetricsTests.swift
@@ -90,4 +90,62 @@ struct DashboardMetricsTests {
#expect(empty.totalPending == 0)
#expect(empty.visibleBills.isEmpty)
}
+
+ @Test("Due today metrics include unsettled due-today payables, holder filter and FX unconverted tracking")
+ func dueTodayWithPayables() {
+ let bills = [item("today", amount: 1000)]
+ let fx = FxRates(base: "USD", rates: ["USD": 1, "CNY": 7.2], timestamp: 0, fetchedAt: 0)
+ let payables = [
+ PayableItem(
+ id: "p-usd", createdBy: "u1", name: "VPS", category: .utility,
+ amount: 150, currency: "USD", dueDay: 10, holderId: "holder-a",
+ period: "2026-05", dueDate: "2026-05-10", daysUntilDue: 0, paidAmount: 50, status: .unpaid
+ ),
+ PayableItem(
+ id: "p-hkd", createdBy: "u1", name: "香港保险", category: .insurance,
+ amount: 500, currency: "HKD", dueDay: 10, holderId: "holder-a",
+ period: "2026-05", dueDate: "2026-05-10", daysUntilDue: 0, paidAmount: 0, status: .unpaid
+ ),
+ PayableItem(
+ id: "p-paid", createdBy: "u1", name: "物业", category: .utility,
+ amount: 300, currency: "CNY", dueDay: 10, holderId: "holder-a",
+ period: "2026-05", dueDate: "2026-05-10", daysUntilDue: 0, paidAmount: 300, status: .paid
+ ),
+ PayableItem(
+ id: "p-other-holder", createdBy: "u1", name: "房贷", category: .loan,
+ amount: 2000, currency: "CNY", dueDay: 10, holderId: "holder-b",
+ period: "2026-05", dueDate: "2026-05-10", daysUntilDue: 0, paidAmount: 0, status: .unpaid
+ ),
+ ]
+
+ let allMetrics = DashboardMetrics.compute(
+ bills: bills,
+ cards: [],
+ holderId: nil,
+ futureDays: 7,
+ displayCurrency: "CNY",
+ rates: fx,
+ payables: payables
+ )
+ // 1000 CNY bill + (150-50)*7.2 USD + 2000 CNY other-holder = 3720 CNY; HKD missing FX -> unconverted
+ #expect(allMetrics.dueTodayAmount == 3720)
+ #expect(allMetrics.dueTodayPayables.map(\.id) == ["p-usd", "p-hkd", "p-other-holder"])
+ #expect(allMetrics.dueTodayCount == 4)
+ #expect(allMetrics.dueTodayByCurrency == ["CNY": 3000, "USD": 100, "HKD": 500])
+ #expect(allMetrics.unconvertedCurrencies == ["HKD"])
+ #expect(allMetrics.totalPending == 1000)
+
+ let holderBMetrics = DashboardMetrics.compute(
+ bills: [],
+ cards: [],
+ holderId: "holder-b",
+ futureDays: 7,
+ displayCurrency: "CNY",
+ rates: fx,
+ payables: payables
+ )
+ #expect(holderBMetrics.dueTodayAmount == 2000)
+ #expect(holderBMetrics.dueTodayPayables.map(\.id) == ["p-other-holder"])
+ #expect(holderBMetrics.dueTodayCount == 1)
+ }
}
diff --git a/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/NotificationsCenterTests.swift b/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/NotificationsCenterTests.swift
new file mode 100644
index 0000000..b6585c0
--- /dev/null
+++ b/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/NotificationsCenterTests.swift
@@ -0,0 +1,223 @@
+import Foundation
+import Testing
+import GRDB
+import UserNotifications
+@testable import WorldCreditCore
+
+private final class NotificationCenterSpy: NotificationCenterProtocol, @unchecked Sendable {
+ var requests: [UNNotificationRequest] = []
+
+ func add(_ request: UNNotificationRequest) async throws {
+ requests.append(request)
+ }
+
+ func removePendingNotificationRequests(withIdentifiers identifiers: [String]) {
+ requests.removeAll { identifiers.contains($0.identifier) }
+ }
+
+ func removeAllPendingNotificationRequests() {
+ requests.removeAll()
+ }
+
+ func pendingNotificationRequests() async -> [UNNotificationRequest] {
+ requests
+ }
+}
+
+@Suite("Notification center DTOs, remote RPCs and scheduler")
+struct NotificationsCenterTests {
+ private func response(_ request: URLRequest, _ json: String, status: Int = 200) -> (Data, URLResponse) {
+ (Data(json.utf8), HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!)
+ }
+
+ private func instant(_ iso: String) -> Date {
+ ISO8601DateFormatter().date(from: iso)!
+ }
+
+ @Test("DTOs tolerate unknown categories, missing switch keys, legacy reset fallback and structured metadata")
+ func dtoDecoding() throws {
+ let rawPrefs = """
+ {
+ "user_id": "u1",
+ "reminder_config": {
+ "remind_days_before": [3, 1],
+ "opportunities": {
+ "enabled": true,
+ "web_push_enabled": false,
+ "reset_enabled": false
+ }
+ }
+ }
+ """
+ let envelope = try JSONDecoder().decode(ReminderPreferencesEnvelope.self, from: Data(rawPrefs.utf8))
+ #expect(envelope.userId == "u1")
+ #expect(envelope.reminderConfig.webPushChannelEnabled == false)
+ #expect(envelope.reminderConfig.items.billDueToday == true)
+ #expect(envelope.reminderConfig.items.payableDueToday == true)
+ #expect(envelope.reminderConfig.items.gracePeriodLongest == true)
+ #expect(envelope.reminderConfig.items.opportunityReset == false)
+ #expect(envelope.reminderConfig.items.opportunityBooking == true)
+
+ let notificationJson = """
+ {
+ "id": "n1",
+ "user_id": "u1",
+ "notification_key": "due_today_summary:2026-05-10",
+ "category": "future_kind",
+ "title": "今日待还",
+ "body": "完整正文",
+ "metadata_json": "{\\"kind\\":\\"due_today_summary\\",\\"totals_by_currency\\":{\\"CNY\\":1000},\\"bills\\":[{\\"id\\":\\"b1\\",\\"subject\\":\\"招行\\",\\"remaining\\":600,\\"currency\\":\\"CNY\\",\\"due_date\\":\\"2026-05-10\\"}],\\"payables\\":[{\\"id\\":\\"p1\\",\\"name\\":\\"房租\\",\\"category\\":\\"房租\\",\\"remaining\\":400,\\"currency\\":\\"CNY\\",\\"due_date\\":\\"2026-05-10\\"}]}",
+ "sent_at": "2026-05-10T01:00:00Z",
+ "status": "skipped",
+ "read_at": null
+ }
+ """
+ let item = try JSONDecoder().decode(UserNotificationItem.self, from: Data(notificationJson.utf8))
+ #expect(item.category == .unknown("future_kind"))
+ #expect(item.category.label == "future_kind")
+ #expect(item.isUnread == true)
+ #expect(item.parsedMetadata?.totalsByCurrency == ["CNY": 1000])
+ #expect(item.parsedMetadata?.bills?.first?.remaining == 600)
+ #expect(item.parsedMetadata?.payables?.first?.name == "房租")
+ }
+
+ @Test("NotificationsRemoteService sends exact RPC paths and arguments across all 8 operations")
+ func remoteContracts() async throws {
+ let sampleNotification = """
+ {
+ "id": "n1",
+ "user_id": "alice",
+ "notification_key": "k1",
+ "category": "bill_due_today",
+ "title": "标题",
+ "body": "正文",
+ "sent_at": "2026-05-10T01:00:00Z",
+ "status": "sent"
+ }
+ """
+
+ let session = MockNetworkSession { request in
+ let requestBody = try #require(request.httpBody)
+ let body = try #require(JSONSerialization.jsonObject(with: requestBody) as? [String: Any])
+ let args = try #require(body["args"] as? [Any])
+ switch request.url?.path {
+ case "/api/rpc/notifications/getNotifications":
+ let opts = try #require(args.last as? [String: Any])
+ #expect(opts["filter"] as? String == "unread")
+ return response(request, #"{"data":{"items":[\#(sampleNotification)],"unread_count":1,"total_count":2},"error":null}"#)
+ case "/api/rpc/notifications/getUnreadNotificationCount":
+ #expect(args.count == 1)
+ return response(request, #"{"data":3,"error":null}"#)
+ case "/api/rpc/notifications/markNotificationRead":
+ #expect(args.last as? String == "n1")
+ return response(request, #"{"data":{"updated":true,"unread_count":2},"error":null}"#)
+ case "/api/rpc/notifications/markAllNotificationsRead":
+ return response(request, #"{"data":{"updated_count":2,"unread_count":0},"error":null}"#)
+ case "/api/rpc/notifications/deleteNotification":
+ #expect(args.last as? String == "n1")
+ return response(request, #"{"data":{"deleted":true,"unread_count":0},"error":null}"#)
+ case "/api/rpc/notifications/deleteAllNotifications":
+ return response(request, #"{"data":{"deleted_count":2,"unread_count":0},"error":null}"#)
+ case "/api/rpc/preferences/getUserPreferences":
+ #expect(args as? [String] == ["alice"])
+ return response(request, #"{"data":{"user_id":"alice","reminder_config":{"remind_days_before":[5,1],"items":{"grace_period_longest":false}}},"error":null}"#)
+ case "/api/rpc/preferences/updateUserPreferences":
+ #expect(args.first as? String == "alice")
+ let patch = try #require(args.last as? [String: Any])
+ let reminder = try #require(patch["reminder_config"] as? [String: Any])
+ let items = try #require(reminder["items"] as? [String: Any])
+ #expect(items["payable_due_today"] as? Bool == false)
+ return response(request, #"{"data":{"user_id":"alice","reminder_config":{"remind_days_before":[5,1],"items":{"payable_due_today":false}}},"error":null}"#)
+ default:
+ Issue.record("Unexpected RPC path \(request.url?.path ?? "")")
+ throw URLError(.badURL)
+ }
+ }
+
+ let client = ApiClient(baseURL: URL(string: "https://test.local")!, session: session, token: "tok", useKeychain: false)
+ let service = NotificationsRemoteService(apiClient: client)
+
+ let page = try await service.fetchNotifications(filter: "unread")
+ #expect(page.items.count == 1)
+ #expect(page.unreadCount == 1)
+ #expect(try await service.fetchUnreadCount() == 3)
+ #expect(try await service.markRead(notificationId: "n1").updated == true)
+ #expect(try await service.markAllRead().updatedCount == 2)
+ #expect(try await service.delete(notificationId: "n1").deleted == true)
+ #expect(try await service.deleteAll().deletedCount == 2)
+
+ var prefs = try await service.fetchReminderPreferences(userId: "alice")
+ #expect(prefs.remindDaysBefore == [5, 1])
+ #expect(prefs.items.gracePeriodLongest == false)
+
+ prefs.items.payableDueToday = false
+ let updated = try await service.updateReminderPreferences(userId: "alice", config: prefs)
+ #expect(updated.items.payableDueToday == false)
+ }
+
+ @Test("NotificationScheduler enforces switches, schedules payables, clamps Feb 28->Mar 1 grace period and excludes loans")
+ func schedulerSwitchesAndGracePeriod() async throws {
+ let manager = try DatabaseManager.inMemory()
+ try await manager.dbWriter.write { db in
+ try db.execute(sql: """
+ INSERT INTO banks (id, name) VALUES ('bank', '招行');
+ INSERT INTO card_products (id, bank_id, bank_name, card_name, payment_due_type, payment_due_value)
+ VALUES ('product', 'bank', '招行', '经典白', 'after_billing', 20);
+ INSERT INTO card_holders (id, created_by, managed_by, name) VALUES ('holder', 'user', 'user', '测试');
+ INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day, status, card_type)
+ VALUES ('card-eom', 'holder', 'product', '3131', 31, 'active', 'credit');
+ INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day, status, card_type)
+ VALUES ('card-loan', 'holder', 'product', '9999', 28, 'active', 'loan');
+ INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day, status, card_type)
+ VALUES ('card-frozen', 'holder', 'product', '0000', 28, 'frozen', 'credit');
+ INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date)
+ VALUES ('bill-1', 'card-eom', '2026-03', 1000, '2026-03-05');
+ """)
+ }
+
+ let payables = [
+ PayableItem(
+ id: "pay-open", createdBy: "user", name: "房租", category: .rent,
+ amount: 3000, currency: "CNY", dueDay: 5, holderId: "holder",
+ period: "2026-03", dueDate: "2026-03-05", daysUntilDue: 6, paidAmount: 0, status: .unpaid
+ ),
+ PayableItem(
+ id: "pay-paid", createdBy: "user", name: "网费", category: .utility,
+ amount: 100, currency: "CNY", dueDay: 5, holderId: "holder",
+ period: "2026-03", dueDate: "2026-03-05", daysUntilDue: 6, paidAmount: 100, status: .paid
+ ),
+ ]
+
+ // 2026-02-27 Asia/Shanghai 08:00 = 2026-02-27T00:00:00Z
+ let today = instant("2026-02-27T00:00:00Z")
+ let center = NotificationCenterSpy()
+ let scheduler = NotificationScheduler(dbManager: manager, center: center)
+
+ let prefs = UserReminderPreferences(
+ remindDaysBefore: [2, 0],
+ items: NotificationItemSwitches(
+ billDueToday: false,
+ payableDueToday: true,
+ billDueAdvance: true,
+ payableDueAdvance: true,
+ gracePeriodLongest: true
+ )
+ )
+
+ try await scheduler.rescheduleAll(today: today, payables: payables, preferences: prefs)
+ let ids = center.requests.map(\.identifier)
+ #expect(!ids.contains("bill-due-bill-1"))
+ #expect(ids.contains("bill-2d-bill-1"))
+ #expect(ids.contains("payable-due-pay-open"))
+ #expect(ids.contains("payable-2d-pay-open"))
+ #expect(!ids.contains("payable-due-pay-paid"))
+ #expect(ids.contains("grace-longest-card-eom-2026-03-01"))
+ #expect(!ids.contains(where: { $0.contains("card-loan") || $0.contains("card-frozen") }))
+
+ // 关闭 gracePeriodLongest 后不再调度免息期提醒
+ var noGrace = prefs
+ noGrace.items.gracePeriodLongest = false
+ try await scheduler.rescheduleAll(today: today, payables: payables, preferences: noGrace)
+ #expect(!center.requests.map(\.identifier).contains(where: { $0.hasPrefix("grace-longest-") }))
+ }
+}
diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift
index b82cb9d..bae99dc 100644
--- a/ios/WorldCredit/AppState.swift
+++ b/ios/WorldCredit/AppState.swift
@@ -74,6 +74,7 @@ public final class AppState {
private func advanceSession() -> UUID { refreshState.advanceSession() }
@ObservationIgnored private lazy var dashboardRemote = DashboardRemoteService(apiClient: apiClient)
@ObservationIgnored private lazy var payablesService = PayablesRemoteService(apiClient: apiClient)
+ @ObservationIgnored private lazy var notificationsRemote = NotificationsRemoteService(apiClient: apiClient)
public var summary: DashboardSummary?
public var bills: [BillDisplayItem] = []
@@ -131,6 +132,23 @@ public final class AppState {
private var payableHistoryStale: Set = []
public var payablesError: String?
+ public var notifications: [UserNotificationItem] = []
+ public var unreadNotificationCount: Int = 0
+ public var totalNotificationCount: Int = 0
+ public var isLoadingNotifications: Bool = false
+ public var isLoadingMoreNotifications: Bool = false
+ public var hasMoreNotifications: Bool = false
+ public var notificationsError: String?
+ public var pendingOpenNotifications: Bool = false
+ public var pendingWebDestination: DashboardWebDestination?
+ public var reminderPreferences: UserReminderPreferences = UserReminderPreferences()
+ public var isSavingReminderPreferences: Bool = false
+ public var reminderPreferencesError: String?
+ @ObservationIgnored private var reminderPrefsRevision: Int = 0
+ @ObservationIgnored private var reminderPrefsSaveTail: Task?
+ @ObservationIgnored private var lastConfirmedReminderPreferences: UserReminderPreferences?
+ @ObservationIgnored private var currentNotificationFilter: String = "all"
+ @ObservationIgnored private let notificationPageSize = 50
/// 盘库打不开、退到内存库时的可恢复提示(数据不持久化),由 UI 展示。
public var dbInitWarning: String?
@@ -300,6 +318,10 @@ public final class AppState {
await self.refreshPayables()
guard self.refreshState.isCurrent(epoch, isLoggedIn: self.isLoggedIn) else { return false }
await self.refreshDashboardRemote()
+ guard self.refreshState.isCurrent(epoch, isLoggedIn: self.isLoggedIn) else { return false }
+ await self.refreshUnreadNotificationCount()
+ guard self.refreshState.isCurrent(epoch, isLoggedIn: self.isLoggedIn) else { return false }
+ await self.loadReminderPreferences(silent: true)
return true
},
dayRefresh: { epoch, now in
@@ -416,7 +438,9 @@ public final class AppState {
isDashboardLoading = dashboardBills.isEmpty
defer { isDashboardLoading = false }
_ = await reloadData()
+ await refreshPayables()
await refreshDashboardRemote()
+ await refreshUnreadNotificationCount()
}
public func refreshDashboardRemote() async {
@@ -589,6 +613,22 @@ public final class AppState {
payableHistoryErrors = []
payableHistoryRevision = [:]
payableHistoryStale = []
+ notifications = []
+ unreadNotificationCount = 0
+ totalNotificationCount = 0
+ isLoadingNotifications = false
+ isLoadingMoreNotifications = false
+ hasMoreNotifications = false
+ notificationsError = nil
+ pendingOpenNotifications = false
+ pendingWebDestination = nil
+ currentNotificationFilter = "all"
+ reminderPreferences = UserReminderPreferences()
+ lastConfirmedReminderPreferences = nil
+ reminderPrefsRevision += 1
+ reminderPrefsSaveTail = nil
+ isSavingReminderPreferences = false
+ reminderPreferencesError = nil
lastSyncError = nil
// 401 会话过期不走完整 logout:per-user 快照靠 owner 记录在这里补清,
// 否则下一个账号直接 login 时前任财务快照残留磁盘
@@ -673,6 +713,7 @@ public final class AppState {
} else {
Self.savePayablesSnapshot(items, userId: user.id)
}
+ try? await rescheduleLocalNotifications()
} catch is CancellationError {
return
} catch let urlError as URLError where urlError.code == .cancelled {
@@ -791,6 +832,7 @@ public final class AppState {
// 只刷新列表:refreshPayables 会清空历史缓存并标记 stale,
// 预取的结果必然被作废,交给视图按需重取
await refreshPayables()
+ await refreshUnreadNotificationCount()
}
public func savePayable(_ draft: PayableDraft, existing: PayableItem?) async throws {
@@ -887,10 +929,401 @@ public final class AppState {
}
}
+ // MARK: - Notifications & Reminder Preferences
+
+ private func rescheduleLocalNotifications() async throws {
+ try await notificationScheduler.rescheduleAll(
+ payables: payables,
+ preferences: reminderPreferences
+ )
+ }
+
+ public func refreshUnreadNotificationCount() async {
+ guard isLoggedIn, !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode"),
+ apiClient.token != nil else { return }
+ let epoch = sessionEpoch
+ let credential = apiClient.token
+ do {
+ let count = try await notificationsRemote.fetchUnreadCount()
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential else { return }
+ unreadNotificationCount = max(0, count)
+ } catch is CancellationError {
+ return
+ } catch let urlError as URLError where urlError.code == .cancelled {
+ return
+ } catch {
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential else { return }
+ if let nsError = error as NSError?, nsError.code == 401, await trySilentRefresh() {
+ await refreshUnreadNotificationCount()
+ }
+ }
+ }
+
+ public func loadNotifications(filter: String = "all", syncToday: Bool = true) async {
+ guard isLoggedIn, !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode"),
+ apiClient.token != nil else { return }
+ let epoch = sessionEpoch
+ let credential = apiClient.token
+ currentNotificationFilter = filter
+ isLoadingNotifications = true
+ isLoadingMoreNotifications = false
+ notificationsError = nil
+ defer {
+ if sessionEpoch == epoch {
+ isLoadingNotifications = false
+ }
+ }
+ do {
+ let page = try await notificationsRemote.fetchNotifications(
+ filter: filter,
+ limit: notificationPageSize,
+ offset: 0,
+ syncToday: syncToday
+ )
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential,
+ currentNotificationFilter == filter else { return }
+ notifications = page.items
+ unreadNotificationCount = max(0, page.unreadCount)
+ totalNotificationCount = max(0, page.totalCount)
+ let expectedTotal = filter == "unread" ? page.unreadCount : page.totalCount
+ hasMoreNotifications = page.items.count >= notificationPageSize && page.items.count < expectedTotal
+ } catch is CancellationError {
+ return
+ } catch let urlError as URLError where urlError.code == .cancelled {
+ return
+ } catch {
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential else { return }
+ if let nsError = error as NSError?, nsError.code == 401, await trySilentRefresh() {
+ await loadNotifications(filter: filter, syncToday: syncToday)
+ return
+ }
+ notificationsError = error.localizedDescription
+ }
+ }
+
+ public func loadMoreNotifications() async {
+ guard isLoggedIn,
+ !isLoadingNotifications,
+ !isLoadingMoreNotifications,
+ hasMoreNotifications,
+ !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode"),
+ apiClient.token != nil else { return }
+ let epoch = sessionEpoch
+ let credential = apiClient.token
+ let activeFilter = currentNotificationFilter
+ let offset = notifications.count
+ isLoadingMoreNotifications = true
+ defer {
+ if sessionEpoch == epoch {
+ isLoadingMoreNotifications = false
+ }
+ }
+ do {
+ let page = try await performWithSilentRefresh {
+ try await self.notificationsRemote.fetchNotifications(
+ filter: activeFilter,
+ limit: self.notificationPageSize,
+ offset: offset,
+ syncToday: false
+ )
+ }
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential,
+ currentNotificationFilter == activeFilter else { return }
+ var existingIds = Set(notifications.map(\.id))
+ let appended = page.items.filter { existingIds.insert($0.id).inserted }
+ notifications.append(contentsOf: appended)
+ unreadNotificationCount = max(0, page.unreadCount)
+ totalNotificationCount = max(0, page.totalCount)
+ let expectedTotal = activeFilter == "unread" ? page.unreadCount : page.totalCount
+ hasMoreNotifications = page.items.count >= notificationPageSize && notifications.count < expectedTotal
+ } catch is CancellationError {
+ return
+ } catch let urlError as URLError where urlError.code == .cancelled {
+ return
+ } catch {
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential else { return }
+ notificationsError = error.localizedDescription
+ }
+ }
+
+ public func handleNotificationRoute(_ rawUrl: String) {
+ let trimmed = rawUrl.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard trimmed.hasPrefix("/"), !trimmed.hasPrefix("//") else { return }
+ let noQuery = trimmed
+ .split(separator: "?", maxSplits: 1, omittingEmptySubsequences: false).first
+ .map(String.init) ?? trimmed
+ let path = noQuery
+ .split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false).first
+ .map(String.init) ?? noQuery
+
+ if path == "/dashboard" || path == "/" {
+ pendingWebDestination = nil
+ pendingOpenNotifications = false
+ selectedTab = 0
+ } else if path == "/notifications" {
+ pendingWebDestination = nil
+ selectedTab = 0
+ pendingOpenNotifications = true
+ } else if path == "/bills" || path.hasPrefix("/bills/") {
+ pendingWebDestination = nil
+ pendingOpenNotifications = false
+ selectedTab = 1
+ } else if path == "/cards" || path.hasPrefix("/cards/") {
+ pendingWebDestination = nil
+ pendingOpenNotifications = false
+ selectedTab = 2
+ } else if path == "/settings" {
+ pendingWebDestination = nil
+ pendingOpenNotifications = false
+ selectedTab = 3
+ } else if path == "/promos" {
+ pendingOpenNotifications = false
+ selectedTab = 0
+ pendingWebDestination = .promos
+ } else if path == "/benefits/calendar" {
+ pendingOpenNotifications = false
+ selectedTab = 0
+ pendingWebDestination = .benefitCalendar
+ } else if path == "/benefits" || path.hasPrefix("/benefits/") {
+ pendingOpenNotifications = false
+ selectedTab = 0
+ pendingWebDestination = .benefits
+ } else if path == "/gmail-ledger" {
+ pendingOpenNotifications = false
+ selectedTab = 0
+ pendingWebDestination = .gmailLedger
+ } else {
+ pendingWebDestination = nil
+ selectedTab = 0
+ pendingOpenNotifications = true
+ }
+ }
+
+ private func performWithSilentRefresh(
+ _ operation: @escaping () async throws -> T
+ ) async throws -> T {
+ do {
+ return try await operation()
+ } catch {
+ if let nsError = error as NSError?, nsError.code == 401, await trySilentRefresh() {
+ return try await operation()
+ }
+ throw error
+ }
+ }
+
+ public func markNotificationRead(_ id: String) async throws {
+ guard isLoggedIn, !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode") else { return }
+ let prevItems = notifications
+ let prevUnread = unreadNotificationCount
+ let nowIso = ISO8601DateFormatter().string(from: Date())
+ if let idx = notifications.firstIndex(where: { $0.id == id && $0.isUnread }) {
+ notifications[idx] = notifications[idx].markingRead(at: nowIso)
+ unreadNotificationCount = max(0, unreadNotificationCount - 1)
+ }
+ do {
+ let result = try await performWithSilentRefresh {
+ try await self.notificationsRemote.markRead(notificationId: id)
+ }
+ unreadNotificationCount = max(0, result.unreadCount)
+ } catch {
+ notifications = prevItems
+ unreadNotificationCount = prevUnread
+ throw error
+ }
+ }
+
+ public func markAllNotificationsRead() async throws {
+ guard isLoggedIn, !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode") else { return }
+ let prevItems = notifications
+ let prevUnread = unreadNotificationCount
+ let prevHasMore = hasMoreNotifications
+ let nowIso = ISO8601DateFormatter().string(from: Date())
+ notifications = currentNotificationFilter == "unread" ? [] : notifications.map { $0.markingRead(at: nowIso) }
+ unreadNotificationCount = 0
+ if currentNotificationFilter == "unread" {
+ hasMoreNotifications = false
+ }
+ do {
+ let result = try await performWithSilentRefresh {
+ try await self.notificationsRemote.markAllRead()
+ }
+ unreadNotificationCount = max(0, result.unreadCount)
+ } catch {
+ notifications = prevItems
+ unreadNotificationCount = prevUnread
+ hasMoreNotifications = prevHasMore
+ throw error
+ }
+ }
+
+ public func deleteNotification(_ id: String) async throws {
+ guard isLoggedIn, !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode") else { return }
+ let prevItems = notifications
+ let prevUnread = unreadNotificationCount
+ let prevTotal = totalNotificationCount
+ if let removed = notifications.first(where: { $0.id == id }) {
+ notifications.removeAll { $0.id == id }
+ totalNotificationCount = max(0, totalNotificationCount - 1)
+ if removed.isUnread {
+ unreadNotificationCount = max(0, unreadNotificationCount - 1)
+ }
+ }
+ do {
+ let result = try await performWithSilentRefresh {
+ try await self.notificationsRemote.delete(notificationId: id)
+ }
+ unreadNotificationCount = max(0, result.unreadCount)
+ } catch {
+ notifications = prevItems
+ unreadNotificationCount = prevUnread
+ totalNotificationCount = prevTotal
+ throw error
+ }
+ }
+
+ public func deleteAllNotifications() async throws {
+ guard isLoggedIn, !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode") else { return }
+ let prevItems = notifications
+ let prevUnread = unreadNotificationCount
+ let prevTotal = totalNotificationCount
+ let prevHasMore = hasMoreNotifications
+ notifications = []
+ unreadNotificationCount = 0
+ totalNotificationCount = 0
+ hasMoreNotifications = false
+ do {
+ let result = try await performWithSilentRefresh {
+ try await self.notificationsRemote.deleteAll()
+ }
+ unreadNotificationCount = max(0, result.unreadCount)
+ } catch {
+ notifications = prevItems
+ unreadNotificationCount = prevUnread
+ totalNotificationCount = prevTotal
+ hasMoreNotifications = prevHasMore
+ throw error
+ }
+ }
+
+ public func loadReminderPreferences(silent: Bool = false) async {
+ guard isLoggedIn, !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode"),
+ apiClient.token != nil else { return }
+ let epoch = sessionEpoch
+ let credential = apiClient.token
+ do {
+ let user: SessionUser
+ if let currentUser { user = currentUser }
+ else { user = try await apiClient.fetchSessionUser() }
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential else { return }
+ currentUser = user
+ let prefs = try await notificationsRemote.fetchReminderPreferences(userId: user.id)
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential,
+ currentUser?.id == user.id else { return }
+ reminderPreferences = prefs
+ lastConfirmedReminderPreferences = prefs
+ reminderPreferencesError = nil
+ try? await rescheduleLocalNotifications()
+ } catch is CancellationError {
+ return
+ } catch let urlError as URLError where urlError.code == .cancelled {
+ return
+ } catch {
+ guard isLoggedIn, sessionEpoch == epoch, apiClient.token == credential else { return }
+ if let nsError = error as NSError?, nsError.code == 401, await trySilentRefresh() {
+ await loadReminderPreferences(silent: silent)
+ return
+ }
+ if !silent {
+ reminderPreferencesError = error.localizedDescription
+ }
+ }
+ }
+
+ public func updateReminderPreferences(_ next: UserReminderPreferences) async throws {
+ guard isLoggedIn, !UITestConfiguration.isEnabled,
+ !CommandLine.arguments.contains("--demo-mode") else {
+ reminderPreferences = next
+ lastConfirmedReminderPreferences = next
+ return
+ }
+ reminderPrefsRevision += 1
+ let rev = reminderPrefsRevision
+ let epoch = sessionEpoch
+ let initialSnapshot = reminderPreferences
+ let prevTail = reminderPrefsSaveTail
+
+ reminderPreferences = next
+ isSavingReminderPreferences = true
+ reminderPreferencesError = nil
+
+ let saveTask = Task { @MainActor [weak self] in
+ if let prevTail {
+ _ = await prevTail.value
+ }
+ guard let self else { throw CancellationError() }
+ let fallback = self.lastConfirmedReminderPreferences ?? initialSnapshot
+
+ defer {
+ if rev == self.reminderPrefsRevision && self.sessionEpoch == epoch {
+ self.isSavingReminderPreferences = false
+ }
+ }
+
+ guard self.isLoggedIn, self.sessionEpoch == epoch else {
+ throw CancellationError()
+ }
+
+ do {
+ let (user, saved) = try await self.performWithSilentRefresh {
+ let resolvedUser: SessionUser
+ if let currentUser = self.currentUser {
+ resolvedUser = currentUser
+ } else {
+ resolvedUser = try await self.apiClient.fetchSessionUser()
+ }
+ self.currentUser = resolvedUser
+ let updated = try await self.notificationsRemote.updateReminderPreferences(
+ userId: resolvedUser.id,
+ config: next
+ )
+ return (resolvedUser, updated)
+ }
+ if self.isLoggedIn, self.sessionEpoch == epoch, self.currentUser?.id == user.id {
+ self.lastConfirmedReminderPreferences = saved
+ if rev == self.reminderPrefsRevision {
+ self.reminderPreferences = saved
+ try? await self.rescheduleLocalNotifications()
+ }
+ }
+ } catch {
+ if self.sessionEpoch == epoch && rev == self.reminderPrefsRevision {
+ self.reminderPreferences = fallback
+ self.reminderPreferencesError = error.localizedDescription
+ }
+ throw error
+ }
+ }
+
+ reminderPrefsSaveTail = Task {
+ _ = try? await saveTask.value
+ }
+
+ try await saveTask.value
+ }
+
public func payDashboardBills(_ ids: [String]) async throws -> Int {
let count = try await paymentService.recordFullPayments(billIds: ids)
await reloadData()
- do { try await notificationScheduler.rescheduleAll() }
+ do { try await rescheduleLocalNotifications() }
catch { lastSyncError = "还款已保存,提醒更新失败:\(error.localizedDescription)" }
Task { await self.sync() }
return count
@@ -952,7 +1385,7 @@ public final class AppState {
do {
try await syncEngine.sync()
guard isLoggedIn, sessionEpoch == epoch else { return }
- try await notificationScheduler.rescheduleAll()
+ try await rescheduleLocalNotifications()
guard await reloadData() else {
throw NSError(domain: "WorldCredit.Sync", code: 1,
userInfo: [NSLocalizedDescriptionKey: "同步后刷新本地数据失败"])
@@ -1047,6 +1480,22 @@ public final class AppState {
payableHistoryErrors = []
payableHistoryRevision = [:]
payableHistoryStale = []
+ notifications = []
+ unreadNotificationCount = 0
+ totalNotificationCount = 0
+ isLoadingNotifications = false
+ isLoadingMoreNotifications = false
+ hasMoreNotifications = false
+ notificationsError = nil
+ pendingOpenNotifications = false
+ pendingWebDestination = nil
+ currentNotificationFilter = "all"
+ reminderPreferences = UserReminderPreferences()
+ lastConfirmedReminderPreferences = nil
+ reminderPrefsRevision += 1
+ reminderPrefsSaveTail = nil
+ isSavingReminderPreferences = false
+ reminderPreferencesError = nil
notificationScheduler.center.removeAllPendingNotificationRequests()
watchSnapshots.clear()
let emptySnapshot = WatchSnapshot(
@@ -1140,7 +1589,7 @@ public final class AppState {
// Refresh local UI immediately
await reloadData()
do {
- try await notificationScheduler.rescheduleAll()
+ try await rescheduleLocalNotifications()
} catch {
lastSyncError = "本地修改已保存,提醒更新失败:\(error.localizedDescription)"
print("提醒更新失败:\(error)")
@@ -1156,7 +1605,7 @@ public final class AppState {
try await billEditService.setBillAmountOverride(billId: billId, amount: amount)
await reloadData()
do {
- try await notificationScheduler.rescheduleAll()
+ try await rescheduleLocalNotifications()
} catch {
lastSyncError = "本地修改已保存,提醒更新失败:\(error.localizedDescription)"
print("提醒更新失败:\(error)")
diff --git a/ios/WorldCredit/PushNotificationManager.swift b/ios/WorldCredit/PushNotificationManager.swift
index a01d491..aabff73 100644
--- a/ios/WorldCredit/PushNotificationManager.swift
+++ b/ios/WorldCredit/PushNotificationManager.swift
@@ -116,4 +116,16 @@ extension PushNotificationManager: UNUserNotificationCenterDelegate {
) {
completionHandler([.banner, .badge, .sound, .list])
}
+
+ public nonisolated func userNotificationCenter(
+ _ center: UNUserNotificationCenter,
+ didReceive response: UNNotificationResponse,
+ withCompletionHandler completionHandler: @escaping () -> Void
+ ) {
+ let rawUrl = (response.notification.request.content.userInfo["url"] as? String) ?? "/notifications"
+ Task { @MainActor in
+ PushNotificationManager.shared.appState?.handleNotificationRoute(rawUrl)
+ }
+ completionHandler()
+ }
}
diff --git a/ios/WorldCredit/Views/DashboardView.swift b/ios/WorldCredit/Views/DashboardView.swift
index 6fefde7..1ace3b3 100644
--- a/ios/WorldCredit/Views/DashboardView.swift
+++ b/ios/WorldCredit/Views/DashboardView.swift
@@ -9,6 +9,7 @@ struct DashboardView: View {
@State private var debtExpanded = false
@State private var showPayAllConfirm = false
@State private var webDestination: DashboardWebDestination?
+ @State private var showPushNotificationsCenter = false
private let futureOptions = [7, 14, 30]
@@ -34,6 +35,18 @@ struct DashboardView: View {
.navigationDestination(for: BillDetailRoute.self) { route in
BillDetailView(item: route.item)
}
+ .navigationDestination(isPresented: $showPushNotificationsCenter) {
+ NotificationsCenterView()
+ }
+ .onAppear {
+ consumePendingNotificationRoutes()
+ }
+ .onChange(of: appState.pendingOpenNotifications) { _, _ in
+ consumePendingNotificationRoutes()
+ }
+ .onChange(of: appState.pendingWebDestination) { _, _ in
+ consumePendingNotificationRoutes()
+ }
.refreshable { await appState.refreshDashboard() }
.task { await appState.loadInitialDataIfNeeded() }
.sheet(item: $payingItem) { item in
@@ -80,12 +93,24 @@ struct DashboardView: View {
holderId: holderFilter,
futureDays: futureDays,
displayCurrency: appState.dashboardCurrency,
- rates: appState.dashboardRates
+ rates: appState.dashboardRates,
+ payables: appState.payables
)
}
private var currency: String { appState.dashboardCurrency }
+ private func consumePendingNotificationRoutes() {
+ if appState.pendingOpenNotifications {
+ appState.pendingOpenNotifications = false
+ showPushNotificationsCenter = true
+ }
+ if let dest = appState.pendingWebDestination {
+ appState.pendingWebDestination = nil
+ webDestination = dest
+ }
+ }
+
// MARK: - 金额
private func money(_ amount: Double, billCurrency: String? = nil) -> some View {
@@ -111,6 +136,29 @@ struct DashboardView: View {
.font(.headline)
}
Spacer()
+ NavigationLink {
+ NotificationsCenterView()
+ } label: {
+ ZStack(alignment: .topTrailing) {
+ Image(systemName: appState.unreadNotificationCount > 0 ? "bell.badge" : "bell")
+ .font(.title3)
+ .frame(width: 44, height: 44)
+ .background(Color(uiColor: .secondarySystemGroupedBackground), in: Circle())
+ if appState.unreadNotificationCount > 0 {
+ Text(appState.unreadNotificationCount > 99 ? "99+" : "\(appState.unreadNotificationCount)")
+ .font(.caption2.bold())
+ .foregroundStyle(.white)
+ .padding(.horizontal, 5)
+ .padding(.vertical, 1)
+ .background(Color.red, in: Capsule())
+ .offset(x: 4, y: -2)
+ }
+ }
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("通知中心,\(appState.unreadNotificationCount) 条未读")
+ .accessibilityIdentifier("dashboard.notifications")
+
Button {
Task { await appState.setDashboardPrivacy(!appState.dashboardPrivacy) }
} label: {
@@ -130,19 +178,29 @@ struct DashboardView: View {
.font(.system(size: 36, weight: .bold, design: .rounded))
.accessibilityIdentifier("dashboard.totalDebt")
- HStack(spacing: 24) {
+ HStack(spacing: 16) {
VStack(spacing: 2) {
Text("含逾期").font(.caption).foregroundStyle(.secondary)
money(metrics.overdueAmount)
.font(.subheadline.bold())
.foregroundStyle(.red)
}
+ .frame(maxWidth: .infinity)
+ VStack(spacing: 2) {
+ Text("当日待还").font(.caption).foregroundStyle(.secondary)
+ money(metrics.dueTodayAmount)
+ .font(.subheadline.bold())
+ .foregroundStyle(.orange)
+ .accessibilityIdentifier("dashboard.dueTodayAmount")
+ }
+ .frame(maxWidth: .infinity)
VStack(spacing: 2) {
Text("未来 \(futureDays) 天").font(.caption).foregroundStyle(.secondary)
money(metrics.futureAmount)
.font(.subheadline.bold())
.foregroundStyle(.orange)
}
+ .frame(maxWidth: .infinity)
}
if !metrics.unconvertedCurrencies.isEmpty {
@@ -354,13 +412,22 @@ struct DashboardView: View {
private var dueTodaySection: some View {
Group {
- if !metrics.dueTodayBills.isEmpty {
+ if metrics.dueTodayCount > 0 {
VStack(alignment: .leading, spacing: 10) {
HStack {
Text("今天需还款").font(.headline)
Spacer()
- Text("\(metrics.dueTodayBills.count) 笔")
- .font(.caption.bold()).foregroundStyle(.orange)
+ HStack(spacing: 4) {
+ Text("当日待还")
+ .font(.caption)
+ .foregroundStyle(.orange)
+ money(metrics.dueTodayAmount)
+ .font(.caption.bold())
+ .foregroundStyle(.orange)
+ Text("· \(metrics.dueTodayCount) 笔")
+ .font(.caption.bold())
+ .foregroundStyle(.orange)
+ }
}
ForEach(metrics.dueTodayBills) { item in
HStack {
@@ -385,6 +452,45 @@ struct DashboardView: View {
.background(Color(uiColor: .secondarySystemGroupedBackground))
.clipShape(RoundedRectangle(cornerRadius: 12))
}
+ ForEach(metrics.dueTodayPayables) { item in
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ Text(item.name)
+ .font(.subheadline.bold())
+ Text(item.category.label)
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 2)
+ .background(Color(uiColor: .tertiarySystemGroupedBackground), in: Capsule())
+ }
+ HStack(spacing: 4) {
+ Text("今日应付 ·")
+ .font(.caption).foregroundStyle(.orange)
+ money(item.remainingAmount, billCurrency: item.currency)
+ .font(.caption.bold()).foregroundStyle(.orange)
+ }
+ }
+ Spacer()
+ Button("标记已付") {
+ Task {
+ do {
+ try await appState.payPayable(item, amount: item.remainingAmount)
+ } catch {
+ appState.lastSyncError = error.localizedDescription
+ }
+ }
+ }
+ .font(.caption.bold())
+ .buttonStyle(.borderedProminent)
+ .tint(.orange)
+ .accessibilityIdentifier("dashboard.dueToday.payable.\(item.id)")
+ }
+ .padding()
+ .background(Color(uiColor: .secondarySystemGroupedBackground))
+ .clipShape(RoundedRectangle(cornerRadius: 12))
+ }
}
}
}
diff --git a/ios/WorldCredit/Views/NotificationSettingsView.swift b/ios/WorldCredit/Views/NotificationSettingsView.swift
new file mode 100644
index 0000000..79d8faf
--- /dev/null
+++ b/ios/WorldCredit/Views/NotificationSettingsView.swift
@@ -0,0 +1,226 @@
+import SwiftUI
+import WorldCreditCore
+
+struct NotificationSettingsView: View {
+ @Environment(AppState.self) private var appState
+ @State private var saveError: String?
+
+ private let advanceDayChoices = [7, 5, 3, 2, 1, 0]
+
+ private enum QuietPreset: String, CaseIterable, Identifiable {
+ case off = "off"
+ case night22 = "22:00-08:00"
+ case night23 = "23:00-07:00"
+ case night21 = "21:00-09:00"
+
+ var id: String { rawValue }
+
+ var title: String {
+ switch self {
+ case .off: return "关闭免打扰"
+ case .night22: return "22:00 - 08:00"
+ case .night23: return "23:00 - 07:00"
+ case .night21: return "21:00 - 09:00"
+ }
+ }
+
+ var bounds: (String?, String?) {
+ switch self {
+ case .off: return (nil, nil)
+ case .night22: return ("22:00", "08:00")
+ case .night23: return ("23:00", "07:00")
+ case .night21: return ("21:00", "09:00")
+ }
+ }
+ }
+
+ var body: some View {
+ List {
+ if let err = saveError ?? appState.reminderPreferencesError {
+ Section {
+ HStack(spacing: 8) {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .foregroundStyle(.red)
+ Text(err)
+ .font(.caption)
+ .foregroundStyle(.red)
+ }
+ }
+ }
+
+ Section {
+ Toggle("当日待还信用卡账单", isOn: itemBinding(\.billDueToday))
+ Toggle("当日待还固定支出", isOn: itemBinding(\.payableDueToday))
+ Toggle("今日新增最长免息期账单", isOn: itemBinding(\.gracePeriodLongest))
+ Toggle("账单还款日前提前提醒", isOn: itemBinding(\.billDueAdvance))
+ Toggle("固定支出提前提醒", isOn: itemBinding(\.payableDueAdvance))
+ Toggle("逾期账单提醒", isOn: itemBinding(\.billOverdue))
+ } header: {
+ Text("账单与固定支出通知")
+ } footer: {
+ Text("支持独立关闭或开启任意通知项;最长免息期会在账单日次日主动提醒。")
+ }
+
+ Section {
+ Toggle("启用权益提醒", isOn: Binding(
+ get: { appState.reminderPreferences.opportunities.enabled },
+ set: { enabled in
+ var next = appState.reminderPreferences
+ next.opportunities.enabled = enabled
+ persist(next)
+ }
+ ))
+
+ let oppDisabled = !appState.reminderPreferences.opportunities.enabled
+ Toggle("权益到期提醒", isOn: itemBinding(\.opportunityExpiry))
+ .disabled(oppDisabled)
+ Toggle("权益领取截止提醒", isOn: itemBinding(\.opportunityClaim))
+ .disabled(oppDisabled)
+ Toggle("优惠活动提醒", isOn: itemBinding(\.opportunityActivity))
+ .disabled(oppDisabled)
+ Toggle("达标任务提醒", isOn: itemBinding(\.opportunityTask))
+ .disabled(oppDisabled)
+ Toggle("权益周期重置提醒", isOn: itemBinding(\.opportunityReset) { next, val in
+ next.opportunities.resetEnabled = val
+ })
+ .disabled(oppDisabled)
+ Toggle("预约服务提醒", isOn: itemBinding(\.opportunityBooking) { next, val in
+ next.opportunities.bookingEnabled = val
+ })
+ .disabled(oppDisabled)
+ } header: {
+ Text("权益与活动通知")
+ }
+
+ Section {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 8) {
+ ForEach(advanceDayChoices, id: \.self) { day in
+ let selected = appState.reminderPreferences.remindDaysBefore.contains(day)
+ Button {
+ toggleAdvanceDay(day)
+ } label: {
+ Text(day == 0 ? "到期当天" : "提前 \(day) 天")
+ .font(.caption.bold())
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background(
+ selected ? Color.accentColor : Color(uiColor: .tertiarySystemGroupedBackground),
+ in: Capsule()
+ )
+ .foregroundStyle(selected ? .white : .primary)
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(.vertical, 4)
+ }
+ } header: {
+ Text("提前提醒天数")
+ }
+
+ Section {
+ Toggle("推送通道(Web Push / 站外推送)", isOn: Binding(
+ get: { appState.reminderPreferences.webPushChannelEnabled },
+ set: { enabled in
+ var next = appState.reminderPreferences
+ var channels = next.enabledChannels.filter { $0 != "web_push" }
+ if enabled {
+ channels.insert("web_push", at: 0)
+ }
+ next.enabledChannels = channels
+ next.opportunities.webPushEnabled = enabled
+ persist(next)
+ }
+ ))
+
+ Picker("免打扰时段", selection: quietPresetBinding) {
+ ForEach(QuietPreset.allCases) { preset in
+ Text(preset.title).tag(preset)
+ }
+ }
+ } header: {
+ Text("推送通道与免打扰")
+ } footer: {
+ if let start = appState.reminderPreferences.quietHoursStart,
+ let end = appState.reminderPreferences.quietHoursEnd {
+ Text("当前免打扰时段:\(start) - \(end)(仍会保留站内通知中心记录)。")
+ } else {
+ Text("当前未开启免打扰,将在触发时段正常下发推送。")
+ }
+ }
+ }
+ .listStyle(.insetGrouped)
+ .navigationTitle("通知与提醒开关")
+ .toolbar {
+ ToolbarItem(placement: .topBarTrailing) {
+ if appState.isSavingReminderPreferences {
+ ProgressView()
+ }
+ }
+ }
+ .task {
+ await appState.loadReminderPreferences()
+ }
+ }
+
+ private func itemBinding(
+ _ keyPath: WritableKeyPath,
+ onUpdate: ((inout UserReminderPreferences, Bool) -> Void)? = nil
+ ) -> Binding {
+ Binding(
+ get: { appState.reminderPreferences.items[keyPath: keyPath] },
+ set: { newValue in
+ var next = appState.reminderPreferences
+ next.items[keyPath: keyPath] = newValue
+ onUpdate?(&next, newValue)
+ persist(next)
+ }
+ )
+ }
+
+ private var quietPresetBinding: Binding {
+ Binding(
+ get: {
+ let s = appState.reminderPreferences.quietHoursStart
+ let e = appState.reminderPreferences.quietHoursEnd
+ if s == nil || e == nil { return .off }
+ switch "\(s!)-\(e!)" {
+ case "23:00-07:00": return .night23
+ case "21:00-09:00": return .night21
+ default: return .night22
+ }
+ },
+ set: { preset in
+ var next = appState.reminderPreferences
+ let (start, end) = preset.bounds
+ next.quietHoursStart = start
+ next.quietHoursEnd = end
+ persist(next)
+ }
+ )
+ }
+
+ private func toggleAdvanceDay(_ day: Int) {
+ var days = Set(appState.reminderPreferences.remindDaysBefore)
+ if days.contains(day) {
+ days.remove(day)
+ } else {
+ days.insert(day)
+ }
+ var next = appState.reminderPreferences
+ next.remindDaysBefore = Array(days).sorted(by: >)
+ persist(next)
+ }
+
+ private func persist(_ next: UserReminderPreferences) {
+ saveError = nil
+ Task {
+ do {
+ try await appState.updateReminderPreferences(next)
+ } catch {
+ saveError = "保存失败,已恢复原设置:\(error.localizedDescription)"
+ }
+ }
+ }
+}
diff --git a/ios/WorldCredit/Views/NotificationsCenterView.swift b/ios/WorldCredit/Views/NotificationsCenterView.swift
new file mode 100644
index 0000000..7f4e115
--- /dev/null
+++ b/ios/WorldCredit/Views/NotificationsCenterView.swift
@@ -0,0 +1,394 @@
+import SwiftUI
+import WorldCreditCore
+
+struct NotificationsCenterView: View {
+ @Environment(AppState.self) private var appState
+ @Environment(\.dismiss) private var dismiss
+ @State private var filter: String = "all"
+ @State private var selectedNotification: UserNotificationItem?
+ @State private var showingDeleteAllConfirm = false
+ @State private var actionError: String?
+ @State private var hasSyncedToday = false
+
+ var body: some View {
+ List {
+ if let err = actionError ?? appState.notificationsError {
+ Section {
+ HStack(spacing: 8) {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .foregroundStyle(.red)
+ Text(err)
+ .font(.caption)
+ .foregroundStyle(.red)
+ }
+ }
+ }
+
+ Section {
+ Picker("筛选", selection: $filter) {
+ Text("全部").tag("all")
+ Text("未读 (\(appState.unreadNotificationCount))").tag("unread")
+ }
+ .pickerStyle(.segmented)
+ .listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
+ }
+
+ Section {
+ if appState.isLoadingNotifications && appState.notifications.isEmpty {
+ HStack {
+ Spacer()
+ ProgressView("正在加载通知…")
+ Spacer()
+ }
+ .padding(.vertical, 24)
+ } else if appState.notifications.isEmpty {
+ ContentUnavailableView(
+ filter == "unread" ? "暂无未读通知" : "暂无通知记录",
+ systemImage: "bell.slash",
+ description: Text(filter == "unread" ? "所有主动提醒与账单动态均已阅读。" : "当日待还与免息期通知会在生成后出现在这里。")
+ )
+ .padding(.vertical, 16)
+ } else {
+ ForEach(appState.notifications) { item in
+ Button {
+ openNotification(item)
+ } label: {
+ notificationRow(item)
+ }
+ .buttonStyle(.plain)
+ .swipeActions(edge: .trailing, allowsFullSwipe: true) {
+ Button(role: .destructive) {
+ Task { await performDelete(item.id) }
+ } label: {
+ Label("删除", systemImage: "trash")
+ }
+ }
+ .swipeActions(edge: .leading, allowsFullSwipe: true) {
+ if item.isUnread {
+ Button {
+ Task { await performMarkRead(item.id) }
+ } label: {
+ Label("已读", systemImage: "checkmark.circle")
+ }
+ .tint(.accentColor)
+ }
+ }
+ }
+
+ if appState.hasMoreNotifications {
+ Button {
+ Task { await appState.loadMoreNotifications() }
+ } label: {
+ HStack {
+ Spacer()
+ if appState.isLoadingMoreNotifications {
+ ProgressView()
+ .padding(.trailing, 6)
+ Text("正在加载更多…")
+ } else {
+ Text("加载更多")
+ }
+ Spacer()
+ }
+ }
+ .disabled(appState.isLoadingMoreNotifications)
+ }
+ }
+ } header: {
+ if appState.totalNotificationCount > 0 {
+ Text("共 \(appState.totalNotificationCount) 条通知 · \(appState.unreadNotificationCount) 条未读")
+ }
+ }
+ }
+ .listStyle(.insetGrouped)
+ .navigationTitle("通知中心")
+ .toolbar {
+ ToolbarItemGroup(placement: .topBarTrailing) {
+ Button {
+ Task { await performMarkAllRead() }
+ } label: {
+ Image(systemName: "checkmark.circle")
+ }
+ .disabled(appState.unreadNotificationCount == 0)
+ .accessibilityLabel("全部已读")
+
+ Button(role: .destructive) {
+ showingDeleteAllConfirm = true
+ } label: {
+ Image(systemName: "trash")
+ }
+ .disabled(appState.notifications.isEmpty && appState.totalNotificationCount == 0)
+ .accessibilityLabel("全部删除")
+
+ NavigationLink {
+ NotificationSettingsView()
+ } label: {
+ Image(systemName: "gearshape")
+ }
+ .accessibilityLabel("通知开关设置")
+ }
+ }
+ .refreshable {
+ hasSyncedToday = true
+ await appState.loadNotifications(filter: filter, syncToday: true)
+ }
+ .task(id: filter) {
+ let shouldSync = !hasSyncedToday
+ await appState.loadNotifications(filter: filter, syncToday: shouldSync)
+ if appState.notificationsError == nil {
+ hasSyncedToday = true
+ }
+ }
+ .sheet(item: $selectedNotification) { item in
+ notificationDetailSheet(item)
+ }
+ .confirmationDialog("确定删除全部通知?", isPresented: $showingDeleteAllConfirm, titleVisibility: .visible) {
+ Button("全部删除", role: .destructive) {
+ Task { await performDeleteAll() }
+ }
+ Button("取消", role: .cancel) {}
+ } message: {
+ Text("删除后将清空通知中心历史记录,且当日已删通知不会重新弹出。")
+ }
+ }
+
+ private func notificationRow(_ item: UserNotificationItem) -> some View {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 8) {
+ if item.isUnread {
+ Circle()
+ .fill(Color.accentColor)
+ .frame(width: 8, height: 8)
+ }
+ Text(item.category.label)
+ .font(.caption2.bold())
+ .foregroundStyle(toneColor(item.category.tone))
+ .padding(.horizontal, 6)
+ .padding(.vertical, 2)
+ .background(toneColor(item.category.tone).opacity(0.14), in: Capsule())
+ Spacer()
+ Text(formatSentTime(item.sentAt, full: false))
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ }
+
+ Text(item.title)
+ .font(.subheadline.weight(item.isUnread ? .semibold : .regular))
+ .foregroundStyle(.primary)
+
+ if let body = item.body, !body.isEmpty {
+ Text(body)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(2)
+ }
+ }
+ .padding(.vertical, 4)
+ .opacity(item.isUnread ? 1.0 : 0.78)
+ }
+
+ private func notificationDetailSheet(_ item: UserNotificationItem) -> some View {
+ NavigationStack {
+ List {
+ Section {
+ HStack {
+ Text(item.category.label)
+ .font(.caption.bold())
+ .foregroundStyle(toneColor(item.category.tone))
+ .padding(.horizontal, 8)
+ .padding(.vertical, 4)
+ .background(toneColor(item.category.tone).opacity(0.14), in: Capsule())
+ Spacer()
+ Text(formatSentTime(item.sentAt, full: true))
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+
+ Text(item.title)
+ .font(.headline)
+ .textSelection(.enabled)
+
+ if let body = item.body, !body.isEmpty {
+ Text(body)
+ .font(.body)
+ .foregroundStyle(.primary)
+ .textSelection(.enabled)
+ }
+ }
+
+ if let meta = item.parsedMetadata {
+ if let totals = meta.totalsByCurrency, !totals.isEmpty {
+ Section("分币种合计") {
+ ForEach(totals.sorted(by: { $0.key < $1.key }), id: \.key) { code, amount in
+ LabeledContent(code, value: DashboardMoney.format(amount, currency: code))
+ }
+ }
+ }
+
+ if let bills = meta.bills, !bills.isEmpty {
+ Section("涉及账单") {
+ ForEach(bills) { bill in
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(bill.subject).font(.subheadline.bold())
+ Text("到期日:\(bill.dueDate)").font(.caption).foregroundStyle(.secondary)
+ }
+ Spacer()
+ Text(DashboardMoney.format(bill.remaining, currency: bill.currency))
+ .font(.subheadline.bold())
+ }
+ }
+ }
+ }
+
+ if let payables = meta.payables, !payables.isEmpty {
+ Section("涉及固定支出") {
+ ForEach(payables) { payable in
+ HStack {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("\(payable.name) · \(payable.category)").font(.subheadline.bold())
+ Text("应付日:\(payable.dueDate)").font(.caption).foregroundStyle(.secondary)
+ }
+ Spacer()
+ Text(DashboardMoney.format(payable.remaining, currency: payable.currency))
+ .font(.subheadline.bold())
+ }
+ }
+ }
+ }
+
+ if let cards = meta.cards, !cards.isEmpty {
+ Section("最长免息期明细") {
+ ForEach(cards) { card in
+ VStack(alignment: .leading, spacing: 4) {
+ HStack {
+ Text(card.label).font(.subheadline.bold())
+ Spacer()
+ Text("最长 \(card.graceDays) 天")
+ .font(.caption.bold())
+ .foregroundStyle(.orange)
+ }
+ Text("下期账单日 \(card.nextBillingDate) · 还款日 \(card.nextDueDate)")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ }
+ }
+ }
+
+ Section {
+ if let targetUrl = item.targetUrl,
+ targetUrl.hasPrefix("/"),
+ !targetUrl.hasPrefix("//") {
+ Button {
+ selectedNotification = nil
+ appState.handleNotificationRoute(targetUrl)
+ let cleanPath = targetUrl
+ .split(separator: "?", maxSplits: 1, omittingEmptySubsequences: false).first
+ .map(String.init) ?? targetUrl
+ if cleanPath != "/notifications" {
+ dismiss()
+ }
+ } label: {
+ Label("前往查看", systemImage: "arrow.up.right.square")
+ }
+ }
+ if item.isUnread {
+ Button("标记为已读") {
+ Task {
+ await performMarkRead(item.id)
+ selectedNotification = item.markingRead(at: ISO8601DateFormatter().string(from: Date()))
+ }
+ }
+ }
+ Button("删除此通知", role: .destructive) {
+ let deletingId = item.id
+ selectedNotification = nil
+ Task { await performDelete(deletingId) }
+ }
+ }
+ }
+ .listStyle(.insetGrouped)
+ .navigationTitle("通知详情")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ Button("完成") { selectedNotification = nil }
+ }
+ }
+ }
+ }
+
+ private func openNotification(_ item: UserNotificationItem) {
+ if item.isUnread {
+ selectedNotification = item.markingRead(at: ISO8601DateFormatter().string(from: Date()))
+ Task { await performMarkRead(item.id) }
+ } else {
+ selectedNotification = item
+ }
+ }
+
+ private func performMarkRead(_ id: String) async {
+ actionError = nil
+ do {
+ try await appState.markNotificationRead(id)
+ if filter == "unread" {
+ await appState.loadNotifications(filter: "unread", syncToday: false)
+ }
+ } catch {
+ actionError = "标记已读失败:\(error.localizedDescription)"
+ }
+ }
+
+ private func performMarkAllRead() async {
+ actionError = nil
+ do {
+ try await appState.markAllNotificationsRead()
+ if filter == "unread" {
+ await appState.loadNotifications(filter: "unread", syncToday: false)
+ }
+ } catch {
+ actionError = "全部已读失败:\(error.localizedDescription)"
+ }
+ }
+
+ private func performDelete(_ id: String) async {
+ actionError = nil
+ do {
+ try await appState.deleteNotification(id)
+ } catch {
+ actionError = "删除失败:\(error.localizedDescription)"
+ }
+ }
+
+ private func performDeleteAll() async {
+ actionError = nil
+ do {
+ try await appState.deleteAllNotifications()
+ } catch {
+ actionError = "全部删除失败:\(error.localizedDescription)"
+ }
+ }
+
+ private func toneColor(_ tone: NotificationCategoryTone) -> Color {
+ switch tone {
+ case .danger: return .red
+ case .gold: return .orange
+ case .accent: return .accentColor
+ case .muted: return .secondary
+ }
+ }
+
+ private func formatSentTime(_ iso: String, full: Bool) -> String {
+ let isoFormatter = ISO8601DateFormatter()
+ isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ guard let date = isoFormatter.date(from: iso) ?? ISO8601DateFormatter().date(from: iso) else {
+ return String(iso.prefix(16)).replacingOccurrences(of: "T", with: " ")
+ }
+ let df = DateFormatter()
+ df.timeZone = TimeZone(identifier: "Asia/Shanghai") ?? .current
+ df.dateFormat = full ? "yyyy-MM-dd HH:mm" : "MM-dd HH:mm"
+ return df.string(from: date)
+ }
+}
diff --git a/ios/WorldCredit/Views/SettingsView.swift b/ios/WorldCredit/Views/SettingsView.swift
index 2c63bda..cc1a2e7 100644
--- a/ios/WorldCredit/Views/SettingsView.swift
+++ b/ios/WorldCredit/Views/SettingsView.swift
@@ -72,6 +72,31 @@ struct SettingsView: View {
GmailSyncSection()
+ Section("通知与提醒") {
+ NavigationLink {
+ NotificationsCenterView()
+ } label: {
+ HStack {
+ Label("通知中心", systemImage: "bell")
+ Spacer()
+ if appState.unreadNotificationCount > 0 {
+ Text("\(appState.unreadNotificationCount)")
+ .font(.caption.bold())
+ .foregroundStyle(.white)
+ .padding(.horizontal, 7)
+ .padding(.vertical, 2)
+ .background(Color.red, in: Capsule())
+ }
+ }
+ }
+
+ NavigationLink {
+ NotificationSettingsView()
+ } label: {
+ Label("通知与提醒开关", systemImage: "slider.horizontal.3")
+ }
+ }
+
Section("外观与主题") {
Picker("主题模式", selection: Binding(
get: { appState.themeMode },
diff --git a/lib/__tests__/bill-amount-override.test.ts b/lib/__tests__/bill-amount-override.test.ts
index c117c1f..75c6e17 100644
--- a/lib/__tests__/bill-amount-override.test.ts
+++ b/lib/__tests__/bill-amount-override.test.ts
@@ -109,12 +109,16 @@ describe("读路径统一按生效金额投影", () => {
"lib/api/cards.server.ts",
"lib/api/holders.server.ts",
"lib/api/analytics.server.ts",
- "worker/cron.ts",
+ "lib/notifications-engine.server.ts",
])("%s 在 SQL 层做 COALESCE(bill_amount_override, bill_amount)", (rel) => {
// 允许表别名前缀(joins 里写成 b.bill_amount_override)
expect(read(rel)).toMatch(/COALESCE\(\w*\.?bill_amount_override,\s*\w*\.?bill_amount\)/);
});
+ it("worker/cron.ts 委托 lib/notifications-engine.server.ts 生成当日通知候选", () => {
+ expect(read("worker/cron.ts")).toMatch(/buildDailyNotificationCandidates/);
+ });
+
it("还款校验用生效金额(否则手填 800 却按导入 1200 拒绝还款)", () => {
const server = read("lib/api/bills.server.ts");
expect(server).toMatch(/const billAmount = effectiveBillAmount\(bill\)/);
diff --git a/lib/__tests__/card-override-coverage.test.ts b/lib/__tests__/card-override-coverage.test.ts
index 35ae1fe..2a0ae31 100644
--- a/lib/__tests__/card-override-coverage.test.ts
+++ b/lib/__tests__/card-override-coverage.test.ts
@@ -56,12 +56,14 @@ describe('账单/卡片查询必须携带卡级别覆盖列', () => {
})
describe('推送与提醒路径必须优先使用卡级别名称', () => {
- it('每日推送 cron 选中并优先使用 name_override', () => {
+ it('每日推送 cron 经 notifications-engine 选中并优先使用 name_override', () => {
const cron = read('worker/cron.ts')
- expect(cron, 'cron 没查 name_override,推送标题会显示卡产品原名').toMatch(/cc\.name_override/)
- expect(cron).toMatch(/name_override \|\|/)
- // 标题里的三个分支都要用生效名,不能残留 bill.card_name
- expect(cron).not.toMatch(/\$\{bill\.card_name \|\| ''\}/)
+ expect(cron).toMatch(/buildDailyNotificationCandidates/)
+ const engine = read('lib/notifications-engine.server.ts')
+ expect(engine, 'cron 通知引擎没查 name_override,推送标题会显示卡产品原名').toMatch(/cc\.name_override/)
+ expect(engine).toMatch(/name_override \|\|/)
+ // 标题里的分支都要用生效名,不能残留 bill.card_name
+ expect(engine).not.toMatch(/\$\{bill\.card_name \|\| ''\}/)
})
it('站内提醒的两条查询都带 name_override,且消费端优先取它', () => {
diff --git a/lib/__tests__/dashboard-metrics.test.ts b/lib/__tests__/dashboard-metrics.test.ts
index 67a0ce3..ed0fc1f 100644
--- a/lib/__tests__/dashboard-metrics.test.ts
+++ b/lib/__tests__/dashboard-metrics.test.ts
@@ -1,11 +1,13 @@
import { describe, expect, it } from 'vitest'
import type { BillDashboardItem } from '../api/bills.server'
+import type { PayableWithStatus } from '../api/payables.server'
import {
billCurrency,
computeMetrics,
countCardsByHolder,
formatMoney,
getDueTodayBills,
+ getDueTodayPayables,
} from '../dashboard-metrics'
/** 最小账单夹具:只带 computeMetrics 读取的字段(characterization 钉行为用)。 */
@@ -18,6 +20,27 @@ function bill(p: { days_until_due: number; remaining_amount: number; currency?:
} as unknown as BillDashboardItem
}
+/** 最小固定支出夹具。 */
+function payable(p: {
+ id?: string
+ days_until_due: number
+ amount: number
+ paid_amount?: number
+ currency?: string
+ status?: 'unpaid' | 'paid' | 'overdue'
+}): PayableWithStatus {
+ return {
+ id: p.id ?? 'pay-1',
+ name: '房租',
+ category: 'rent',
+ amount: p.amount,
+ paid_amount: p.paid_amount ?? 0,
+ currency: p.currency ?? 'CNY',
+ days_until_due: p.days_until_due,
+ status: p.status ?? 'unpaid',
+ } as unknown as PayableWithStatus
+}
+
const RATES = { base: 'USD', rates: { USD: 1, CNY: 7.2 }, timestamp: 0, fetched_at: 0 }
describe('computeMetrics(现状 characterization)', () => {
@@ -129,3 +152,46 @@ describe('getDueTodayBills(今天需还款列表)', () => {
])).toEqual([due])
})
})
+
+describe('当日待还总金额(账单 + 固定支出)', () => {
+ it('getDueTodayPayables 只保留当天到期且仍有剩余待付的固定支出', () => {
+ const partialToday = payable({ id: 'p-partial', days_until_due: 0, amount: 3000, paid_amount: 1200 })
+ const settledPaid = payable({ id: 'p-paid', days_until_due: 0, amount: 1000, paid_amount: 1000, status: 'paid' })
+ const centZero = payable({ id: 'p-cent', days_until_due: 0, amount: 100, paid_amount: 99.995, status: 'unpaid' })
+ const tomorrow = payable({ id: 'p-tmr', days_until_due: 1, amount: 500 })
+ const overdue = payable({ id: 'p-ov', days_until_due: -2, amount: 500, status: 'overdue' })
+
+ expect(
+ getDueTodayPayables([partialToday, settledPaid, centZero, tomorrow, overdue])
+ ).toEqual([partialToday])
+ })
+
+ it('computeMetrics 汇总当日到期账单与固定支出并按汇率折算,缺汇率排除进 unconvertedCurrencies', () => {
+ const m = computeMetrics(
+ [
+ bill({ days_until_due: 0, remaining_amount: 1000, currency: 'CNY' }),
+ bill({ days_until_due: 3, remaining_amount: 500, currency: 'CNY' }),
+ ],
+ 7,
+ 'CNY',
+ RATES,
+ [
+ payable({ id: 'p-usd', days_until_due: 0, amount: 150, paid_amount: 50, currency: 'USD' }),
+ payable({ id: 'p-hkd', days_until_due: 0, amount: 200, currency: 'HKD' }),
+ payable({ id: 'p-paid', days_until_due: 0, amount: 900, paid_amount: 900, status: 'paid' }),
+ payable({ id: 'p-next', days_until_due: 2, amount: 400, currency: 'CNY' }),
+ ]
+ )
+
+ // USD 100 * 7.2 + CNY 1000 = 1720;HKD 缺汇率不得 1:1 混加
+ expect(m.dueTodayAmount).toBe(1720)
+ expect(m.dueTodayBills).toHaveLength(1)
+ expect(m.dueTodayPayables.map(p => p.id)).toEqual(['p-usd', 'p-hkd'])
+ expect(m.dueTodayCount).toBe(3)
+ expect(m.unconvertedCurrencies).toContain('HKD')
+ expect(m.fx.dueToday.unconverted_currencies).toEqual(['HKD'])
+ // totalPending 仅统计账单未还,不被固定支出污染
+ expect(m.totalPending).toBe(1500)
+ })
+})
+
diff --git a/lib/__tests__/notification-center.test.ts b/lib/__tests__/notification-center.test.ts
new file mode 100644
index 0000000..0c3d92e
--- /dev/null
+++ b/lib/__tests__/notification-center.test.ts
@@ -0,0 +1,1044 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createOpportunityDb } from './helpers/sqlite-d1'
+import type { SqliteD1 } from './helpers/sqlite-d1'
+import { setDb } from '../db/client'
+import {
+ buildDailyNotificationCandidates,
+ ensureDailyNotificationsForUser,
+} from '../notifications-engine.server'
+import {
+ computeCardGraceWindowOnDate,
+ isInQuietHours,
+ isNewLongestGracePeriodDay,
+ syncItemSwitchesWithOpportunities,
+} from '../notifications.shared'
+import { getBillDashboardItems } from '../api/bills.server'
+import {
+ deleteAllNotifications,
+ deleteNotification,
+ getNotifications,
+ getUnreadNotificationCount,
+ markAllNotificationsRead,
+ markNotificationRead,
+} from '../api/notifications.server'
+
+const { mockSendNotification, mockSetVapidDetails, mockSendApnsToUser } = vi.hoisted(() => ({
+ mockSendNotification: vi.fn(),
+ mockSetVapidDetails: vi.fn(),
+ mockSendApnsToUser: vi.fn(),
+}))
+
+vi.mock('web-push', () => ({
+ default: {
+ sendNotification: mockSendNotification,
+ setVapidDetails: mockSetVapidDetails,
+ },
+}))
+
+vi.mock('../apns.server', () => ({
+ sendApnsToUser: mockSendApnsToUser,
+}))
+
+import { handleScheduled } from '../../worker/cron'
+import { scanOpportunityNotifications } from '../../worker/opportunity-cron'
+
+async function seedWorld(db: SqliteD1) {
+ await db.batch([
+ db
+ .prepare(`INSERT INTO users (id, email, password_hash, name, role) VALUES (?, ?, ?, ?, ?)`)
+ .bind('user-a', 'a@test.local', 'hash-a', '用户A', 'admin'),
+ db
+ .prepare(`INSERT INTO users (id, email, password_hash, name, role) VALUES (?, ?, ?, ?, ?)`)
+ .bind('user-b', 'b@test.local', 'hash-b', '用户B', 'member'),
+ db
+ .prepare(`INSERT INTO card_holders (id, created_by, managed_by, name) VALUES (?, ?, ?, ?)`)
+ .bind('holder-a', 'user-a', 'user-a', '持卡人甲'),
+ db
+ .prepare(`INSERT INTO card_holders (id, created_by, managed_by, name) VALUES (?, ?, ?, ?)`)
+ .bind('holder-b', 'user-b', 'user-b', '持卡人乙'),
+ db.prepare(`INSERT INTO banks (id, name) VALUES (?, ?)`).bind('bank-cmb', '招商银行'),
+ db
+ .prepare(
+ `INSERT INTO card_products (id, bank_id, bank_name, card_name, currency, payment_due_type, payment_due_value)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
+ )
+ .bind('prod-cny', 'bank-cmb', '招商银行', '经典白', 'CNY', 'after_billing', 20),
+ db
+ .prepare(
+ `INSERT INTO card_products (id, bank_id, bank_name, card_name, currency, payment_due_type, payment_due_value)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
+ )
+ .bind('prod-usd', 'bank-cmb', '招商银行', '全币白', 'USD', 'fixed', 25),
+ db
+ .prepare(
+ `INSERT INTO user_preferences (id, user_id, reminder_config) VALUES (?, ?, ?)`
+ )
+ .bind(
+ 'pref-a',
+ 'user-a',
+ JSON.stringify({
+ remind_days_before: [3, 1, 0],
+ quiet_hours_start: '22:00',
+ quiet_hours_end: '08:00',
+ enabled_channels: ['web_push'],
+ })
+ ),
+ ])
+}
+
+describe('主动通知增强 + 通知中心 + 全部通知项开关', () => {
+ let db: SqliteD1
+
+ beforeEach(async () => {
+ db = createOpportunityDb()
+ setDb(db as unknown as D1Database)
+ mockSendNotification.mockReset().mockResolvedValue({ statusCode: 201 })
+ mockSetVapidDetails.mockReset()
+ mockSendApnsToUser.mockReset().mockResolvedValue({ total: 1, sent: 1, failed: 0 })
+ await seedWorld(db)
+ })
+
+ afterEach(() => {
+ setDb(null)
+ db.close()
+ })
+
+ describe('当日待还主动通知与独立开关', () => {
+ it('汇总信用卡账单(含覆盖到期日与已还扣除)及固定支出,按币种拆分总额', async () => {
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day, status, card_type)
+ VALUES (?, ?, ?, ?, ?, 'active', 'credit')`
+ )
+ .bind('card-1', 'holder-a', 'prod-cny', '8888', 20),
+ db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date, due_date_override, status)
+ VALUES (?, ?, ?, ?, ?, ?, 'partial')`
+ )
+ .bind('bill-1', 'card-1', '2026-05', 1500, '2026-05-05', '2026-05-10'),
+ db
+ .prepare(
+ `INSERT INTO payments (id, bill_id, amount, paid_at, idempotency_key)
+ VALUES (?, ?, ?, ?, ?)`
+ )
+ .bind('pmt-1', 'bill-1', 500, '2026-05-06', 'idem-pmt-1'),
+ db
+ .prepare(
+ `INSERT INTO recurring_payables (id, created_by, name, category, amount, currency, due_day, holder_id, is_active)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)`
+ )
+ .bind('pay-usd', 'user-a', '海外主机', 'utility', 150, 'USD', 10, 'holder-a'),
+ db
+ .prepare(
+ `INSERT INTO recurring_payable_payments (id, payable_id, period, amount, paid_at)
+ VALUES (?, ?, ?, ?, ?)`
+ )
+ .bind('rpay-1', 'pay-usd', '2026-05', 50, '2026-05-08'),
+ ])
+
+ const { candidates } = await buildDailyNotificationCandidates(
+ db as unknown as D1Database,
+ 'user-a',
+ '2026-05-10'
+ )
+ const summary = candidates.find(c => c.notification_key === 'due_today_summary:2026-05-10')
+ expect(summary).toBeTruthy()
+ expect(summary!.category).toBe('bill_due_today')
+ expect(summary!.title).toContain('¥1,000')
+ expect(summary!.title).toContain('$100')
+ expect(summary!.title).toContain('共 2 笔')
+ expect(summary!.body).toContain('8888')
+ expect(summary!.body).toContain('海外主机')
+
+ const meta = JSON.parse(summary!.metadata_json!)
+ expect(meta.totals_by_currency).toEqual({ CNY: 1000, USD: 100 })
+ expect(meta.bills).toHaveLength(1)
+ expect(meta.bills[0].remaining).toBe(1000)
+ expect(meta.payables).toHaveLength(1)
+ expect(meta.payables[0].remaining).toBe(100)
+
+ // 仅关闭 bill_due_today,只保留固定支出进入当日汇总
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = ?`)
+ .bind(
+ JSON.stringify({
+ remind_days_before: [3, 1, 0],
+ items: { bill_due_today: false, payable_due_today: true },
+ }),
+ 'user-a'
+ )
+ .run()
+
+ const payablesOnly = await buildDailyNotificationCandidates(
+ db as unknown as D1Database,
+ 'user-a',
+ '2026-05-10'
+ )
+ const paySummary = payablesOnly.candidates.find(
+ c => c.notification_key === 'due_today_summary:2026-05-10'
+ )
+ expect(paySummary).toBeTruthy()
+ expect(paySummary!.category).toBe('payable_due_today')
+ expect(paySummary!.title).toContain('$100')
+ expect(paySummary!.title).toContain('共 1 笔')
+ expect(paySummary!.body).not.toContain('8888')
+
+ // 两项都关闭时不生成当日待还汇总
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = ?`)
+ .bind(
+ JSON.stringify({
+ remind_days_before: [3, 1, 0],
+ items: { bill_due_today: false, payable_due_today: false },
+ }),
+ 'user-a'
+ )
+ .run()
+ const none = await buildDailyNotificationCandidates(
+ db as unknown as D1Database,
+ 'user-a',
+ '2026-05-10'
+ )
+ expect(none.candidates.some(c => c.notification_key.startsWith('due_today_summary:'))).toBe(false)
+ })
+
+ it('grace_period_longest 按账单日次日触发、支持 2 月月末钳制、合并账户去重并排除贷款卡', async () => {
+ expect(isNewLongestGracePeriodDay(10, '2026-05-10')).toBe(false)
+ expect(isNewLongestGracePeriodDay(10, '2026-05-11')).toBe(true)
+ expect(isNewLongestGracePeriodDay(31, '2026-02-28')).toBe(false)
+ expect(isNewLongestGracePeriodDay(31, '2026-03-01')).toBe(true)
+
+ const win = computeCardGraceWindowOnDate(
+ { billing_day: 31, payment_due_type: 'after_billing', payment_due_value: 20 },
+ '2026-03-01'
+ )
+ expect(win.nextBillingDate).toBe('2026-03-31')
+ expect(win.nextDueDate).toBe('2026-04-20')
+ expect(win.graceDays).toBe(50)
+
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO credit_accounts (id, holder_id, bank_id, bank_name, currency, statement_mode, quota_mode, billing_day, due_type, due_value, status)
+ VALUES (?, ?, ?, ?, 'CNY', 'merged', 'shared', 10, 'after_billing', 20, 'active')`
+ )
+ .bind('acc-merged', 'holder-a', 'bank-cmb', '招商银行'),
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, account_id, card_number_last4, billing_day, status, card_type)
+ VALUES (?, ?, ?, ?, ?, 10, 'active', 'credit')`
+ )
+ .bind('card-m1', 'holder-a', 'prod-cny', 'acc-merged', '1001'),
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, account_id, card_number_last4, billing_day, status, card_type)
+ VALUES (?, ?, ?, ?, ?, 10, 'active', 'credit')`
+ )
+ .bind('card-m2', 'holder-a', 'prod-cny', 'acc-merged', '1002'),
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day, status, card_type)
+ VALUES (?, ?, ?, ?, 28, 'active', 'credit')`
+ )
+ .bind('card-eom', 'holder-a', 'prod-usd', '3131'),
+ db
+ .prepare(
+ `UPDATE credit_cards SET billing_day = 31 WHERE id = 'card-eom'`
+ ),
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, status, card_type, loan_due_day)
+ VALUES (?, ?, ?, 10, 'active', 'loan', 10)`
+ )
+ .bind('card-loan', 'holder-a', 'prod-cny'),
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, status, card_type)
+ VALUES (?, ?, ?, 10, 'frozen', 'credit')`
+ )
+ .bind('card-frozen', 'holder-a', 'prod-cny'),
+ ])
+
+ // 2026-05-11:合并账户 2 张卡合并去重成 1 条,贷款卡与冻结卡不进入
+ const may11 = await buildDailyNotificationCandidates(
+ db as unknown as D1Database,
+ 'user-a',
+ '2026-05-11'
+ )
+ const mayGrace = may11.candidates.find(c => c.notification_key === 'grace_longest:2026-05-11')
+ expect(mayGrace).toBeTruthy()
+ const mayMeta = JSON.parse(mayGrace!.metadata_json!)
+ expect(mayMeta.cards).toHaveLength(1)
+
+ // 2026-03-01:billing_day=31 于 2/28 次日触发
+ const mar1 = await buildDailyNotificationCandidates(
+ db as unknown as D1Database,
+ 'user-a',
+ '2026-03-01'
+ )
+ const marGrace = mar1.candidates.find(c => c.notification_key === 'grace_longest:2026-03-01')
+ expect(marGrace).toBeTruthy()
+ const marMeta = JSON.parse(marGrace!.metadata_json!)
+ expect(marMeta.cards).toHaveLength(1)
+ expect(marMeta.cards[0].cardId).toBe('card-eom')
+
+ // 关闭 grace_period_longest 开关
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = ?`)
+ .bind(JSON.stringify({ items: { grace_period_longest: false } }), 'user-a')
+ .run()
+ const disabled = await buildDailyNotificationCandidates(
+ db as unknown as D1Database,
+ 'user-a',
+ '2026-05-11'
+ )
+ expect(disabled.candidates.some(c => c.category === 'grace_period_longest')).toBe(false)
+ })
+
+ it('支持提前提醒/逾期开关与跨午夜免打扰判断', async () => {
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day, status, card_type)
+ VALUES (?, ?, ?, ?, 1, 'active', 'credit')`
+ )
+ .bind('card-adv', 'holder-a', 'prod-cny', '7777'),
+ db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date, status)
+ VALUES (?, ?, ?, ?, ?, 'unpaid')`
+ )
+ .bind('bill-adv', 'card-adv', '2026-05', 800, '2026-05-13'),
+ db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date, status)
+ VALUES (?, ?, ?, ?, ?, 'overdue')`
+ )
+ .bind('bill-ov', 'card-adv', '2026-04', 600, '2026-05-01'),
+ db
+ .prepare(
+ `INSERT INTO recurring_payables (id, created_by, name, category, amount, currency, due_day, holder_id, is_active)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)`
+ )
+ .bind('pay-adv', 'user-a', '房租', 'rent', 4000, 'CNY', 13, 'holder-a'),
+ ])
+
+ const allOn = await buildDailyNotificationCandidates(
+ db as unknown as D1Database,
+ 'user-a',
+ '2026-05-10'
+ )
+ expect(allOn.candidates.some(c => c.category === 'bill_due_advance')).toBe(true)
+ expect(allOn.candidates.some(c => c.category === 'payable_due_advance')).toBe(true)
+ expect(allOn.candidates.some(c => c.category === 'bill_overdue')).toBe(true)
+
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = ?`)
+ .bind(
+ JSON.stringify({
+ remind_days_before: [3],
+ items: {
+ bill_due_advance: false,
+ payable_due_advance: false,
+ bill_overdue: false,
+ },
+ }),
+ 'user-a'
+ )
+ .run()
+
+ const gated = await buildDailyNotificationCandidates(
+ db as unknown as D1Database,
+ 'user-a',
+ '2026-05-10'
+ )
+ expect(gated.candidates.some(c => c.category === 'bill_due_advance')).toBe(false)
+ expect(gated.candidates.some(c => c.category === 'payable_due_advance')).toBe(false)
+ expect(gated.candidates.some(c => c.category === 'bill_overdue')).toBe(false)
+
+ // 2026-05-10T15:30:00Z = Asia/Shanghai 23:30,应命中 22:00-08:00 免打扰
+ expect(
+ isInQuietHours(new Date('2026-05-10T15:30:00Z'), 'Asia/Shanghai', '22:00', '08:00')
+ ).toBe(true)
+ // 2026-05-10T02:00:00Z = Asia/Shanghai 10:00,不在免打扰时段
+ expect(
+ isInQuietHours(new Date('2026-05-10T02:00:00Z'), 'Asia/Shanghai', '22:00', '08:00')
+ ).toBe(false)
+ })
+ })
+
+ describe('通知中心 6 个 RPC、跨用户隔离与软删除防复活', () => {
+ it('支持查询、未读筛选、单条/全部已读、单条/全部软删除及跨用户隔离', async () => {
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO notification_history (id, user_id, notification_key, category, title, body, sent_at, status)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'skipped')`
+ )
+ .bind('n-a1', 'user-a', 'k-a1', 'bill_due_today', '今日账单A1', '正文A1', '2026-05-10T01:00:00.000Z'),
+ db
+ .prepare(
+ `INSERT INTO notification_history (id, user_id, notification_key, category, title, body, sent_at, status)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'skipped')`
+ )
+ .bind('n-a2', 'user-a', 'k-a2', 'grace_period_longest', '最长免息A2', '正文A2', '2026-05-10T02:00:00.000Z'),
+ db
+ .prepare(
+ `INSERT INTO notification_history (id, user_id, notification_key, category, title, body, sent_at, status)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'skipped')`
+ )
+ .bind('n-b1', 'user-b', 'k-b1', 'system', '用户B通知', '正文B1', '2026-05-10T03:00:00.000Z'),
+ ])
+
+ const pageAll = await getNotifications('user-a', { syncToday: false })
+ expect(pageAll.total_count).toBe(2)
+ expect(pageAll.unread_count).toBe(2)
+ expect(pageAll.items.map(i => i.id)).toEqual(['n-a2', 'n-a1'])
+
+ // 跨用户隔离:user-b 看不到、读不了、删不了 user-a 的通知
+ const pageB = await getNotifications('user-b', { syncToday: false })
+ expect(pageB.items.map(i => i.id)).toEqual(['n-b1'])
+ const illegalRead = await markNotificationRead('user-b', 'n-a1')
+ expect(illegalRead.updated).toBe(false)
+ const illegalDelete = await deleteNotification('user-b', 'n-a1')
+ expect(illegalDelete.deleted).toBe(false)
+
+ // 单条已读 + 未读筛选
+ const readRes = await markNotificationRead('user-a', 'n-a1')
+ expect(readRes.updated).toBe(true)
+ expect(readRes.unread_count).toBe(1)
+
+ const unreadOnly = await getNotifications('user-a', { filter: 'unread', syncToday: false })
+ expect(unreadOnly.items.map(i => i.id)).toEqual(['n-a2'])
+
+ // 全部已读
+ const bulkRead = await markAllNotificationsRead('user-a')
+ expect(bulkRead.updated_count).toBe(1)
+ expect(bulkRead.unread_count).toBe(0)
+
+ // 单条软删除 + 全部软删除
+ const delOne = await deleteNotification('user-a', 'n-a1')
+ expect(delOne.deleted).toBe(true)
+ const remainingA = await getNotifications('user-a', { syncToday: false })
+ expect(remainingA.items.map(i => i.id)).toEqual(['n-a2'])
+
+ const delAll = await deleteAllNotifications('user-a')
+ expect(delAll.deleted_count).toBe(1)
+ expect(delAll.unread_count).toBe(0)
+
+ // user-b 自己的通知不受影响
+ expect(await getUnreadNotificationCount('user-b')).toBe(1)
+ })
+
+ it('当日待还通知删除后不会因再次打开通知中心而复活', async () => {
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO recurring_payables (id, created_by, name, category, amount, currency, due_day, holder_id, is_active)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)`
+ )
+ .bind('pay-keep', 'user-a', '水电网费', 'utility', 200, 'CNY', 10, 'holder-a'),
+ ])
+
+ const todayStr = new Intl.DateTimeFormat('en-CA', {
+ timeZone: 'Asia/Shanghai',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ }).format(new Date())
+ const dueDayNum = Number(todayStr.split('-')[2])
+ await db
+ .prepare(`UPDATE recurring_payables SET due_day = ? WHERE id = 'pay-keep'`)
+ .bind(dueDayNum)
+ .run()
+
+ await ensureDailyNotificationsForUser(db as unknown as D1Database, 'user-a', todayStr)
+ const firstPage = await getNotifications('user-a', { syncToday: true })
+ const summary = firstPage.items.find(i => i.notification_key === `due_today_summary:${todayStr}`)
+ expect(summary).toBeTruthy()
+
+ await deleteNotification('user-a', summary!.id)
+ // 再次同步当日候选,已软删记录保持 deleted_at 非空,绝不复活
+ await ensureDailyNotificationsForUser(db as unknown as D1Database, 'user-a', todayStr)
+ const afterReSync = await getNotifications('user-a', { syncToday: true })
+ expect(afterReSync.items.some(i => i.id === summary!.id)).toBe(false)
+ })
+ })
+
+ describe('Cron 站内生成与 push_sent_at 单次推送语义', () => {
+ it('无推送订阅时仍保留站内记录;有订阅时只推送一次并跳过已读/已删通知', async () => {
+ await db
+ .prepare(
+ `INSERT INTO recurring_payables (id, created_by, name, category, amount, currency, due_day, holder_id, is_active)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)`
+ )
+ .bind('pay-cron', 'user-a', '房贷', 'loan', 5000, 'CNY', 15, 'holder-a')
+ .run()
+
+ // 2026-05-15T01:00:00Z = 2026-05-15 09:00 Asia/Shanghai(非免打扰)
+ const scheduledAt = Date.parse('2026-05-15T01:00:00Z')
+
+ // 1) 无任何 push_subscriptions 时依然写入站内 notification_history
+ await handleScheduled(
+ { scheduledTime: scheduledAt } as ScheduledEvent,
+ { DB: db as unknown as D1Database },
+ {} as ExecutionContext
+ )
+ const inboxRow = await db
+ .prepare(
+ `SELECT status, push_sent_at, title FROM notification_history WHERE user_id = 'user-a' AND notification_key = 'due_today_summary:2026-05-15'`
+ )
+ .first<{ status: string; push_sent_at: string | null; title: string }>()
+ expect(inboxRow).toBeTruthy()
+ expect(inboxRow!.status).toBe('skipped')
+ expect(inboxRow!.push_sent_at).toBeNull()
+ expect(mockSendNotification).not.toHaveBeenCalled()
+
+ // 2) 添加一条 Web Push 订阅并传入 VAPID:补推一次并写入 push_sent_at
+ await db
+ .prepare(
+ `INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth)
+ VALUES ('sub-1', 'user-a', 'https://push.example/1', 'p256', 'auth')`
+ )
+ .run()
+
+ await handleScheduled(
+ { scheduledTime: scheduledAt } as ScheduledEvent,
+ {
+ DB: db as unknown as D1Database,
+ VAPID_PUBLIC_KEY: 'pub',
+ VAPID_PRIVATE_KEY: 'priv',
+ VAPID_SUBJECT: 'mailto:test@test.local',
+ },
+ {} as ExecutionContext
+ )
+ expect(mockSendNotification).toHaveBeenCalledTimes(1)
+ const afterPush = await db
+ .prepare(
+ `SELECT status, push_sent_at FROM notification_history WHERE user_id = 'user-a' AND notification_key = 'due_today_summary:2026-05-15'`
+ )
+ .first<{ status: string; push_sent_at: string | null }>()
+ expect(afterPush!.status).toBe('sent')
+ expect(afterPush!.push_sent_at).toBeTruthy()
+
+ // 3) 同日再次执行 Cron:push_sent_at 已有值,不再重复发送
+ mockSendNotification.mockClear()
+ await handleScheduled(
+ { scheduledTime: scheduledAt } as ScheduledEvent,
+ {
+ DB: db as unknown as D1Database,
+ VAPID_PUBLIC_KEY: 'pub',
+ VAPID_PRIVATE_KEY: 'priv',
+ },
+ {} as ExecutionContext
+ )
+ expect(mockSendNotification).not.toHaveBeenCalled()
+ })
+
+ it('worker/opportunity-cron 遵守细分开关并将发送结果落入 notification_history', async () => {
+ const ruleJson = JSON.stringify({
+ schema_version: 1,
+ title: '机场贵宾厅',
+ description: null,
+ category: 'travel',
+ time_zone: 'Asia/Shanghai',
+ bank_id: 'bank-cmb',
+ card_product_ids: ['prod-cny'],
+ valid_from: '2026-01-01',
+ valid_until_before: null,
+ open_ended: true,
+ weekdays: null,
+ cycle: { kind: 'monthly', anchor_month: null, anchor_day: 1, anchor_source: null },
+ allocation: 'recurring',
+ count_limit: 2,
+ amount_limit_minor: null,
+ currency: null,
+ unit_label: '次',
+ eligibility_text: null,
+ requires_personal_confirmation: false,
+ claim_window: null,
+ booking_window: null,
+ workflow_time_basis: 'per_cycle',
+ booking_consumes: 'reserve_then_use',
+ cancellation_rule: 'confirm_with_issuer',
+ entry: {},
+ })
+
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, status, card_type)
+ VALUES ('card-opp', 'holder-a', 'prod-cny', 10, 'active', 'credit')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_definitions (id, kind, visibility, status, created_by, created_at)
+ VALUES ('def-exp', 'benefit', 'shared', 'active', 'user-a', '2026-01-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_rule_versions (id, definition_id, version, effective_from, rules_json, verification, published_at)
+ VALUES ('ver-exp', 'def-exp', 1, '2026-01-01', ?, 'official_verified', '2026-01-01T00:00:00Z')`
+ )
+ .bind(ruleJson),
+ db
+ .prepare(
+ `INSERT INTO opportunity_accounts (id, definition_id, holder_id, scope_kind, scope_key, eligibility, status, created_by, created_at)
+ VALUES ('oacc-exp', 'def-exp', 'holder-a', 'card', 'card-opp', 'confirmed', 'active', 'user-a', '2026-01-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_account_cards (account_id, definition_id, holder_id, card_id)
+ VALUES ('oacc-exp', 'def-exp', 'holder-a', 'card-opp')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_cycles (id, account_id, version_id, version_as_of_on, cycle_key, allocation_kind, activation_state, period_start_on, period_end_before, usable_start_on, usable_end_before, time_zone, count_limit, created_at)
+ VALUES ('cyc-exp', 'oacc-exp', 'ver-exp', '2026-05-01', '2026-05', 'regular', 'active', '2026-05-01', '2026-06-01', '2026-05-01', '2026-06-01', 'Asia/Shanghai', 2, '2026-05-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth)
+ VALUES ('sub-opp', 'user-a', 'https://push.example/opp', 'p256', 'auth')`
+ ),
+ ])
+
+ const sender = vi.fn().mockResolvedValue({ ok: true })
+ const now = new Date('2026-05-31T01:00:00Z')
+
+ // 关闭 opportunity_expiry 时跳过触发,不产生站内历史
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = ?`)
+ .bind(JSON.stringify({ items: { opportunity_expiry: false } }), 'user-a')
+ .run()
+ await scanOpportunityNotifications({
+ db: db as unknown as D1Database,
+ now,
+ sender,
+ })
+ expect(sender).not.toHaveBeenCalled()
+
+ // 打开 opportunity_expiry 后触发发送并写入 notification_history(opp:)
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = ?`)
+ .bind(JSON.stringify({ items: { opportunity_expiry: true } }), 'user-a')
+ .run()
+ const report = await scanOpportunityNotifications({
+ db: db as unknown as D1Database,
+ now,
+ sender,
+ })
+ expect(report.sent).toBeGreaterThanOrEqual(1)
+ expect(sender).toHaveBeenCalled()
+ const hist = await db
+ .prepare(
+ `SELECT notification_key, category, push_sent_at FROM notification_history WHERE user_id = 'user-a' AND notification_key LIKE 'opp:%'`
+ )
+ .first<{ notification_key: string; category: string; push_sent_at: string | null }>()
+ expect(hist).toBeTruthy()
+ expect(hist!.category).toBe('opportunity_expiry')
+ expect(hist!.push_sent_at).toBeTruthy()
+ })
+ })
+
+ describe('PR #56 Review 回归用例', () => {
+ it('Codex #1: 存在 reminder_config 但未显式配置 items 时保留旧 notification_preferences 退订设置', async () => {
+ await db.batch([
+ db
+ .prepare(
+ `UPDATE user_preferences SET reminder_config = ? WHERE user_id = 'user-a'`
+ )
+ .bind(JSON.stringify({ quiet_hours_start: '22:00', quiet_hours_end: '08:00' })),
+ db
+ .prepare(
+ `INSERT INTO notification_preferences (user_id, bill_due_enabled, overdue_enabled, due_days_before)
+ VALUES ('user-a', 0, 0, 3)`
+ ),
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, status, card_type)
+ VALUES ('card-leg', 'holder-a', 'prod-cny', 10, 'active', 'credit')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date, status)
+ VALUES ('bill-leg-due', 'card-leg', '2026-05', 500, '2026-05-10', 'unpaid')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date, status)
+ VALUES ('bill-leg-over', 'card-leg', '2026-04', 200, '2026-05-05', 'overdue')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO recurring_payables (id, created_by, name, category, amount, currency, due_day, is_active, created_at)
+ VALUES ('pay-leg', 'user-a', '宽带费', 'utility', 100, 'CNY', 10, 1, '2026-01-01T00:00:00Z')`
+ ),
+ ])
+
+ const first = await buildDailyNotificationCandidates(db as unknown as D1Database, 'user-a', '2026-05-10')
+ expect(first.context.reminderConfig.items?.bill_due_today).toBe(false)
+ expect(first.context.reminderConfig.items?.bill_due_advance).toBe(false)
+ expect(first.context.reminderConfig.items?.bill_overdue).toBe(false)
+ expect(first.candidates.some(c => c.notification_key === 'bill_overdue:bill-leg-over:2026-05-10')).toBe(false)
+ const summary = first.candidates.find(c => c.notification_key === 'due_today_summary:2026-05-10')
+ expect(summary).toBeTruthy()
+ const meta = JSON.parse(summary!.metadata_json!)
+ expect(meta.bills).toHaveLength(0)
+ expect(meta.payables).toHaveLength(1)
+
+ // 显式开启 bill_due_today 时覆盖旧表退订
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = 'user-a'`)
+ .bind(JSON.stringify({ items: { bill_due_today: true } }))
+ .run()
+ const second = await buildDailyNotificationCandidates(db as unknown as D1Database, 'user-a', '2026-05-10')
+ const summary2 = second.candidates.find(c => c.notification_key === 'due_today_summary:2026-05-10')
+ const meta2 = JSON.parse(summary2!.metadata_json!)
+ expect(meta2.bills).toHaveLength(1)
+ expect(second.candidates.some(c => c.notification_key === 'bill_overdue:bill-leg-over:2026-05-10')).toBe(false)
+ })
+
+ it('Codex #7: 用户关闭推送通道 (enabled_channels: []) 时跳过 APNs 发送', async () => {
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, status, card_type)
+ VALUES ('card-apns', 'holder-a', 'prod-cny', 10, 'active', 'credit')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date, status)
+ VALUES ('bill-apns', 'card-apns', '2026-05', 300, '2026-05-10', 'unpaid')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO device_tokens (id, user_id, token, platform)
+ VALUES ('dev-1', 'user-a', 'apns-tok-1', 'ios')`
+ ),
+ db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = 'user-a'`)
+ .bind(
+ JSON.stringify({
+ remind_days_before: [3, 1, 0],
+ quiet_hours_start: '22:00',
+ quiet_hours_end: '08:00',
+ enabled_channels: [],
+ })
+ ),
+ ])
+
+ const env = {
+ DB: db as unknown as D1Database,
+ APNS_KEY_P8: 'fake-key',
+ APNS_KEY_ID: 'key-1',
+ APNS_TEAM_ID: 'team-1',
+ }
+ await handleScheduled(
+ { scheduledTime: Date.parse('2026-05-10T02:00:00Z') } as ScheduledEvent,
+ env,
+ {} as ExecutionContext
+ )
+ expect(mockSendApnsToUser).not.toHaveBeenCalled()
+
+ // 清空历史并恢复推送通道后 APNs 恢复发送
+ await db.prepare(`DELETE FROM notification_history WHERE user_id = 'user-a'`).run()
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = 'user-a'`)
+ .bind(
+ JSON.stringify({
+ remind_days_before: [3, 1, 0],
+ quiet_hours_start: '22:00',
+ quiet_hours_end: '08:00',
+ enabled_channels: ['web_push'],
+ })
+ )
+ .run()
+ await handleScheduled(
+ { scheduledTime: Date.parse('2026-05-10T02:00:00Z') } as ScheduledEvent,
+ env,
+ {} as ExecutionContext
+ )
+ expect(mockSendApnsToUser).toHaveBeenCalledTimes(1)
+ })
+
+ it('OCR #31/#33 & #27: 畸形到期日不误判今日到期,syncToday=false 不写当日通知,items 优先于 opportunities 冲突值', async () => {
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, status, card_type)
+ VALUES ('card-bad', 'holder-a', 'prod-cny', 10, 'active', 'credit')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date, due_date_override, status)
+ VALUES ('bill-bad-date', 'card-bad', '2026-05', 100, '2026-05-10', 'not-a-date', 'unpaid')`
+ ),
+ ])
+
+ const built = await buildDailyNotificationCandidates(db as unknown as D1Database, 'user-a', '2026-05-10')
+ expect(built.candidates).toHaveLength(0)
+
+ // 写入合法今日待还账单后,getUnreadNotificationCount(userId, false) 不触发 syncToday 写入
+ await db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, due_date, status)
+ VALUES ('bill-good', 'card-bad', '2026-06', 250, '2026-05-10', 'unpaid')`
+ )
+ .run()
+ const countWithoutSync = await getUnreadNotificationCount('user-a', false)
+ expect(countWithoutSync).toBe(0)
+ const countWithSync = await getUnreadNotificationCount('user-a')
+ expect(countWithSync).toBe(1)
+
+ // syncItemSwitchesWithOpportunities: incoming.items 优先覆盖 incoming.opportunities
+ const synced = syncItemSwitchesWithOpportunities(
+ { items: { opportunity_reset: true }, opportunities: { reset_enabled: true } },
+ { items: { opportunity_reset: false }, opportunities: { reset_enabled: true } }
+ )
+ expect(synced.items.opportunity_reset).toBe(false)
+ expect(synced.opportunities.reset_enabled).toBe(false)
+ })
+
+ it('Codex #2/#3 & OCR #43/#44/#45: 取消已关闭开关的在途任务、promo 使用 activity_days_before、结构化 deliveryKey 分类、web_push 关闭计数与 partial 写回', async () => {
+ const makeRuleJson = (title: string, category: 'shopping' | 'travel') =>
+ JSON.stringify({
+ schema_version: 1,
+ title,
+ description: null,
+ category,
+ time_zone: 'Asia/Shanghai',
+ bank_id: 'bank-cmb',
+ card_product_ids: ['prod-cny'],
+ valid_from: '2026-01-01',
+ valid_until_before: null,
+ open_ended: true,
+ weekdays: null,
+ cycle: { kind: 'monthly', anchor_month: null, anchor_day: 1, anchor_source: null },
+ allocation: 'recurring',
+ count_limit: 1,
+ amount_limit_minor: null,
+ currency: null,
+ unit_label: '次',
+ eligibility_text: null,
+ requires_personal_confirmation: false,
+ claim_window: null,
+ booking_window: null,
+ workflow_time_basis: 'per_cycle',
+ booking_consumes: 'reserve_then_use',
+ cancellation_rule: 'confirm_with_issuer',
+ entry: {},
+ })
+ const promoRules = makeRuleJson('双倍积分活动', 'shopping')
+ const benefitRules = makeRuleJson('延误险权益', 'travel')
+
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, status, card_type)
+ VALUES ('card-opp2', 'holder-a', 'prod-cny', 10, 'active', 'credit')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_definitions (id, kind, visibility, status, created_by, created_at)
+ VALUES ('def-promo', 'promo', 'shared', 'active', 'user-a', '2026-01-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_rule_versions (id, definition_id, version, effective_from, rules_json, verification, published_at)
+ VALUES ('ver-promo', 'def-promo', 1, '2026-01-01', ?, 'official_verified', '2026-01-01T00:00:00Z')`
+ )
+ .bind(promoRules),
+ db
+ .prepare(
+ `INSERT INTO opportunity_accounts (id, definition_id, holder_id, scope_kind, scope_key, eligibility, status, created_by, created_at)
+ VALUES ('oacc-promo', 'def-promo', 'holder-a', 'card', 'card-opp2', 'confirmed', 'active', 'user-a', '2026-01-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_account_cards (account_id, definition_id, holder_id, card_id)
+ VALUES ('oacc-promo', 'def-promo', 'holder-a', 'card-opp2')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_cycles (id, account_id, version_id, version_as_of_on, cycle_key, allocation_kind, activation_state, period_start_on, period_end_before, usable_start_on, usable_end_before, time_zone, count_limit, created_at)
+ VALUES ('cyc-promo', 'oacc-promo', 'ver-promo', '2026-06-01', '2026-06', 'regular', 'active', '2026-06-01', '2026-06-06', '2026-06-01', '2026-06-06', 'Asia/Shanghai', 1, '2026-06-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_definitions (id, kind, visibility, status, created_by, created_at)
+ VALUES ('def-claim-id', 'benefit', 'shared', 'active', 'user-a', '2026-01-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_rule_versions (id, definition_id, version, effective_from, rules_json, verification, published_at)
+ VALUES ('ver-claim-id', 'def-claim-id', 1, '2026-01-01', ?, 'official_verified', '2026-01-01T00:00:00Z')`
+ )
+ .bind(benefitRules),
+ // 对象 ID 本身含 "claim" 字样,用来验证 OCR #43 不会被子串误判为 opportunity_claim
+ db
+ .prepare(
+ `INSERT INTO opportunity_accounts (id, definition_id, holder_id, scope_kind, scope_key, eligibility, status, created_by, created_at)
+ VALUES ('oacc-claim-word', 'def-claim-id', 'holder-a', 'card', 'card-opp2', 'confirmed', 'active', 'user-a', '2026-01-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_account_cards (account_id, definition_id, holder_id, card_id)
+ VALUES ('oacc-claim-word', 'def-claim-id', 'holder-a', 'card-opp2')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO opportunity_cycles (id, account_id, version_id, version_as_of_on, cycle_key, allocation_kind, activation_state, period_start_on, period_end_before, usable_start_on, usable_end_before, time_zone, count_limit, created_at)
+ VALUES ('cyc-claim-word', 'oacc-claim-word', 'ver-claim-id', '2026-06-01', '2026-06', 'regular', 'active', '2026-06-01', '2026-06-02', '2026-06-01', '2026-06-02', 'Asia/Shanghai', 1, '2026-06-01T00:00:00Z')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth)
+ VALUES ('sub-1', 'user-a', 'https://push.example/1', 'p', 'a')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth)
+ VALUES ('sub-2', 'user-a', 'https://push.example/2', 'p', 'a')`
+ ),
+ ])
+
+ const now = new Date('2026-06-01T01:00:00Z')
+
+ // Codex #3: promo 的 last usable day 是 2026-06-05 (距 06-01 为 4 天),仅在 activity_days_before 含 4 时生成 d4 任务
+ // 同时验证 OCR #44: web_push 关闭时计入 skipped_web_push_disabled,且不误计入 skipped_no_subscription
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = 'user-a'`)
+ .bind(
+ JSON.stringify({
+ enabled_channels: [],
+ items: { opportunity_activity: true, opportunity_expiry: true },
+ opportunities: { enabled: true, activity_days_before: [4], expiry_days_before: [2] },
+ })
+ )
+ .run()
+ const sender = vi.fn(async (sub: { endpoint: string }) =>
+ sub.endpoint.endsWith('/1') ? { ok: true } : { ok: false, error: '502 bad gateway' }
+ )
+ const rDisabled = await scanOpportunityNotifications({
+ db: db as unknown as D1Database,
+ now,
+ sender,
+ })
+ const promoJob = await db
+ .prepare(`SELECT delivery_key FROM opportunity_notification_jobs WHERE object_id = 'oacc-promo'`)
+ .first<{ delivery_key: string }>()
+ expect(promoJob?.delivery_key.endsWith(':d4')).toBe(true)
+ expect(rDisabled.skipped_web_push_disabled).toBeGreaterThanOrEqual(1)
+ expect(rDisabled.skipped_no_subscription).toBe(0)
+ expect(sender).not.toHaveBeenCalled()
+
+ // 开启 web_push 通道并重置 job 为 pending 以便在部分失败场景验证 OCR #45
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = 'user-a'`)
+ .bind(
+ JSON.stringify({
+ enabled_channels: ['web_push'],
+ items: { opportunity_activity: true, opportunity_expiry: true },
+ opportunities: { enabled: true, activity_days_before: [4], expiry_days_before: [2] },
+ })
+ )
+ .run()
+ await db
+ .prepare(`UPDATE opportunity_notification_jobs SET status = 'pending', scheduled_at = '2026-06-01T00:00:00Z'`)
+ .run()
+
+ const rPartial = await scanOpportunityNotifications({
+ db: db as unknown as D1Database,
+ now,
+ sender,
+ })
+ expect(rPartial.partial).toBeGreaterThanOrEqual(2)
+
+ const histRows = (
+ await db
+ .prepare(
+ `SELECT notification_key, category, status, push_sent_at, error
+ FROM notification_history
+ WHERE user_id = 'user-a' AND notification_key LIKE 'opp:%'`
+ )
+ .all<{ notification_key: string; category: string; status: string; push_sent_at: string | null; error: string | null }>()
+ ).results
+ const promoHist = histRows.find(r => r.notification_key.includes('oacc-promo'))
+ const claimWordHist = histRows.find(r => r.notification_key.includes('oacc-claim-word'))
+ expect(promoHist?.category).toBe('opportunity_activity')
+ expect(promoHist?.status).toBe('sent')
+ expect(promoHist?.push_sent_at).toBeTruthy()
+ expect(promoHist?.error).toContain('发送失败')
+ // OCR #43: 对象 id 含 "claim" 仍按结构化 event type 'expiry' 归类
+ expect(claimWordHist?.category).toBe('opportunity_expiry')
+ expect(claimWordHist?.status).toBe('sent')
+
+ // Codex #2: 若已有待投递 job,在投递前关闭开关则会直接取消 job 且不再写 notification_history
+ await db.prepare(`DELETE FROM notification_history WHERE user_id = 'user-a'`).run()
+ await db
+ .prepare(`UPDATE opportunity_notification_jobs SET status = 'pending', scheduled_at = '2026-06-01T00:00:00Z'`)
+ .run()
+ await db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = 'user-a'`)
+ .bind(
+ JSON.stringify({
+ enabled_channels: ['web_push'],
+ items: { opportunity_activity: false, opportunity_expiry: false },
+ opportunities: { enabled: true, activity_days_before: [4], expiry_days_before: [2] },
+ })
+ )
+ .run()
+ sender.mockClear()
+ const rCancelled = await scanOpportunityNotifications({
+ db: db as unknown as D1Database,
+ now,
+ sender,
+ })
+ expect(rCancelled.cancelled).toBeGreaterThanOrEqual(2)
+ expect(sender).not.toHaveBeenCalled()
+ const postCancelHist = await db
+ .prepare(`SELECT COUNT(*) AS cnt FROM notification_history WHERE user_id = 'user-a'`)
+ .first<{ cnt: number }>()
+ expect(Number(postCancelHist?.cnt ?? 0)).toBe(0)
+ })
+
+ it('Round-2: buildDailyNotificationCandidates 按用户时区判定今日日期,且 bills.server 保留 min_payment_override = 0', async () => {
+ await db.batch([
+ db
+ .prepare(`UPDATE user_preferences SET reminder_config = ? WHERE user_id = 'user-a'`)
+ .bind(
+ JSON.stringify({
+ enabled_channels: ['web_push'],
+ opportunities: { time_zone: 'America/New_York' },
+ })
+ ),
+ db
+ .prepare(
+ `INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, status, card_type)
+ VALUES ('card-tz', 'holder-a', 'prod-cny', 10, 'active', 'credit')`
+ ),
+ db
+ .prepare(
+ `INSERT INTO bills (id, card_id, bill_month, bill_amount, min_payment, min_payment_override, due_date, status)
+ VALUES ('bill-tz', 'card-tz', '2026-05', 800, 80, 0, '2026-05-09', 'unpaid')`
+ ),
+ ])
+
+ // 2026-05-10T02:00:00Z = America/New_York 2026-05-09 22:00 (Asia/Shanghai 已是 05-10)
+ const built = await buildDailyNotificationCandidates(db as unknown as D1Database, 'user-a', undefined, {
+ now: new Date('2026-05-10T02:00:00Z'),
+ })
+ expect(built.context.timeZone).toBe('America/New_York')
+ const summary = built.candidates.find(c => c.notification_key === 'due_today_summary:2026-05-09')
+ expect(summary).toBeTruthy()
+
+ const items = await getBillDashboardItems(20, 'user-a')
+ const target = items.find(b => b.id === 'bill-tz')
+ expect(target?.min_payment).toBe(0)
+ expect(target?.min_payment_override).toBe(0)
+ })
+ })
+})
diff --git a/lib/api/bills.server.ts b/lib/api/bills.server.ts
index 406bbbe..431b001 100644
--- a/lib/api/bills.server.ts
+++ b/lib/api/bills.server.ts
@@ -56,14 +56,6 @@ function withCreditCardProductFields(bill: BillWithCard): BillWithCard {
};
}
-function daysUntil(date: string): number {
- const d = new Date();
- d.setHours(0, 0, 0, 0);
- const target = new Date(date);
- target.setHours(0, 0, 0, 0);
- return Math.ceil((target.getTime() - d.getTime()) / (24 * 60 * 60 * 1000));
-}
-
function computeStatus(bill: Bill, paidAmount: number): Bill["status"] {
if (bill.status === "paid") return "paid";
// 一律用生效金额:用户手填值优先,否则已还金额会跟展示的金额对不上
@@ -89,10 +81,13 @@ interface BillJoinRow extends Record {
statement_start: string | null;
statement_end: string | null;
statement_date: string | null;
+ statement_date_override: string | null;
bill_amount: number;
bill_amount_override: number | null;
min_payment: number | null;
+ min_payment_override: number | null;
due_date: string;
+ due_date_override: string | null;
status: Bill["status"];
created_at: string;
// credit_cards fields
@@ -128,6 +123,10 @@ function mapJoinRowToDashboard(
payments: Pick[],
attachments?: { id: string; file_name: string; public_url?: string }[],
): BillDashboardItem {
+ const effectiveDueDate = row.due_date_override || row.due_date;
+ const effectiveStatementDate = row.statement_date_override || row.statement_date;
+ const effectiveMinPayment =
+ row.min_payment_override != null ? row.min_payment_override : row.min_payment;
const bill: Bill = {
id: row.id,
account_id: row.account_id ? String(row.account_id) : undefined,
@@ -135,15 +134,18 @@ function mapJoinRowToDashboard(
bill_month: row.bill_month,
statement_start: row.statement_start || undefined,
statement_end: row.statement_end || undefined,
- statement_date: row.statement_date || undefined,
+ statement_date: effectiveStatementDate || undefined,
+ statement_date_override: row.statement_date_override || undefined,
// 读边界统一把 bill_amount 归一化为「生效金额」(手填值优先)。
// 让每个消费方自己调用 effectiveBillAmount 是行不通的——本文件与
// analytics/holders/cards/cron 共有二十多处读取点,漏一处就会两处显示不一致。
bill_amount: row.bill_amount_override != null ? row.bill_amount_override : row.bill_amount,
// 手填值原样带出:界面要能显示「已手动设定」并允许改回,
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,
+ min_payment_override: row.min_payment_override != null ? row.min_payment_override : undefined,
+ due_date: effectiveDueDate,
+ due_date_override: row.due_date_override || undefined,
status: row.status,
created_at: row.created_at,
};
@@ -192,6 +194,7 @@ function mapJoinRowToDashboard(
};
const paidAmount = payments.reduce((sum, p) => sum + Number(p.amount || 0), 0);
const amount = effectiveBillAmount(bill);
+ const days = diffInCalendarDays(effectiveDueDate);
return {
...bill,
card,
@@ -199,8 +202,8 @@ function mapJoinRowToDashboard(
attachments,
paid_amount: paidAmount,
remaining_amount: Math.max(0, amount - paidAmount),
- days_until_due: daysUntil(bill.due_date),
- interest_free_days_left: Math.max(0, daysUntil(bill.due_date)),
+ days_until_due: days,
+ interest_free_days_left: Math.max(0, days),
computed_status: computeStatus(bill, paidAmount),
};
}
diff --git a/lib/api/notifications.server.ts b/lib/api/notifications.server.ts
new file mode 100644
index 0000000..2306745
--- /dev/null
+++ b/lib/api/notifications.server.ts
@@ -0,0 +1,194 @@
+// lib/api/notifications.server.ts — 通知中心服务端 RPC 实现(bindUser: 0 会话隔离)。
+
+import { getDb } from '../db/client'
+import { ensureDailyNotificationsForUser } from '../notifications-engine.server'
+import type { NotificationCategory, UserNotificationItem } from '../types'
+import { RpcDomainError } from './errors'
+
+export interface GetNotificationsOptions {
+ filter?: 'all' | 'unread'
+ category?: NotificationCategory
+ limit?: number
+ offset?: number
+ syncToday?: boolean
+}
+
+export interface NotificationsPageResult {
+ items: UserNotificationItem[]
+ unread_count: number
+ total_count: number
+}
+
+export interface NotificationReadResult {
+ updated: boolean
+ unread_count: number
+}
+
+export interface NotificationBulkReadResult {
+ updated_count: number
+ unread_count: number
+}
+
+export interface NotificationDeleteResult {
+ deleted: boolean
+ unread_count: number
+}
+
+export interface NotificationBulkDeleteResult {
+ deleted_count: number
+ unread_count: number
+}
+
+async function countUnreadForUser(db: D1Database, userId: string): Promise {
+ const row = await db
+ .prepare(
+ 'SELECT COUNT(*) AS cnt FROM notification_history WHERE user_id = ? AND deleted_at IS NULL AND read_at IS NULL'
+ )
+ .bind(userId)
+ .first<{ cnt: number }>()
+ return Number(row?.cnt ?? 0)
+}
+
+export async function getNotifications(
+ userId: string,
+ options: GetNotificationsOptions = {}
+): Promise {
+ const db = getDb()
+ if (options?.syncToday !== false) {
+ await ensureDailyNotificationsForUser(db, userId)
+ }
+
+ const filter = options?.filter === 'unread' ? 'unread' : 'all'
+ const category = typeof options?.category === 'string' && options.category ? options.category : null
+ const limit = Math.min(200, Math.max(1, Number(options?.limit) || 50))
+ const offset = Math.max(0, Number(options?.offset) || 0)
+
+ const whereParts = ['user_id = ?', 'deleted_at IS NULL']
+ const params: unknown[] = [userId]
+
+ if (filter === 'unread') {
+ whereParts.push('read_at IS NULL')
+ }
+ if (category) {
+ whereParts.push('category = ?')
+ params.push(category)
+ }
+
+ const whereSql = whereParts.join(' AND ')
+
+ const [itemsRes, unreadCount, totalRow] = await Promise.all([
+ db
+ .prepare(
+ `SELECT id, user_id, notification_key, category, title, body, target_url,
+ metadata_json, sent_at, status, error, read_at, deleted_at, push_sent_at
+ FROM notification_history
+ WHERE ${whereSql}
+ ORDER BY sent_at DESC, rowid DESC
+ LIMIT ? OFFSET ?`
+ )
+ .bind(...params, limit, offset)
+ .all(),
+ countUnreadForUser(db, userId),
+ db
+ .prepare(
+ 'SELECT COUNT(*) AS cnt FROM notification_history WHERE user_id = ? AND deleted_at IS NULL'
+ )
+ .bind(userId)
+ .first<{ cnt: number }>(),
+ ])
+
+ return {
+ items: itemsRes.results || [],
+ unread_count: unreadCount,
+ total_count: Number(totalRow?.cnt ?? 0),
+ }
+}
+
+export async function getUnreadNotificationCount(userId: string, syncToday = true): Promise {
+ const db = getDb()
+ if (syncToday !== false) {
+ await ensureDailyNotificationsForUser(db, userId)
+ }
+ return countUnreadForUser(db, userId)
+}
+
+async function softMutateNotifications(
+ userId: string,
+ sql: string,
+ bindings: unknown[]
+): Promise<{ changes: number; unread_count: number }> {
+ const db = getDb()
+ 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 countRow = countRes.results?.[0] as { cnt?: number } | undefined
+ return {
+ changes: Number(res.meta?.changes ?? 0),
+ unread_count: Number(countRow?.cnt ?? 0),
+ }
+}
+
+export async function markNotificationRead(
+ userId: string,
+ notificationId: string
+): Promise {
+ if (typeof notificationId !== 'string' || !notificationId.trim()) {
+ throw new RpcDomainError('VALIDATION_FAILED', '缺少合法的通知 ID')
+ }
+ const nowIso = new Date().toISOString()
+ const { changes, unread_count } = await softMutateNotifications(
+ userId,
+ `UPDATE notification_history
+ SET read_at = COALESCE(read_at, ?)
+ WHERE id = ? AND user_id = ? AND deleted_at IS NULL`,
+ [nowIso, notificationId.trim(), userId]
+ )
+ return { updated: changes > 0, unread_count }
+}
+
+export async function markAllNotificationsRead(userId: string): Promise {
+ const nowIso = new Date().toISOString()
+ const { changes, unread_count } = await softMutateNotifications(
+ userId,
+ `UPDATE notification_history
+ SET read_at = COALESCE(read_at, ?)
+ WHERE user_id = ? AND deleted_at IS NULL AND read_at IS NULL`,
+ [nowIso, userId]
+ )
+ return { updated_count: changes, unread_count }
+}
+
+export async function deleteNotification(
+ userId: string,
+ notificationId: string
+): Promise {
+ if (typeof notificationId !== 'string' || !notificationId.trim()) {
+ throw new RpcDomainError('VALIDATION_FAILED', '缺少合法的通知 ID')
+ }
+ const nowIso = new Date().toISOString()
+ const { changes, unread_count } = await softMutateNotifications(
+ userId,
+ `UPDATE notification_history
+ SET deleted_at = COALESCE(deleted_at, ?)
+ WHERE id = ? AND user_id = ? AND deleted_at IS NULL`,
+ [nowIso, notificationId.trim(), userId]
+ )
+ return { deleted: changes > 0, unread_count }
+}
+
+export async function deleteAllNotifications(userId: string): Promise {
+ const nowIso = new Date().toISOString()
+ const { changes, unread_count } = await softMutateNotifications(
+ userId,
+ `UPDATE notification_history
+ SET deleted_at = COALESCE(deleted_at, ?)
+ WHERE user_id = ? AND deleted_at IS NULL`,
+ [nowIso, userId]
+ )
+ return { deleted_count: changes, unread_count }
+}
diff --git a/lib/api/notifications.ts b/lib/api/notifications.ts
new file mode 100644
index 0000000..edd52c3
--- /dev/null
+++ b/lib/api/notifications.ts
@@ -0,0 +1,65 @@
+// lib/api/notifications.ts — client-side RPC wrappers (server: notifications.server.ts).
+import type * as Server from './notifications.server'
+import { callRpc } from './rpc-client'
+
+export type {
+ GetNotificationsOptions,
+ NotificationsPageResult,
+ NotificationReadResult,
+ NotificationBulkReadResult,
+ NotificationDeleteResult,
+ NotificationBulkDeleteResult,
+} from './notifications.server'
+
+export function getNotifications(options?: Server.GetNotificationsOptions) {
+ return callRpc('notifications', 'getNotifications', '', options)
+}
+
+export function getUnreadNotificationCount(syncToday?: boolean) {
+ return syncToday === undefined
+ ? callRpc(
+ 'notifications',
+ 'getUnreadNotificationCount',
+ ''
+ )
+ : callRpc(
+ 'notifications',
+ 'getUnreadNotificationCount',
+ '',
+ syncToday
+ )
+}
+
+export function markNotificationRead(notificationId: string) {
+ return callRpc(
+ 'notifications',
+ 'markNotificationRead',
+ '',
+ notificationId
+ )
+}
+
+export function markAllNotificationsRead() {
+ return callRpc(
+ 'notifications',
+ 'markAllNotificationsRead',
+ ''
+ )
+}
+
+export function deleteNotification(notificationId: string) {
+ return callRpc(
+ 'notifications',
+ 'deleteNotification',
+ '',
+ notificationId
+ )
+}
+
+export function deleteAllNotifications() {
+ return callRpc(
+ 'notifications',
+ 'deleteAllNotifications',
+ ''
+ )
+}
diff --git a/lib/api/preferences.server.ts b/lib/api/preferences.server.ts
index 9878b33..56f5dd2 100644
--- a/lib/api/preferences.server.ts
+++ b/lib/api/preferences.server.ts
@@ -2,6 +2,10 @@ import { queryOne, execute, uuid, now } from '../db'
import type { UserPreferences, UserDisplayConfig, UserReminderConfig } from '../types'
import { DEFAULT_DISPLAY_CONFIG, DEFAULT_REMINDER_CONFIG } from './preferences.shared'
import { mergeOpportunityReminderConfig } from '../opportunities/reminders'
+import {
+ resolveNotificationSwitches,
+ syncItemSwitchesWithOpportunities,
+} from '../notifications.shared'
export { DEFAULT_DISPLAY_CONFIG, DEFAULT_REMINDER_CONFIG }
@@ -26,15 +30,21 @@ export async function getUserPreferences(userId: string): Promise {
const current = await getUserPreferences(userId)
const updatedDisplay = { ...current.display_config, ...(updates.display_config || {}) }
- // 更新只覆盖给出字段;opportunities 子树整体替换(客户端提交完整子树,
- // 服务端在读取时再深合并默认值并校验)。
- const updatedReminder = { ...current.reminder_config, ...(updates.reminder_config || {}) }
+ const incomingReminder = updates.reminder_config || {}
+
+ // 合并 items,并保持 items.opportunity_reset/booking 与 opportunities.reset_enabled/booking_enabled 双向一致
+ const { items: mergedItems, opportunities: mergedOpp } = syncItemSwitchesWithOpportunities(
+ current.reminder_config,
+ incomingReminder
+ )
+
+ // 更新只覆盖给出字段;opportunities 子树保留既有未传入字段。
+ const updatedReminder: UserReminderConfig = {
+ ...current.reminder_config,
+ ...incomingReminder,
+ items: mergedItems,
+ opportunities: mergedOpp,
+ }
const existing = await queryOne('SELECT id FROM user_preferences WHERE user_id = ?', [userId])
if (existing.data) {
diff --git a/lib/api/preferences.shared.ts b/lib/api/preferences.shared.ts
index 17cf40c..e9795dc 100644
--- a/lib/api/preferences.shared.ts
+++ b/lib/api/preferences.shared.ts
@@ -2,6 +2,11 @@
// server implementation and the client wrappers (no database imports).
import type { UserDisplayConfig, UserReminderConfig } from '../types'
import { normalizeCurrencyOrDefault } from '../fx'
+import {
+ DEFAULT_ACTIVITY_DAYS,
+ DEFAULT_NOTIFICATION_ITEM_SWITCHES,
+ DEFAULT_TASK_DAYS,
+} from '../notifications.shared'
export const DEFAULT_DISPLAY_CONFIG: UserDisplayConfig = {
privacy_mode: false,
@@ -17,15 +22,16 @@ export const DEFAULT_REMINDER_CONFIG: UserReminderConfig = {
quiet_hours_start: '22:00',
quiet_hours_end: '08:00',
enabled_channels: ['web_push'],
+ items: { ...DEFAULT_NOTIFICATION_ITEM_SWITCHES },
opportunities: {
enabled: true,
web_push_enabled: true,
time_zone: 'Asia/Shanghai',
local_time: '09:00',
expiry_days_before: [3, 1, 0],
- activity_days_before: [7, 3, 1],
+ activity_days_before: [...DEFAULT_ACTIVITY_DAYS],
claim_days_before: [3, 1, 0],
- task_days_before: [3, 1, 0],
+ task_days_before: [...DEFAULT_TASK_DAYS],
reset_enabled: true,
booking_enabled: true,
},
diff --git a/lib/api/push.ts b/lib/api/push.ts
index 1cace82..fa6bb00 100644
--- a/lib/api/push.ts
+++ b/lib/api/push.ts
@@ -20,23 +20,9 @@ export interface TestPushResult {
/**
* 校验用户的提醒配置是否允许下发 Web Push。
- * 存量口径:若 enabled_channels 未显式设置,而旧 opportunities.web_push_enabled === false,则不开启。
+ * 统一委托给 notifications.shared.ts 单一真源。
*/
-export function isWebPushChannelEnabled(
- config?: {
- enabled_channels?: string[]
- opportunities?: { web_push_enabled?: boolean }
- } | null
-): boolean {
- if (!config) return true
- if (config.enabled_channels !== undefined) {
- return Array.isArray(config.enabled_channels) && config.enabled_channels.includes('web_push')
- }
- if (config.opportunities && config.opportunities.web_push_enabled === false) {
- return false
- }
- return true
-}
+export { isWebPushChannelEnabled } from '../notifications.shared'
/** 触发向当前用户订阅发送测试通知(收敛到统一 API 模块) */
export async function sendTestPush(): Promise {
diff --git a/lib/api/registry.ts b/lib/api/registry.ts
index fbb8d2d..482ee51 100644
--- a/lib/api/registry.ts
+++ b/lib/api/registry.ts
@@ -25,6 +25,7 @@ import * as emailBillsServer from './emailBills.server'
import * as gmailServer from './gmail.server'
import * as gmailLedgerServer from './gmail-ledger.server'
import * as holdersServer from './holders.server'
+import * as notificationsServer from './notifications.server'
import * as payablesServer from './payables.server'
// payments.ts 直接持有 db 访问(历史文件无 .server 拆分),registry 是
// server-only 模块,导入即并入服务端 bundle,符合现有约定。
@@ -286,6 +287,14 @@ export const RPC_REGISTRY: Record> = {
getUserPreferences: { impl: preferencesServer.getUserPreferences, bindUser: 0 },
updateUserPreferences: { impl: preferencesServer.updateUserPreferences, bindUser: 0 },
},
+ notifications: {
+ getNotifications: { impl: notificationsServer.getNotifications, bindUser: 0 },
+ getUnreadNotificationCount: { impl: notificationsServer.getUnreadNotificationCount, bindUser: 0 },
+ markNotificationRead: { impl: notificationsServer.markNotificationRead, bindUser: 0 },
+ markAllNotificationsRead: { impl: notificationsServer.markAllNotificationsRead, bindUser: 0 },
+ deleteNotification: { impl: notificationsServer.deleteNotification, bindUser: 0 },
+ deleteAllNotifications: { impl: notificationsServer.deleteAllNotifications, bindUser: 0 },
+ },
promos: {
getPromosWithBanks: { impl: promosServer.getPromosWithBanks, bindUser: 0 },
createUserPromo: { impl: promosServer.createUserPromo, admin: true },
diff --git a/lib/dashboard-metrics.ts b/lib/dashboard-metrics.ts
index 015abc6..4cc08e2 100644
--- a/lib/dashboard-metrics.ts
+++ b/lib/dashboard-metrics.ts
@@ -1,4 +1,5 @@
import type { BillDashboardItem } from './api/bills.server'
+import type { PayableWithStatus } from './api/payables.server'
import { currencySymbol, sumByCurrency } from './fx'
import type { FxRates } from './fx'
@@ -42,7 +43,8 @@ export function computeMetrics(
bills: BillDashboardItem[],
futureDays: FutureRange,
targetCurrency: string,
- rates: FxRates | null
+ rates: FxRates | null,
+ payables: PayableWithStatus[] = []
) {
// 只统计未还清的账单(§3.4)
const unpaid = bills.filter(b => b.computed_status !== 'paid')
@@ -61,6 +63,18 @@ export function computeMetrics(
const futureBills = unpaid.filter(b => b.days_until_due >= 0 && b.days_until_due <= futureDays)
const futureSum = sumByCurrency(futureBills, pickAmount, targetCurrency, rates)
+ // 当日待还:当天到期且尚未结清的信用卡账单 + 固定支出
+ const dueTodayBills = getDueTodayBills(bills)
+ const dueTodayPayables = getDueTodayPayables(payables)
+ const dueTodayEntries = [
+ ...dueTodayBills.map(pickAmount),
+ ...dueTodayPayables.map(p => ({
+ amount: payableRemaining(p),
+ currency: p.currency || targetCurrency,
+ })),
+ ]
+ const dueTodaySum = sumByCurrency(dueTodayEntries, entry => entry, targetCurrency, rates)
+
// 总欠款:当前数据模型仅"普通未还",分期/贷款暂未接入(§3.2)
const plainOwedSum = pendingSum
@@ -69,6 +83,10 @@ export function computeMetrics(
overdueAmount: overdueSum.total,
overdueBills,
futureAmount: futureSum.total,
+ dueTodayAmount: dueTodaySum.total,
+ dueTodayBills,
+ dueTodayPayables,
+ dueTodayCount: dueTodayBills.length + dueTodayPayables.length,
plainOwed: plainOwedSum.total,
unpaidCount: unpaid.length,
/** 汇率拿到没有:为 false 时下面的合计是不完整的,必须显式标注。 */
@@ -78,14 +96,20 @@ export function computeMetrics(
...pendingSum.unconverted_currencies,
...overdueSum.unconverted_currencies,
...futureSum.unconverted_currencies,
+ ...dueTodaySum.unconverted_currencies,
])).sort(),
- fx: { pending: pendingSum, overdue: overdueSum, future: futureSum, plainOwed: plainOwedSum },
+ fx: {
+ pending: pendingSum,
+ overdue: overdueSum,
+ future: futureSum,
+ dueToday: dueTodaySum,
+ plainOwed: plainOwedSum,
+ },
/** 当前口径下是否出现多币种,用于决定要不要展示币种构成。 */
mixed: pendingSum.mixed,
}
}
-
/**
* 「今天需还款」列表:当天到期、尚未结清、且还有剩余待还的账单。
*
@@ -99,6 +123,23 @@ export function getDueTodayBills(bills: BillDashboardItem[]): BillDashboardItem[
)
}
+/** 浮点结算精度容差(与服务端 remaining > 0.01 保持一致,排除已结清记录)。 */
+const SETTLED_AMOUNT_EPSILON = 0.01
+
+/** 统一计算固定支出剩余待付金额;缺失或非数值字段按约定静默兜底为 0。 */
+export function payableRemaining(p: { amount: unknown; paid_amount?: unknown }): number {
+ const amount = Number(p.amount)
+ const paid = Number(p.paid_amount ?? 0)
+ return Math.max(0, (Number.isFinite(amount) ? amount : 0) - (Number.isFinite(paid) ? paid : 0))
+}
+
+/** 当天到期、未结清且有剩余待付金额的固定支出列表。 */
+export function getDueTodayPayables(payables: PayableWithStatus[]): PayableWithStatus[] {
+ return payables.filter(
+ p => p.days_until_due === 0 && p.status !== 'paid' && payableRemaining(p) > SETTLED_AMOUNT_EPSILON
+ )
+}
+
/** 卡数统计:{ holderId: count } */
export function countCardsByHolder(cards: Array<{ holder_id: string }>): Record {
const map: Record = {}
diff --git a/lib/hooks/useUserPreferences.ts b/lib/hooks/useUserPreferences.ts
index e0fd505..c2038d0 100644
--- a/lib/hooks/useUserPreferences.ts
+++ b/lib/hooks/useUserPreferences.ts
@@ -10,6 +10,10 @@ import {
} from '../api/preferences'
import type { UserDisplayConfig, UserReminderConfig } from '../types'
import { resolveEffectiveChannels } from '@/components/settings/shared'
+import {
+ resolveNotificationSwitches,
+ syncItemSwitchesWithOpportunities,
+} from '../notifications.shared'
const PREF_CACHE_KEY = 'worldcredit_user_prefs_cache'
@@ -38,37 +42,61 @@ function showToastMessage(message: string) {
}, 3500)
}
+function getSafeStorage(): Storage | null {
+ if (typeof window === 'undefined') return null
+ try {
+ const storage =
+ (typeof localStorage !== 'undefined' ? localStorage : undefined) ?? window.localStorage
+ if (!storage || typeof storage.getItem !== 'function' || typeof storage.setItem !== 'function') {
+ return null
+ }
+ return storage
+ } catch {
+ return null
+ }
+}
+
+function readPrefCache(): Record {
+ const storage = getSafeStorage()
+ if (!storage) return {}
+ try {
+ const raw = storage.getItem(PREF_CACHE_KEY)
+ if (!raw) return {}
+ const parsed = JSON.parse(raw)
+ return parsed && typeof parsed === 'object' ? (parsed as Record) : {}
+ } catch {
+ return {}
+ }
+}
+
+function writePrefCache(patch: Record, merge = true): void {
+ const storage = getSafeStorage()
+ if (!storage) return
+ try {
+ const nextValue = merge ? { ...readPrefCache(), ...patch } : patch
+ storage.setItem(PREF_CACHE_KEY, JSON.stringify(nextValue))
+ } catch {
+ // ignore storage errors in restricted environments
+ }
+}
+
export function useUserPreferences() {
const { user } = useAuth()
const [displayConfig, setDisplayConfig] = useState(() => {
- if (typeof window !== 'undefined') {
- const cached = localStorage.getItem(PREF_CACHE_KEY)
- if (cached) {
- try {
- return JSON.parse(cached).display_config || DEFAULT_DISPLAY_CONFIG
- } catch {
- // ignore malformed cache, fall back to defaults
- }
- }
- }
- return DEFAULT_DISPLAY_CONFIG
+ const parsed = readPrefCache().display_config as UserDisplayConfig | undefined
+ return parsed || DEFAULT_DISPLAY_CONFIG
})
const [reminderConfig, setReminderConfig] = useState(() => {
- if (typeof window !== 'undefined') {
- const cached = localStorage.getItem(PREF_CACHE_KEY)
- if (cached) {
- try {
- const parsed = JSON.parse(cached).reminder_config
- if (parsed) {
- if (parsed.enabled_channels === undefined) {
- return { ...parsed, enabled_channels: resolveEffectiveChannels(parsed) }
- }
- return parsed
- }
- } catch {
- // ignore malformed cache, fall back to defaults
- }
+ const parsed = readPrefCache().reminder_config as UserReminderConfig | undefined
+ if (parsed) {
+ const withChannels =
+ parsed.enabled_channels === undefined
+ ? { ...parsed, enabled_channels: resolveEffectiveChannels(parsed) }
+ : parsed
+ return {
+ ...withChannels,
+ items: resolveNotificationSwitches(withChannels),
}
}
return DEFAULT_REMINDER_CONFIG
@@ -98,9 +126,7 @@ export function useUserPreferences() {
setDisplayConfig(prefs.display_config)
setReminderConfig(reminder)
- if (typeof window !== 'undefined') {
- localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...prefs, reminder_config: reminder }))
- }
+ writePrefCache({ ...prefs, reminder_config: reminder }, false)
} catch (err) {
console.error('Failed to load user preferences:', err)
setLoadError(err instanceof Error ? err.message : '加载偏好设置失败')
@@ -119,10 +145,7 @@ export function useUserPreferences() {
setDisplayConfig(nextDisplay)
// Update local cache immediately for snappy UI
- if (typeof window !== 'undefined') {
- const currentCache = JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}')
- localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...currentCache, display_config: nextDisplay }))
- }
+ writePrefCache({ display_config: nextDisplay })
if (user?.id) {
try {
@@ -130,10 +153,7 @@ export function useUserPreferences() {
} catch (err) {
// Rollback on write failure
setDisplayConfig(prev)
- if (typeof window !== 'undefined') {
- const currentCache = JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}')
- localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...currentCache, display_config: prev }))
- }
+ writePrefCache({ display_config: prev })
throw err
}
}
@@ -141,24 +161,27 @@ export function useUserPreferences() {
const updateReminder = async (updates: Partial) => {
const prev = reminderConfig
- const nextReminder = { ...reminderConfig, ...updates }
+ const { items: mergedItems, opportunities: mergedOpp } = syncItemSwitchesWithOpportunities(
+ reminderConfig,
+ updates
+ )
+ const nextReminder: UserReminderConfig = {
+ ...reminderConfig,
+ ...updates,
+ items: mergedItems,
+ opportunities: mergedOpp,
+ }
setReminderConfig(nextReminder)
- if (typeof window !== 'undefined') {
- const currentCache = JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}')
- localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...currentCache, reminder_config: nextReminder }))
- }
+ writePrefCache({ reminder_config: nextReminder })
if (user?.id) {
try {
- await updateUserPreferences(user.id, { reminder_config: nextReminder })
+ await updateUserPreferences(user.id, { reminder_config: updates })
} catch (err) {
// Rollback on write failure
setReminderConfig(prev)
- if (typeof window !== 'undefined') {
- const currentCache = JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}')
- localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...currentCache, reminder_config: prev }))
- }
+ writePrefCache({ reminder_config: prev })
throw err
}
}
diff --git a/lib/notifications-engine.server.ts b/lib/notifications-engine.server.ts
new file mode 100644
index 0000000..98d578c
--- /dev/null
+++ b/lib/notifications-engine.server.ts
@@ -0,0 +1,686 @@
+// lib/notifications-engine.server.ts — 每日主动通知候选生成与站内通知落库引擎。
+//
+// 显式接收 D1Database 参数,供 worker/cron.ts 与 lib/api/notifications.server.ts 共用:
+// - 站内读取通知中心/未读数时幂等补齐当日通知(status='skipped', push_sent_at=NULL);
+// - 每日 Cron 扫表时补发 Web Push / APNs(跳过已读、已删、已推送、免打扰时段),并写入 push_sent_at。
+
+import { categoryLabel, type PayableCategory, type PayableCycleType } from './api/payables.shared'
+import {
+ computeCardGraceWindowOnDate,
+ formatCurrencyBuckets,
+ formatMoneySingle,
+ isInQuietHours,
+ isNewLongestGracePeriodDay,
+ resolveNotificationSwitches,
+ type NotificationBillMetadataItem,
+ type NotificationGraceCardMetadataItem,
+ type NotificationMetadata,
+ type NotificationPayableMetadataItem,
+} from './notifications.shared'
+import type { CardProduct, NotificationCategory, UserReminderConfig } from './types'
+import { getLocalTodayString, nextPayablePeriodOf, payableDueDate, payablePeriodOf } from './utils'
+
+export interface DailyNotificationCandidate {
+ notification_key: string
+ category: NotificationCategory
+ title: string
+ body: string
+ target_url: string
+ metadata_json: string | null
+}
+
+export interface UserNotificationContext {
+ userId: string
+ reminderConfigRaw: string | null
+ reminderConfig: UserReminderConfig
+ remindDaysBefore: number[]
+ timeZone: string
+ quietHoursStart?: string
+ quietHoursEnd?: string
+}
+
+interface BillQueryRow {
+ id: string
+ account_id: string | null
+ card_id: string
+ bill_month: string
+ effective_amount: number
+ effective_due_date: string
+ effective_statement_date: string | null
+ statement_end: string | null
+ status: string
+ holder_id: string
+ bank_name: string | null
+ card_name: string | null
+ currency: string | null
+ name_override: string | null
+ card_number_last4: string | null
+ account_statement_mode: string | null
+ paid_amount: number
+}
+
+interface PayableQueryRow {
+ id: string
+ name: string
+ category: PayableCategory
+ custom_category: string | null
+ amount: number
+ currency: string
+ cycle_type: PayableCycleType | null
+ cycle_months: number | null
+ due_month: number | null
+ due_day: number
+ anchor_period: string | null
+ created_at: string
+}
+
+interface CreditCardGraceRow {
+ id: string
+ holder_id: string
+ account_id: string | null
+ billing_day: number
+ override_billing_day: number | null
+ override_due_type: CardProduct['payment_due_type'] | null
+ override_due_value: number | null
+ name_override: string | null
+ card_number_last4: string | null
+ bank_name: string | null
+ card_name: string | null
+ payment_due_type: CardProduct['payment_due_type'] | null
+ payment_due_value: number | null
+ account_statement_mode: string | null
+}
+
+function parseCivilDateUTC(dateStr: string): number {
+ const m = /^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(dateStr.trim())
+ if (!m) return Number.NaN
+ const year = Number(m[1])
+ const month = Number(m[2])
+ const day = Number(m[3])
+ const ts = Date.UTC(year, month - 1, day)
+ const verify = new Date(ts)
+ if (
+ verify.getUTCFullYear() !== year ||
+ verify.getUTCMonth() !== month - 1 ||
+ verify.getUTCDate() !== day
+ ) {
+ return Number.NaN
+ }
+ return ts
+}
+
+function diffCivilDays(targetStr: string, todayStr: string): number {
+ const t = parseCivilDateUTC(targetStr)
+ const c = parseCivilDateUTC(todayStr)
+ if (!Number.isFinite(t) || !Number.isFinite(c)) return Number.NaN
+ return Math.round((t - c) / 86_400_000)
+}
+
+function encodeMetadata(meta: NotificationMetadata): string {
+ return JSON.stringify(meta)
+}
+
+function civilDateFromTodayStr(todayStr: string): Date {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(todayStr)
+ if (!m) return new Date()
+ return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]))
+}
+
+function formatPayableDueDateStr(dueDay: number, period: string): string {
+ const d = payableDueDate(dueDay, period)
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
+}
+
+export interface PrefetchedUserNotificationPrefs {
+ reminderConfigRaw: string | null
+ legacyRow: { bill_due_enabled: number; overdue_enabled: number; due_days_before: number } | null
+}
+
+export async function loadUserNotificationContext(
+ db: D1Database,
+ userId: string,
+ prefetched?: PrefetchedUserNotificationPrefs
+): Promise {
+ const [prefRow, legacyRow] = prefetched
+ ? [
+ prefetched.reminderConfigRaw != null ? { reminder_config: prefetched.reminderConfigRaw } : null,
+ prefetched.legacyRow,
+ ]
+ : await Promise.all([
+ db
+ .prepare('SELECT reminder_config FROM user_preferences WHERE user_id = ?')
+ .bind(userId)
+ .first<{ reminder_config: string }>(),
+ db
+ .prepare('SELECT bill_due_enabled, overdue_enabled, due_days_before FROM notification_preferences WHERE user_id = ?')
+ .bind(userId)
+ .first<{ bill_due_enabled: number; overdue_enabled: number; due_days_before: number }>(),
+ ])
+
+ if (prefRow?.reminder_config) {
+ try {
+ const parsed = JSON.parse(prefRow.reminder_config) as Partial
+ const remindDaysBefore = Array.isArray(parsed.remind_days_before)
+ ? parsed.remind_days_before.filter((d): d is number => typeof d === 'number' && Number.isInteger(d))
+ : [3, 1, 0]
+ const mergedItemsInput = legacyRow
+ ? {
+ ...parsed.items,
+ bill_due_today: parsed.items?.bill_due_today ?? (legacyRow.bill_due_enabled === 1),
+ bill_due_advance: parsed.items?.bill_due_advance ?? (legacyRow.bill_due_enabled === 1),
+ bill_overdue: parsed.items?.bill_overdue ?? (legacyRow.overdue_enabled === 1),
+ }
+ : parsed.items
+ const mergedConfig: UserReminderConfig = {
+ remind_days_before: remindDaysBefore,
+ quiet_hours_start: parsed.quiet_hours_start ?? '22:00',
+ quiet_hours_end: parsed.quiet_hours_end ?? '08:00',
+ enabled_channels: Array.isArray(parsed.enabled_channels) ? parsed.enabled_channels : ['web_push'],
+ items: resolveNotificationSwitches({ ...parsed, items: mergedItemsInput }),
+ opportunities: parsed.opportunities,
+ }
+ return {
+ userId,
+ reminderConfigRaw: prefRow.reminder_config,
+ reminderConfig: mergedConfig,
+ remindDaysBefore,
+ timeZone: parsed.opportunities?.time_zone || 'Asia/Shanghai',
+ quietHoursStart: mergedConfig.quiet_hours_start,
+ quietHoursEnd: mergedConfig.quiet_hours_end,
+ }
+ } catch {
+ // Fall through to legacy/default below if stored JSON is corrupted
+ }
+ }
+
+ if (legacyRow) {
+ const dueDays = Math.max(0, Math.min(30, Number(legacyRow.due_days_before ?? 3)))
+ const remindDaysBefore = Array.from({ length: dueDays + 1 }, (_, i) => i)
+ const billDueOn = legacyRow.bill_due_enabled === 1
+ const overdueOn = legacyRow.overdue_enabled === 1
+ const fallbackConfig: UserReminderConfig = {
+ remind_days_before: remindDaysBefore,
+ quiet_hours_start: '22:00',
+ quiet_hours_end: '08:00',
+ enabled_channels: ['web_push'],
+ items: resolveNotificationSwitches({
+ items: {
+ bill_due_today: billDueOn,
+ bill_due_advance: billDueOn,
+ bill_overdue: overdueOn,
+ },
+ }),
+ }
+ return {
+ userId,
+ reminderConfigRaw: null,
+ reminderConfig: fallbackConfig,
+ remindDaysBefore,
+ timeZone: 'Asia/Shanghai',
+ quietHoursStart: '22:00',
+ quietHoursEnd: '08:00',
+ }
+ }
+
+ const defaultConfig: UserReminderConfig = {
+ remind_days_before: [3, 1, 0],
+ quiet_hours_start: '22:00',
+ quiet_hours_end: '08:00',
+ enabled_channels: ['web_push'],
+ items: resolveNotificationSwitches(null),
+ }
+ return {
+ userId,
+ reminderConfigRaw: null,
+ reminderConfig: defaultConfig,
+ remindDaysBefore: [3, 1, 0],
+ timeZone: 'Asia/Shanghai',
+ quietHoursStart: '22:00',
+ quietHoursEnd: '08:00',
+ }
+}
+
+export function isUserInQuietHours(ctx: UserNotificationContext, now: Date = new Date()): boolean {
+ return isInQuietHours(now, ctx.timeZone, ctx.quietHoursStart, ctx.quietHoursEnd)
+}
+
+export async function buildDailyNotificationCandidates(
+ db: D1Database,
+ userId: string,
+ todayStr?: string,
+ options?: { now?: Date; prefetched?: PrefetchedUserNotificationPrefs }
+): Promise<{ context: UserNotificationContext; candidates: DailyNotificationCandidate[] }> {
+ const context = await loadUserNotificationContext(db, userId, options?.prefetched)
+ const effectiveToday = todayStr ?? getLocalTodayString(context.timeZone, options?.now)
+ const switches = resolveNotificationSwitches(context.reminderConfig)
+ const advanceDays = new Set(context.remindDaysBefore.filter(d => Number.isInteger(d) && d > 0))
+ const candidates: DailyNotificationCandidate[] = []
+
+ // 1-2 & 4. 并发读取未结清账单、活跃固定支出与最长免息期候选卡
+ const [billStmt, payableStmt, cardsStmt] = await Promise.all([
+ db
+ .prepare(
+ `SELECT b.id, COALESCE(b.account_id, cc.account_id) AS account_id, b.card_id, b.bill_month,
+ COALESCE(b.bill_amount_override, b.bill_amount) AS effective_amount,
+ COALESCE(b.due_date_override, b.due_date) AS effective_due_date,
+ COALESCE(b.statement_date_override, b.statement_date) AS effective_statement_date,
+ b.statement_end,
+ b.status,
+ ch.id AS holder_id,
+ cp.bank_name, cp.card_name, COALESCE(cp.currency, 'CNY') AS currency,
+ cc.name_override, cc.card_number_last4,
+ ca.statement_mode AS account_statement_mode,
+ (SELECT COALESCE(SUM(p.amount), 0) FROM payments p WHERE p.bill_id = b.id) AS paid_amount
+ FROM bills b
+ JOIN credit_cards cc ON b.card_id = cc.id
+ JOIN card_holders ch ON cc.holder_id = ch.id
+ LEFT JOIN card_products cp ON cc.card_product_id = cp.id
+ LEFT JOIN credit_accounts ca ON (b.account_id = ca.id OR (b.account_id IS NULL AND cc.account_id = ca.id))
+ WHERE (ch.created_by = ? OR ch.managed_by = ? OR ch.auth_user_id = ?)
+ AND b.status IN ('unpaid', 'partial', 'overdue')`
+ )
+ .bind(userId, userId, userId)
+ .all(),
+ db
+ .prepare(
+ `SELECT id, name, category, custom_category, amount, currency,
+ cycle_type, cycle_months, due_month, due_day, anchor_period, created_at
+ FROM recurring_payables
+ WHERE created_by = ? AND is_active = 1
+ ORDER BY due_day ASC`
+ )
+ .bind(userId)
+ .all(),
+ switches.grace_period_longest
+ ? db
+ .prepare(
+ `SELECT cc.id, cc.holder_id, cc.account_id, cc.billing_day, cc.override_billing_day,
+ cc.override_due_type, cc.override_due_value, cc.name_override, cc.card_number_last4,
+ cp.bank_name, cp.card_name, cp.payment_due_type, cp.payment_due_value,
+ ca.statement_mode AS account_statement_mode
+ FROM credit_cards cc
+ JOIN card_holders ch ON cc.holder_id = ch.id
+ LEFT JOIN card_products cp ON cc.card_product_id = cp.id
+ LEFT JOIN credit_accounts ca ON cc.account_id = ca.id
+ WHERE (ch.created_by = ? OR ch.managed_by = ? OR ch.auth_user_id = ?)
+ AND cc.status = 'active'
+ AND COALESCE(cc.card_type, 'credit') = 'credit'`
+ )
+ .bind(userId, userId, userId)
+ .all()
+ : Promise.resolve(null),
+ ])
+
+ const unpaidBills = (billStmt.results || []).filter(row => {
+ const remaining = Math.max(0, Number(row.effective_amount || 0) - Number(row.paid_amount || 0))
+ return remaining > 0.01
+ })
+
+ // 批量读取合并账户的 active 成员卡信息,用于合并账单提示文案
+ const mergedAccountIds = Array.from(
+ new Set(
+ unpaidBills
+ .filter(b => b.account_statement_mode === 'merged' && b.account_id)
+ .map(b => b.account_id as string)
+ )
+ )
+ const accountCardsMap: Record = {}
+ if (mergedAccountIds.length > 0) {
+ const placeholders = mergedAccountIds.map(() => '?').join(',')
+ const memberStmt = await db
+ .prepare(
+ `SELECT account_id, card_number_last4
+ FROM credit_cards
+ WHERE account_id IN (${placeholders}) AND status = 'active'
+ ORDER BY created_at ASC`
+ )
+ .bind(...mergedAccountIds)
+ .all<{ account_id: string; card_number_last4: string | null }>()
+ for (const mc of memberStmt.results || []) {
+ if (!accountCardsMap[mc.account_id]) {
+ accountCardsMap[mc.account_id] = { count: 0, firstTail: mc.card_number_last4 || '' }
+ }
+ accountCardsMap[mc.account_id].count++
+ }
+ }
+
+ const formatBillSubject = (b: BillQueryRow): string => {
+ const bankPrefix = b.bank_name || ''
+ const accInfo = b.account_id ? accountCardsMap[b.account_id] : null
+ if (b.account_statement_mode === 'merged' && accInfo && accInfo.count > 1) {
+ return `${bankPrefix}合并账单(含尾号 ${accInfo.firstTail} 等 ${accInfo.count} 张卡)`.trim()
+ }
+ const cardName = b.name_override || b.card_name || ''
+ const tail = b.card_number_last4 ? ` 尾号${b.card_number_last4}` : ''
+ return `${bankPrefix} ${cardName}${tail}`.trim() || '信用卡'
+ }
+
+ // 2. 评估活跃固定支出(与 payables.server.ts 同滚动账期口径)
+ const payableRows = payableStmt.results || []
+ const todayDate = civilDateFromTodayStr(effectiveToday)
+
+ interface PayableEval {
+ row: PayableQueryRow
+ period: string
+ dueDate: string
+ daysUntil: number
+ remaining: number
+ categoryText: string
+ }
+ const activePayables: PayableEval[] = []
+ if (payableRows.length > 0) {
+ const payableIds = payableRows.map(p => p.id)
+ const placeholders = payableIds.map(() => '?').join(',')
+ const payStmt = await db
+ .prepare(
+ `SELECT payable_id, period, SUM(amount) AS total
+ FROM recurring_payable_payments
+ WHERE payable_id IN (${placeholders})
+ GROUP BY payable_id, period`
+ )
+ .bind(...payableIds)
+ .all<{ payable_id: string; period: string; total: number }>()
+ const paidMap = new Map()
+ for (const p of payStmt.results || []) {
+ paidMap.set(`${p.payable_id}:${p.period}`, Number(p.total || 0))
+ }
+
+ for (const row of payableRows) {
+ const cycle = {
+ cycle_type: row.cycle_type ?? 'monthly',
+ cycle_months: row.cycle_months ?? 1,
+ due_month: row.due_month ?? null,
+ due_day: row.due_day,
+ anchor_period: row.anchor_period ?? null,
+ created_at: row.created_at,
+ }
+ const currentPeriod = payablePeriodOf(todayDate, cycle)
+ const amount = Number(row.amount) || 0
+ const paidCurrent = paidMap.get(`${row.id}:${currentPeriod}`) ?? 0
+ const settledCurrent = amount > 0 && paidCurrent >= amount - 0.01
+ const nextPeriod = nextPayablePeriodOf(currentPeriod, cycle)
+ const nextDueStr = formatPayableDueDateStr(row.due_day, nextPeriod)
+
+ let displayPeriod = currentPeriod
+ let displayPaid = paidCurrent
+ const nextDiff = diffCivilDays(nextDueStr, effectiveToday)
+ if (settledCurrent && Number.isFinite(nextDiff) && nextDiff < 30) {
+ displayPeriod = nextPeriod
+ displayPaid = paidMap.get(`${row.id}:${nextPeriod}`) ?? 0
+ }
+
+ const remaining = Math.max(0, amount - displayPaid)
+ if (remaining <= 0.01) continue
+
+ const dueDateStr = formatPayableDueDateStr(row.due_day, displayPeriod)
+ const daysUntil = diffCivilDays(dueDateStr, effectiveToday)
+ if (!Number.isFinite(daysUntil)) continue
+ activePayables.push({
+ row,
+ period: displayPeriod,
+ dueDate: dueDateStr,
+ daysUntil,
+ remaining,
+ categoryText: categoryLabel(row.category, row.custom_category),
+ })
+ }
+ }
+
+ // 3. 汇总「当日待还款账单(包含固定支出)」主动通知
+ const dueTodayBillEntries: NotificationBillMetadataItem[] = []
+ const dueTodayPayableEntries: NotificationPayableMetadataItem[] = []
+
+ for (const bill of unpaidBills) {
+ const daysUntil = diffCivilDays(bill.effective_due_date, effectiveToday)
+ if (!Number.isFinite(daysUntil)) continue
+ const remaining = Math.max(0, Number(bill.effective_amount || 0) - Number(bill.paid_amount || 0))
+ const currency = bill.currency || 'CNY'
+ const subject = formatBillSubject(bill)
+ const stmtDate = bill.effective_statement_date || bill.statement_end
+ const stmtDiff = stmtDate ? diffCivilDays(stmtDate, effectiveToday) : Number.NaN
+ const isUnissued = Number.isFinite(stmtDiff) && stmtDiff > 0
+
+ if (daysUntil === 0) {
+ if (switches.bill_due_today) {
+ dueTodayBillEntries.push({
+ id: bill.id,
+ subject,
+ remaining,
+ currency,
+ due_date: bill.effective_due_date,
+ })
+ }
+ } else if (daysUntil < 0 && !isUnissued) {
+ if (switches.bill_overdue) {
+ const amtStr = formatMoneySingle(remaining, currency)
+ candidates.push({
+ notification_key: `bill_overdue:${bill.id}:${effectiveToday}`,
+ category: 'bill_overdue',
+ title: `已逾期:${subject}`,
+ body: `${subject} 账单剩余待还 ${amtStr},已逾期 ${Math.abs(daysUntil)} 天(到期日 ${bill.effective_due_date})。`,
+ target_url: `/bills/${bill.id}`,
+ metadata_json: encodeMetadata({
+ kind: 'bill_overdue',
+ bill_id: bill.id,
+ remaining,
+ currency,
+ days_overdue: Math.abs(daysUntil),
+ due_date: bill.effective_due_date,
+ }),
+ })
+ }
+ } else if (daysUntil > 0 && advanceDays.has(daysUntil)) {
+ if (switches.bill_due_advance) {
+ const amtStr = formatMoneySingle(remaining, currency)
+ candidates.push({
+ notification_key: `bill:${bill.id}:${effectiveToday}`,
+ category: 'bill_due_advance',
+ title: daysUntil === 1 ? `明天到期:${subject}` : `${daysUntil}天后还款:${subject}`,
+ body: `${subject} 账单剩余待还 ${amtStr},将于 ${daysUntil} 天后(${bill.effective_due_date})到期。`,
+ target_url: `/bills/${bill.id}`,
+ metadata_json: encodeMetadata({
+ kind: 'bill_due_advance',
+ bill_id: bill.id,
+ remaining,
+ currency,
+ days_until_due: daysUntil,
+ due_date: bill.effective_due_date,
+ }),
+ })
+ }
+ }
+ }
+
+ for (const p of activePayables) {
+ if (p.daysUntil === 0) {
+ if (switches.payable_due_today) {
+ dueTodayPayableEntries.push({
+ id: p.row.id,
+ name: p.row.name,
+ category: p.categoryText,
+ remaining: p.remaining,
+ currency: p.row.currency || 'CNY',
+ due_date: p.dueDate,
+ })
+ }
+ } else if (p.daysUntil < 0) {
+ if (switches.bill_overdue) {
+ const amtStr = formatMoneySingle(p.remaining, p.row.currency || 'CNY')
+ candidates.push({
+ notification_key: `payable_overdue:${p.row.id}:${effectiveToday}`,
+ category: 'bill_overdue',
+ title: `固定支出已逾期:${p.row.name}`,
+ body: `${p.row.name}(${p.categoryText})本期应付 ${amtStr},已逾期 ${Math.abs(p.daysUntil)} 天(应付日 ${p.dueDate})。`,
+ target_url: '/bills',
+ metadata_json: encodeMetadata({
+ kind: 'payable_overdue',
+ payable_id: p.row.id,
+ remaining: p.remaining,
+ currency: p.row.currency || 'CNY',
+ days_overdue: Math.abs(p.daysUntil),
+ due_date: p.dueDate,
+ }),
+ })
+ }
+ } else if (p.daysUntil > 0 && advanceDays.has(p.daysUntil)) {
+ if (switches.payable_due_advance) {
+ const amtStr = formatMoneySingle(p.remaining, p.row.currency || 'CNY')
+ candidates.push({
+ notification_key: `payable:${p.row.id}:${effectiveToday}`,
+ category: 'payable_due_advance',
+ title: p.daysUntil === 1 ? `固定支出明天到期:${p.row.name}` : `${p.daysUntil}天后应付:${p.row.name}`,
+ body: `${p.row.name}(${p.categoryText})本期应付 ${amtStr},将于 ${p.daysUntil} 天后(${p.dueDate})到期。`,
+ target_url: '/bills',
+ metadata_json: encodeMetadata({
+ kind: 'payable_due_advance',
+ payable_id: p.row.id,
+ remaining: p.remaining,
+ currency: p.row.currency || 'CNY',
+ days_until_due: p.daysUntil,
+ due_date: p.dueDate,
+ }),
+ })
+ }
+ }
+ }
+
+ const totalDueTodayCount = dueTodayBillEntries.length + dueTodayPayableEntries.length
+ if (totalDueTodayCount > 0) {
+ const totalsByCurrency: Record = {}
+ const lines: string[] = []
+ for (const item of dueTodayBillEntries) {
+ totalsByCurrency[item.currency] = (totalsByCurrency[item.currency] || 0) + item.remaining
+ lines.push(`• [信用卡] ${item.subject}:${formatMoneySingle(item.remaining, item.currency)}`)
+ }
+ for (const item of dueTodayPayableEntries) {
+ totalsByCurrency[item.currency] = (totalsByCurrency[item.currency] || 0) + item.remaining
+ lines.push(`• [固定支出·${item.category}] ${item.name}:${formatMoneySingle(item.remaining, item.currency)}`)
+ }
+ const totalLabel = formatCurrencyBuckets(totalsByCurrency)
+ const category: NotificationCategory =
+ dueTodayBillEntries.length === 0 ? 'payable_due_today' : 'bill_due_today'
+ candidates.unshift({
+ notification_key: `due_today_summary:${effectiveToday}`,
+ category,
+ title: `今日待还款 ${totalLabel}(共 ${totalDueTodayCount} 笔)`,
+ body: `今天需完成以下 ${totalDueTodayCount} 笔还款:\n${lines.join('\n')}`,
+ target_url: '/dashboard',
+ metadata_json: encodeMetadata({
+ kind: 'due_today_summary',
+ date: effectiveToday,
+ totals_by_currency: totalsByCurrency,
+ bills: dueTodayBillEntries,
+ payables: dueTodayPayableEntries,
+ }),
+ })
+ }
+
+ // 4. 今日新增最长免息期账单(昨日为账单日 → 今日进入最长免息期首日)
+ if (switches.grace_period_longest && cardsStmt) {
+ const groupedHits = new Map()
+
+ for (const card of cardsStmt.results || []) {
+ const effectiveBillingDay = Number(card.override_billing_day ?? card.billing_day ?? 10)
+ if (!isNewLongestGracePeriodDay(effectiveBillingDay, effectiveToday)) continue
+
+ const win = computeCardGraceWindowOnDate(
+ {
+ billing_day: card.billing_day ?? 10,
+ override_billing_day: card.override_billing_day,
+ override_due_type: card.override_due_type,
+ override_due_value: card.override_due_value,
+ payment_due_type: card.payment_due_type ?? 'after_billing',
+ payment_due_value: card.payment_due_value ?? 20,
+ },
+ effectiveToday
+ )
+ const isMerged = card.account_statement_mode === 'merged' && Boolean(card.account_id)
+ const groupKey = isMerged ? `account:${card.account_id}` : `card:${card.id}`
+ const bank = card.bank_name || ''
+ const cardTitle = card.name_override || card.card_name || '信用卡'
+ const tail = card.card_number_last4 ? `(尾号 ${card.card_number_last4})` : ''
+ const label = isMerged
+ ? `${bank} 合并账户${tail}`.trim()
+ : `${bank} ${cardTitle}${tail}`.trim()
+
+ const existing = groupedHits.get(groupKey)
+ if (!existing || win.graceDays > existing.graceDays) {
+ groupedHits.set(groupKey, {
+ cardId: card.id,
+ label,
+ graceDays: win.graceDays,
+ nextBillingDate: win.nextBillingDate,
+ nextDueDate: win.nextDueDate,
+ })
+ }
+ }
+
+ const graceHits = Array.from(groupedHits.values()).sort(
+ (a, b) => b.graceDays - a.graceDays || a.cardId.localeCompare(b.cardId)
+ )
+ if (graceHits.length > 0) {
+ const lines = graceHits.map(
+ h => `• ${h.label}:今日刷卡可享 ${h.graceDays} 天免息(下期账单日 ${h.nextBillingDate},还款日 ${h.nextDueDate})`
+ )
+ const title =
+ graceHits.length === 1
+ ? `今日新增最长免息期:${graceHits[0].label}(${graceHits[0].graceDays} 天)`
+ : `今日新增 ${graceHits.length} 张最长免息期卡(最长 ${graceHits[0].graceDays} 天)`
+ const body =
+ graceHits.length === 1
+ ? `${graceHits[0].label} 昨日刚出账单,今天进入本轮最长免息期,刷卡可享 ${graceHits[0].graceDays} 天免息(下期账单日 ${graceHits[0].nextBillingDate},还款日 ${graceHits[0].nextDueDate})。`
+ : `以下卡片昨日刚过账单日,今天新进入本轮最长免息期:\n${lines.join('\n')}`
+ candidates.push({
+ notification_key: `grace_longest:${effectiveToday}`,
+ category: 'grace_period_longest',
+ title,
+ body,
+ target_url: graceHits.length === 1 ? `/cards/${graceHits[0].cardId}` : '/bills',
+ metadata_json: encodeMetadata({
+ kind: 'grace_period_longest',
+ date: effectiveToday,
+ cards: graceHits,
+ }),
+ })
+ }
+ }
+
+ return { context, candidates }
+}
+
+/**
+ * 幂等把今日应生成的站内通知写入 notification_history(status='skipped', push_sent_at=NULL)。
+ * 若同 (user_id, notification_key) 已存在(含已读或已软删除),OR IGNORE 保持原状不复活。
+ */
+export async function ensureDailyNotificationsForUser(
+ db: D1Database,
+ userId: string,
+ todayStr?: string,
+ nowIso: string = new Date().toISOString()
+): Promise {
+ const { candidates } = await buildDailyNotificationCandidates(db, userId, todayStr, {
+ now: new Date(nowIso),
+ })
+ if (candidates.length === 0) return 0
+
+ const stmtSql = `INSERT OR IGNORE INTO notification_history
+ (id, user_id, notification_key, category, title, body, target_url, metadata_json, sent_at, status, push_sent_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'skipped', NULL)`
+ const statements = candidates.map(candidate =>
+ db
+ .prepare(stmtSql)
+ .bind(
+ crypto.randomUUID(),
+ userId,
+ candidate.notification_key,
+ candidate.category,
+ candidate.title,
+ candidate.body,
+ candidate.target_url,
+ candidate.metadata_json,
+ nowIso
+ )
+ )
+ const results = await db.batch(statements)
+ return results.reduce((sum, res) => sum + Number(res.meta?.changes ?? 0), 0)
+}
diff --git a/lib/notifications.shared.ts b/lib/notifications.shared.ts
new file mode 100644
index 0000000..3af1452
--- /dev/null
+++ b/lib/notifications.shared.ts
@@ -0,0 +1,463 @@
+// lib/notifications.shared.ts — 通知中心与全通知项开关的纯类型、常量与日期计算(无 DB 依赖)。
+
+import { currencySymbol } from './fx'
+import type {
+ CardProduct,
+ NotificationCategory,
+ NotificationItemSwitches,
+ UserReminderConfig,
+} from './types'
+
+export const DEFAULT_ACTIVITY_DAYS: number[] = [7, 3, 1]
+export const DEFAULT_TASK_DAYS: number[] = [3, 1, 0]
+
+export interface NotificationBillMetadataItem {
+ id: string
+ subject: string
+ remaining: number
+ currency: string
+ due_date: string
+}
+
+export interface NotificationPayableMetadataItem {
+ id: string
+ name: string
+ category: string
+ remaining: number
+ currency: string
+ due_date: string
+}
+
+export interface NotificationGraceCardMetadataItem {
+ cardId: string
+ label: string
+ graceDays: number
+ nextBillingDate: string
+ nextDueDate: string
+}
+
+export interface NotificationMetadata {
+ kind?: string
+ date?: string
+ due_date?: string
+ bill_id?: string
+ payable_id?: string
+ remaining?: number
+ currency?: string
+ days_until_due?: number
+ days_overdue?: number
+ totals_by_currency?: Record
+ bills?: NotificationBillMetadataItem[]
+ payables?: NotificationPayableMetadataItem[]
+ cards?: NotificationGraceCardMetadataItem[]
+ event_key?: string
+ delivery_key?: string
+ object_id?: string
+}
+
+export const DEFAULT_NOTIFICATION_ITEM_SWITCHES: NotificationItemSwitches = {
+ bill_due_today: true,
+ payable_due_today: true,
+ bill_due_advance: true,
+ payable_due_advance: true,
+ bill_overdue: true,
+ grace_period_longest: true,
+ opportunity_expiry: true,
+ opportunity_claim: true,
+ opportunity_activity: true,
+ opportunity_task: true,
+ opportunity_reset: true,
+ opportunity_booking: true,
+}
+
+export const NOTIFICATION_SWITCH_ITEMS: Array<{
+ key: keyof NotificationItemSwitches
+ group: 'bills' | 'opportunities'
+ label: string
+ description: string
+}> = [
+ {
+ key: 'bill_due_today',
+ group: 'bills',
+ label: '当日待还信用卡账单',
+ description: '每天汇总今天到期的未结清信用卡账单与待还总金额',
+ },
+ {
+ key: 'payable_due_today',
+ group: 'bills',
+ label: '当日待还固定支出',
+ description: '把房租、贷款等今日到期的固定支出纳入当日待还主动通知',
+ },
+ {
+ key: 'grace_period_longest',
+ group: 'bills',
+ label: '今日新增最长免息期账单',
+ description: '信用卡刚过账单日、今天进入本轮最长免息期时主动提醒',
+ },
+ {
+ key: 'bill_due_advance',
+ group: 'bills',
+ label: '账单还款日前提前提醒',
+ description: '按下方选定的提前天数提醒即将到期的信用卡账单',
+ },
+ {
+ key: 'payable_due_advance',
+ group: 'bills',
+ label: '固定支出提前提醒',
+ description: '按同样的提前天数提醒即将到期的固定支出',
+ },
+ {
+ key: 'bill_overdue',
+ group: 'bills',
+ label: '逾期账单提醒',
+ description: '账单或固定支出已过到期日仍未结清时每日提醒',
+ },
+ {
+ key: 'opportunity_expiry',
+ group: 'opportunities',
+ label: '权益到期提醒',
+ description: '按设定的提前天数提醒即将到期的可用权益',
+ },
+ {
+ key: 'opportunity_claim',
+ group: 'opportunities',
+ label: '权益领取截止提醒',
+ description: '提醒权益/优惠领取窗口开启与领取截止节点',
+ },
+ {
+ key: 'opportunity_activity',
+ group: 'opportunities',
+ label: '优惠活动提醒',
+ description: '按活动节点提醒即将开始或结束的银行优惠活动',
+ },
+ {
+ key: 'opportunity_task',
+ group: 'opportunities',
+ label: '达标任务提醒',
+ description: '提醒消费达标任务进度与任务截止日期',
+ },
+ {
+ key: 'opportunity_reset',
+ group: 'opportunities',
+ label: '权益周期重置提醒',
+ description: '周期权益新一期重置可再次使用时提醒',
+ },
+ {
+ key: 'opportunity_booking',
+ group: 'opportunities',
+ label: '预约服务提醒',
+ description: '已登记的权益预约服务临近时提醒',
+ },
+]
+
+export const NOTIFICATION_CATEGORY_META: Record<
+ NotificationCategory,
+ { label: string; tone: 'danger' | 'gold' | 'accent' | 'muted' }
+> = {
+ bill_due_today: { label: '当日待还', tone: 'gold' },
+ payable_due_today: { label: '固定支出', tone: 'gold' },
+ bill_due_advance: { label: '即将到期', tone: 'accent' },
+ payable_due_advance: { label: '支出提醒', tone: 'accent' },
+ bill_overdue: { label: '已逾期', tone: 'danger' },
+ grace_period_longest: { label: '最长免息期', tone: 'gold' },
+ opportunity_expiry: { label: '权益到期', tone: 'gold' },
+ opportunity_claim: { label: '权益领取', tone: 'accent' },
+ opportunity_activity: { label: '优惠活动', tone: 'accent' },
+ opportunity_task: { label: '达标任务', tone: 'accent' },
+ opportunity_reset: { label: '周期重置', tone: 'accent' },
+ opportunity_booking: { label: '预约服务', tone: 'accent' },
+ system: { label: '系统通知', tone: 'muted' },
+}
+
+export function resolveNotificationSwitches(
+ config?: Partial | null
+): NotificationItemSwitches {
+ const rawItems = config?.items
+ const opp = config?.opportunities
+
+ const pick = (key: keyof NotificationItemSwitches, fallback = true): boolean => {
+ const val = rawItems?.[key]
+ return typeof val === 'boolean' ? val : fallback
+ }
+
+ return {
+ bill_due_today: pick('bill_due_today'),
+ payable_due_today: pick('payable_due_today'),
+ bill_due_advance: pick('bill_due_advance'),
+ payable_due_advance: pick('payable_due_advance'),
+ bill_overdue: pick('bill_overdue'),
+ grace_period_longest: pick('grace_period_longest'),
+ opportunity_expiry: pick('opportunity_expiry'),
+ opportunity_claim: pick('opportunity_claim'),
+ opportunity_activity: pick('opportunity_activity'),
+ opportunity_task: pick('opportunity_task'),
+ opportunity_reset: pick('opportunity_reset', opp?.reset_enabled ?? true),
+ opportunity_booking: pick('opportunity_booking', opp?.booking_enabled ?? true),
+ }
+}
+
+export type OpportunitySwitchKey =
+ | 'opportunity_expiry'
+ | 'opportunity_claim'
+ | 'opportunity_activity'
+ | 'opportunity_task'
+ | 'opportunity_reset'
+ | 'opportunity_booking'
+
+export function isOpportunitySwitchEnabled(
+ config: Partial | null | undefined,
+ key: OpportunitySwitchKey
+): boolean {
+ if (config?.opportunities?.enabled === false) return false
+ return resolveNotificationSwitches(config)[key]
+}
+
+export function countEnabledNotificationItems(
+ config?: Partial | null
+): { enabled: number; total: number } {
+ const switches = resolveNotificationSwitches(config)
+ const oppGlobalOn = config?.opportunities?.enabled !== false
+ let enabled = 0
+ for (const item of NOTIFICATION_SWITCH_ITEMS) {
+ if (item.group === 'opportunities' && !oppGlobalOn) continue
+ if (switches[item.key]) enabled += 1
+ }
+ return { enabled, total: NOTIFICATION_SWITCH_ITEMS.length }
+}
+
+function parseHHMM(raw?: string | null): number | null {
+ if (typeof raw !== 'string') return null
+ const m = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(raw.trim())
+ if (!m) return null
+ return Number(m[1]) * 60 + Number(m[2])
+}
+
+/** 按指定时区判断当前是否落在免打扰时段内(支持跨午夜区间如 22:00 - 08:00)。 */
+export function isInQuietHours(
+ now: Date,
+ timeZone = 'Asia/Shanghai',
+ start?: string | null,
+ end?: string | null
+): boolean {
+ const startMin = parseHHMM(start)
+ const endMin = parseHHMM(end)
+ if (startMin === null || endMin === null || startMin === endMin) return false
+
+ const readClock = (tz: string) => {
+ const parts = new Intl.DateTimeFormat('en-GB', {
+ timeZone: tz,
+ hour: '2-digit',
+ minute: '2-digit',
+ hour12: false,
+ }).formatToParts(now)
+ const h = Number(parts.find(p => p.type === 'hour')?.value ?? '0') % 24
+ const m = Number(parts.find(p => p.type === 'minute')?.value ?? '0')
+ return h * 60 + m
+ }
+
+ let currentMin: number
+ try {
+ currentMin = readClock(timeZone)
+ } catch {
+ currentMin = readClock('Asia/Shanghai')
+ }
+
+ if (startMin < endMin) {
+ return currentMin >= startMin && currentMin < endMin
+ }
+ return currentMin >= startMin || currentMin < endMin
+}
+
+function parseCivilDate(dateStr: string): { year: number; month: number; day: number } | null {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateStr.trim())
+ if (!m) return null
+ const year = Number(m[1])
+ const month = Number(m[2])
+ const day = Number(m[3])
+ if (month < 1 || month > 12 || day < 1 || day > 31) return null
+ return { year, month, day }
+}
+
+function daysInCivilMonth(year: number, month1Based: number): number {
+ return new Date(Date.UTC(year, month1Based, 0)).getUTCDate()
+}
+
+function formatCivilDate(year: number, month1Based: number, day: number): string {
+ return `${year}-${String(month1Based).padStart(2, '0')}-${String(day).padStart(2, '0')}`
+}
+
+function shiftCivilMonths(year: number, month1Based: number, delta: number): { year: number; month: number } {
+ const total = year * 12 + (month1Based - 1) + delta
+ const nextYear = Math.floor(total / 12)
+ const nextMonth = (((total % 12) + 12) % 12) + 1
+ return { year: nextYear, month: nextMonth }
+}
+
+function addCivilDays(dateStr: string, days: number): string {
+ const parsed = parseCivilDate(dateStr)
+ if (!parsed) return dateStr
+ const d = new Date(Date.UTC(parsed.year, parsed.month - 1, parsed.day + days))
+ return formatCivilDate(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate())
+}
+
+/**
+ * 判断今天是否为某张卡的「今日新增最长免息期日」(即昨天恰好为该卡当月实际账单日)。
+ * 含小月 / 2 月月末钳制,例如 billing_day=31 在 2/28 的次日 3/1 触发。
+ */
+export function isNewLongestGracePeriodDay(billingDay: number, todayStr: string): boolean {
+ const parsed = parseCivilDate(todayStr)
+ if (!parsed) return false
+ const clampedBillingDay =
+ Number.isFinite(billingDay) && billingDay >= 1 ? Math.min(Math.trunc(billingDay), 31) : 10
+ const yesterdayUtc = new Date(Date.UTC(parsed.year, parsed.month - 1, parsed.day - 1))
+ const yYear = yesterdayUtc.getUTCFullYear()
+ const yMonth = yesterdayUtc.getUTCMonth() + 1
+ const yDay = yesterdayUtc.getUTCDate()
+ const effectiveYesterdayBilling = Math.min(clampedBillingDay, daysInCivilMonth(yYear, yMonth))
+ return yDay === effectiveYesterdayBilling
+}
+
+export interface GraceWindowCardInput {
+ billing_day: number
+ override_billing_day?: number | null
+ override_due_type?: CardProduct['payment_due_type'] | null
+ override_due_value?: number | null
+ payment_due_type: CardProduct['payment_due_type']
+ payment_due_value: number
+}
+
+/**
+ * 纯日历日口径计算指定日期(todayStr = YYYY-MM-DD)刷卡的免息期与关键日期。
+ * 与 lib/utils.ts 的 calculateCardGracePeriod 保持一致,但不依赖进程本地时区。
+ */
+export function computeCardGraceWindowOnDate(
+ input: GraceWindowCardInput,
+ todayStr: string
+): { graceDays: number; nextBillingDate: string; nextDueDate: string } {
+ const parsed = parseCivilDate(todayStr)
+ if (!parsed) {
+ return { graceDays: 1, nextBillingDate: todayStr, nextDueDate: todayStr }
+ }
+ const rawBilling = input.override_billing_day ?? input.billing_day ?? 10
+ const billingDay =
+ Number.isFinite(rawBilling) && rawBilling >= 1 ? Math.min(Math.trunc(rawBilling), 31) : 10
+ const dueType =
+ input.override_due_type != null && input.override_due_value != null
+ ? input.override_due_type
+ : input.payment_due_type
+ const dueValue =
+ input.override_due_type != null && input.override_due_value != null
+ ? input.override_due_value
+ : input.payment_due_value
+
+ const thisMonthBillingDay = Math.min(billingDay, daysInCivilMonth(parsed.year, parsed.month))
+ const purchaseYM =
+ parsed.day > thisMonthBillingDay
+ ? shiftCivilMonths(parsed.year, parsed.month, 1)
+ : { year: parsed.year, month: parsed.month }
+
+ const nextBillingDay = Math.min(billingDay, daysInCivilMonth(purchaseYM.year, purchaseYM.month))
+ const nextBillingDate = formatCivilDate(purchaseYM.year, purchaseYM.month, nextBillingDay)
+
+ let nextDueDate: string
+ if (dueType === 'fixed') {
+ const dueYM = shiftCivilMonths(purchaseYM.year, purchaseYM.month, 1)
+ const dueDay = Math.min(Math.max(1, Math.trunc(dueValue)), daysInCivilMonth(dueYM.year, dueYM.month))
+ nextDueDate = formatCivilDate(dueYM.year, dueYM.month, dueDay)
+ } else if (dueType === 'fixed_before_billing') {
+ const dueDay = Math.min(
+ Math.max(1, Math.trunc(dueValue)),
+ daysInCivilMonth(purchaseYM.year, purchaseYM.month)
+ )
+ nextDueDate = formatCivilDate(purchaseYM.year, purchaseYM.month, dueDay)
+ } else {
+ nextDueDate = addCivilDays(nextBillingDate, Math.max(1, Math.trunc(dueValue || 20)))
+ }
+
+ const diffDays = Math.round((Date.parse(nextDueDate) - Date.parse(todayStr)) / 86_400_000)
+ return {
+ graceDays: Math.max(1, diffDays),
+ nextBillingDate,
+ nextDueDate,
+ }
+}
+
+export function isWebPushChannelEnabled(
+ configOrRaw?:
+ | {
+ enabled_channels?: unknown
+ opportunities?: { web_push_enabled?: unknown } | null
+ }
+ | string
+ | null
+): boolean {
+ if (!configOrRaw) return true
+ let cfg: { enabled_channels?: unknown; opportunities?: { web_push_enabled?: unknown } | null }
+ if (typeof configOrRaw === 'string') {
+ try {
+ const parsed = JSON.parse(configOrRaw)
+ if (!parsed || typeof parsed !== 'object') return true
+ cfg = parsed as { enabled_channels?: unknown; opportunities?: { web_push_enabled?: unknown } | null }
+ } catch {
+ return true
+ }
+ } else {
+ cfg = configOrRaw
+ }
+ if (cfg.enabled_channels !== undefined) {
+ return Array.isArray(cfg.enabled_channels) && cfg.enabled_channels.includes('web_push')
+ }
+ if (cfg.opportunities && cfg.opportunities.web_push_enabled === false) {
+ return false
+ }
+ return true
+}
+
+export function syncItemSwitchesWithOpportunities(
+ current?: Partial | null,
+ incoming?: Partial | null
+): {
+ items: NotificationItemSwitches
+ opportunities: NonNullable
+} {
+ const items: NotificationItemSwitches = {
+ ...resolveNotificationSwitches(current),
+ ...(incoming?.items || {}),
+ }
+ const opportunities: NonNullable = {
+ ...(current?.opportunities || {}),
+ ...(incoming?.opportunities || {}),
+ }
+
+ // Conflicting simultaneous updates settle deterministically on items.*
+ if (incoming?.items?.opportunity_reset !== undefined) {
+ opportunities.reset_enabled = incoming.items.opportunity_reset
+ } else if (incoming?.opportunities?.reset_enabled !== undefined) {
+ items.opportunity_reset = incoming.opportunities.reset_enabled
+ }
+
+ if (incoming?.items?.opportunity_booking !== undefined) {
+ opportunities.booking_enabled = incoming.items.opportunity_booking
+ } else if (incoming?.opportunities?.booking_enabled !== undefined) {
+ items.opportunity_booking = incoming.opportunities.booking_enabled
+ }
+
+ return { items, opportunities }
+}
+
+export function formatMoneySingle(amount: number, currency: string): string {
+ const safe = Number(amount)
+ const rounded = Math.round((Number.isFinite(safe) ? safe : 0) * 100) / 100
+ return `${currencySymbol(currency)}${rounded.toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`
+}
+
+export function formatCurrencyBuckets(totalsByCurrency: Record): string {
+ const entries = Object.entries(totalsByCurrency).filter(([, amount]) => Number.isFinite(amount) && amount > 0)
+ if (entries.length === 0) return '¥0'
+ entries.sort(([a], [b]) => {
+ if (a === 'CNY') return -1
+ if (b === 'CNY') return 1
+ return a.localeCompare(b)
+ })
+ return entries.map(([currency, amount]) => formatMoneySingle(amount, currency)).join(' + ')
+}
diff --git a/lib/reminders.ts b/lib/reminders.ts
index f34550f..95d1fc9 100644
--- a/lib/reminders.ts
+++ b/lib/reminders.ts
@@ -10,6 +10,9 @@
import { callRpc } from './api/rpc-client'
import type * as RemindersServer from './api/reminders.server'
+import { getUserPreferences } from './api/preferences'
+import { isWebPushChannelEnabled } from './api/push'
+import { resolveNotificationSwitches } from './notifications.shared'
import { getLoanNextDueDate } from './utils'
import { currencySymbol, normalizeCurrencyOrDefault } from './fx'
@@ -62,7 +65,12 @@ export async function checkAndSendReminders(userId: string): Promise {
if (!('Notification' in window) || Notification.permission !== 'granted') return
try {
- await checkLoanReminders()
+ const prefs = await getUserPreferences(userId)
+ if (!isWebPushChannelEnabled(prefs.reminder_config)) return
+ const switches = resolveNotificationSwitches(prefs.reminder_config)
+ const allowedDays = new Set(prefs.reminder_config.remind_days_before ?? [3, 1, 0])
+
+ await checkLoanReminders(switches, allowedDays)
const today = new Date()
today.setHours(0, 0, 0, 0)
@@ -88,6 +96,8 @@ export async function checkAndSendReminders(userId: string): Promise {
const days = daysUntilDue(bill.due_date)
const remindType = remindTypeForDays(days)
if (!remindType) continue
+ if (days === 0 && !switches.bill_due_today) continue
+ if (days > 0 && (!switches.bill_due_advance || !allowedDays.has(days))) continue
const key = `${bill.id}:${remindType}`
if (sentKeys.has(key)) continue
@@ -121,7 +131,10 @@ export async function checkAndSendReminders(userId: string): Promise {
}
}
-async function checkLoanReminders(): Promise {
+async function checkLoanReminders(
+ switches: ReturnType,
+ allowedDays: Set
+): Promise {
const rawLoanCards = await callRpc(
'reminders', 'getActiveLoanCards'
)
@@ -140,6 +153,8 @@ async function checkLoanReminders(): Promise {
else if (daysUntil === 1) remindType = 'loan_1day'
else if (daysUntil === 0) remindType = 'loan_due_day'
if (!remindType) continue
+ if (daysUntil === 0 && !switches.payable_due_today) continue
+ if (daysUntil > 0 && (!switches.payable_due_advance || !allowedDays.has(daysUntil))) continue
const remindDateStr = nextDue.toISOString().slice(0, 10)
const alreadySent = await callRpc(
diff --git a/lib/types.ts b/lib/types.ts
index 9266d48..7e6c52f 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -362,6 +362,53 @@ export interface UserDisplayConfig {
default_currency: string
}
+export type NotificationCategory =
+ | 'bill_due_today'
+ | 'payable_due_today'
+ | 'bill_due_advance'
+ | 'payable_due_advance'
+ | 'bill_overdue'
+ | 'grace_period_longest'
+ | 'opportunity_expiry'
+ | 'opportunity_claim'
+ | 'opportunity_activity'
+ | 'opportunity_task'
+ | 'opportunity_reset'
+ | 'opportunity_booking'
+ | 'system'
+
+export interface NotificationItemSwitches {
+ bill_due_today: boolean
+ payable_due_today: boolean
+ bill_due_advance: boolean
+ payable_due_advance: boolean
+ bill_overdue: boolean
+ grace_period_longest: boolean
+ opportunity_expiry: boolean
+ opportunity_claim: boolean
+ opportunity_activity: boolean
+ opportunity_task: boolean
+ opportunity_reset: boolean
+ opportunity_booking: boolean
+}
+
+export interface UserNotificationItem {
+ id: string
+ user_id: string
+ notification_key: string
+ category: NotificationCategory
+ title: string
+ body: string | null
+ target_url: string | null
+ metadata_json: string | null
+ sent_at: string
+ status: 'sent' | 'failed' | 'skipped'
+ error: string | null
+ read_at: string | null
+ deleted_at: string | null
+ push_sent_at: string | null
+}
+
/**
* 用户自定义提醒规则与通道设置
*/
@@ -371,6 +418,10 @@ export interface UserReminderConfig {
quiet_hours_end?: string
enabled_channels: ('web_push' | 'email' | 'webhook')[]
custom_reminder_email?: string
+ /**
+ * 全部通知项的细粒度开关(缺省全开,兼容存量配置)
+ */
+ items?: Partial
/**
* 权益提醒子树(Task 14):深合并 OpportunityReminderConfig 默认值;
* 旧字段保持原语义,读取时两者并列生效(旧 quiet hours 约束推送时段)。
diff --git a/migrations/d1/0033_notification_center.sql b/migrations/d1/0033_notification_center.sql
new file mode 100644
index 0000000..9b47b9f
--- /dev/null
+++ b/migrations/d1/0033_notification_center.sql
@@ -0,0 +1,15 @@
+-- 0033_notification_center.sql — 通知中心:分类、跳转链接、结构化详情、已读态、软删除与推送标记
+ALTER TABLE notification_history ADD COLUMN category TEXT NOT NULL DEFAULT 'system';
+ALTER TABLE notification_history ADD COLUMN target_url TEXT;
+ALTER TABLE notification_history ADD COLUMN metadata_json TEXT;
+ALTER TABLE notification_history ADD COLUMN read_at TEXT;
+ALTER TABLE notification_history ADD COLUMN deleted_at TEXT;
+ALTER TABLE notification_history ADD COLUMN push_sent_at TEXT;
+
+-- 历史已发送记录默认视为已推送,防止升级后被 Cron 二次补推
+UPDATE notification_history SET push_sent_at = sent_at WHERE status = 'sent' AND push_sent_at IS NULL;
+
+CREATE INDEX IF NOT EXISTS idx_notification_history_inbox
+ ON notification_history(user_id, deleted_at, sent_at DESC);
+CREATE INDEX IF NOT EXISTS idx_notification_history_unread
+ ON notification_history(user_id, deleted_at, read_at);
diff --git a/public/sw.js b/public/sw.js
index 55702e9..5913fb7 100644
--- a/public/sw.js
+++ b/public/sw.js
@@ -40,12 +40,34 @@ self.addEventListener('push', (event) => {
// ── Notification click ────────────────────────────────────────────────────
// 权益推送(tag 前缀 wc-op:)只允许跳转到站内白名单路径,之后由应用自身
// 鉴权;不向任意入参 URL 导航。
-const OPPORTUNITY_ALLOWED_URLS = new Set(['/promos', '/benefits', '/benefits/calendar'])
+const OPPORTUNITY_ALLOWED_URLS = new Set(['/promos', '/benefits', '/benefits/calendar', '/notifications'])
+const EXACT_ALLOWED_URLS = new Set(['/dashboard', '/bills'])
+const ALLOWED_PREFIXES = ['/bills/', '/cards/']
+
+function normalizeInternalTargetUrl(raw) {
+ if (typeof raw !== 'string' || !raw.startsWith('/') || raw.startsWith('//')) return '/bills'
+ let pathname
+ try {
+ pathname = new URL(raw, self.location.origin).pathname
+ } catch {
+ return '/bills'
+ }
+ if (
+ EXACT_ALLOWED_URLS.has(pathname) ||
+ OPPORTUNITY_ALLOWED_URLS.has(pathname) ||
+ ALLOWED_PREFIXES.some((prefix) => pathname.startsWith(prefix))
+ ) {
+ return pathname
+ }
+ return '/bills'
+}
self.addEventListener('notificationclick', (event) => {
event.notification.close()
- let targetUrl = (event.notification.data && event.notification.data.url) || '/bills'
+ let targetUrl = normalizeInternalTargetUrl(
+ event.notification.data && event.notification.data.url
+ )
const tag = (event.notification.data && event.notification.data.tag) || event.notification.tag || ''
if (tag.startsWith('wc-op:')) {
if (!OPPORTUNITY_ALLOWED_URLS.has(targetUrl)) targetUrl = '/benefits'
diff --git a/worker/cron.ts b/worker/cron.ts
index 2c6436c..bb0564f 100644
--- a/worker/cron.ts
+++ b/worker/cron.ts
@@ -2,8 +2,13 @@
// Deployed as part of the main Worker (cron trigger in wrangler.jsonc)
import webpush from "web-push";
-import { getLocalTodayString } from "../lib/utils";
import { sendApnsToUser } from "../lib/apns.server";
+import { isWebPushChannelEnabled } from "../lib/notifications.shared";
+import {
+ buildDailyNotificationCandidates,
+ isUserInQuietHours,
+ type PrefetchedUserNotificationPrefs,
+} from "../lib/notifications-engine.server";
interface CronEnv {
DB: D1Database;
@@ -18,52 +23,48 @@ interface CronEnv {
}
/**
- * 校验用户的偏好设置是否开启了 Web Push(统一存量兼容口径与迁移判断)。
+ * 校验用户的偏好设置是否开启了主动推送通道(Web Push / APNs 共用主开关)。
* 若 enabled_channels 未设置而旧 opportunities.web_push_enabled === false,绝不下发。
*/
export function isUserWebPushEnabled(reminderConfigRaw?: string | null): boolean {
- if (!reminderConfigRaw) return true;
- try {
- const parsed = JSON.parse(reminderConfigRaw) as {
- enabled_channels?: string[];
- opportunities?: { web_push_enabled?: boolean };
- };
- if (parsed.enabled_channels !== undefined) {
- return (
- Array.isArray(parsed.enabled_channels) &&
- parsed.enabled_channels.includes("web_push")
- );
- }
- if (parsed.opportunities && parsed.opportunities.web_push_enabled === false) {
- return false;
- }
- return true;
- } catch {
- return true;
- }
+ return isWebPushChannelEnabled(reminderConfigRaw);
}
-interface BillWithCard {
+interface ExistingHistoryRow {
id: string;
- account_id: string | null;
- card_id: string;
- bill_month: string;
- bill_amount: number;
- min_payment: number | null;
- due_date: string;
- status: string;
- holder_id: string;
- created_by: string;
- bank_name: string | null;
- card_name: string | null;
- card_number_last4: string | null;
- account_statement_mode: string | null;
- /** 卡级别名称覆盖(NULL = 使用卡产品默认名称)。 */
- name_override: string | null;
+ notification_key: string;
+ read_at: string | null;
+ deleted_at: string | null;
+ push_sent_at: string | null;
+}
+
+async function loadExistingHistoryByKey(
+ db: D1Database,
+ userId: string,
+ keys: string[],
+): Promise