diff --git a/AGENTS.md b/AGENTS.md index 5a8e026..bf4ec27 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,7 @@ - 浏览器端**不写 SQL**:组件只调 `lib/api/*.ts` 包装函数,走 `/api/rpc//` 命名白名单路由(`lib/api/rpc-client.ts` + `lib/api/registry.ts`) - UI 用 ObsidianUI 暗色体系:`components/obsidian/` 原语 + `globals.css` 的 `d-*` token(Tailwind v4 `@theme`)。不要再引入 MUI -- 设计源在 `design/openpencil/`:`.op` 文件是唯一真源,token 三方对齐(foundations.json ↔ .op ↔ globals.css),CI 门禁 `verify-batch.sh --source-only` 会拦漂移 +- 设计源在 `design/baoyu/`:baoyu-design(`canvas.json` + `.dc.html` 画板)是现行唯一真源,token 三方对齐(`tokens.json` ↔ `foundations.json` ↔ `globals.css`),CI 门禁 `verify-batch.sh --source-only` 会拦漂移;`design/openpencil/` 与 `.op` 文件保留为历史存档,不再对其进行写操作 - 部署:`npx vinext deploy`(本地构建 + 上传);密钥用 `wrangler secret put` - `db/seed*.ts`、`scripts/*.mjs` 里残留的 `@insforge/sdk` 脚本是历史存档,SDK 已从依赖移除,跑不动了——别照着它们写新代码 @@ -26,7 +26,7 @@ npm run typecheck # tsc --noEmit npm run lint # eslint --max-warnings=0 npm test # vitest run -bash design/openpencil/verify-batch.sh --source-only # 设计源五项检查 +bash design/openpencil/verify-batch.sh --source-only # 设计源质量门禁(baoyu-design 画板/Token/热区) ``` CI(`.github/workflows/ci.yml`):代码质量 + 设计源质量,PR 到 main 时跑。 diff --git a/app/(mobile)/bills/[id]/page.tsx b/app/(mobile)/bills/[id]/page.tsx index bef9a2e..cfde7e2 100644 --- a/app/(mobile)/bills/[id]/page.tsx +++ b/app/(mobile)/bills/[id]/page.tsx @@ -7,28 +7,42 @@ import { createPayment, updateBillStatus, getBillDetail, getPaymentTotal } from import { PaymentForm } from '@/components/mobile/PaymentForm' import { BillEditForm } from '@/components/mobile/BillEditForm' import { BillPaymentsManage } from '@/components/mobile/BillPaymentsManage' +import { CardDefinitionModal } from '@/components/mobile/CardDefinitionModal' +import { CardAccountModal } from '@/components/mobile/CardAccountModal' +import type { CreditCardWithProduct } from '@/lib/api/cards' import { useAuth } from '@/lib/auth' -import { computePaymentDrivenStatus } from '@/lib/utils' -import { ChevronLeftIcon, ChevronRightIcon, BankIcon, UserIcon, ClockIcon } from '@/components/icons/WcIcon' -import { formatCardTail, getEffectiveCardName } from '@/lib/utils' -import type { Bill, Payment, CreditCard, CardProduct, CardHolder } from '@/lib/types' +import { + computePaymentDrivenStatus, + getEffectiveCreditLimit, + getEffectiveBillingDay, + formatCardTail, + getEffectiveCardName, + isBillUnissued, + calculateCardGracePeriod, +} from '@/lib/utils' +import { ChevronLeftIcon, ChevronRightIcon, ClockIcon } from '@/components/icons/WcIcon' +import type { Bill, Payment, CardHolder } from '@/lib/types' type BillDetail = Bill & { - card: CreditCard & { + card?: CreditCardWithProduct & { card_holders?: CardHolder - card_product: CardProduct } payments: Payment[] } -/** 计算已还 / 剩余 / 状态 */ +/** 计算已还 / 剩余 / 状态 / 是否未出账 */ function computeBillProgress(bill: BillDetail) { const paid = (bill.payments || []).reduce((s, p) => s + Number(p.amount || 0), 0) const amount = Number(bill.bill_amount) || 0 const remaining = Math.max(0, amount - paid) // 与服务端落库、还款重算共用同一个状态函数,避免 0 / 0.01 边界两套口径 - const status = computePaymentDrivenStatus(bill, paid) - return { paid, remaining, status } + let status = computePaymentDrivenStatus(bill, paid) + const unissued = isBillUnissued(bill) + if (status === 'overdue' && unissued) { + // 待出账保护:未到出账日绝无逾期 + status = 'unpaid' + } + return { paid, remaining, status, isUnissued: unissued } } /** 状态徽章(暗色):淡底 + ink,与 bills 暗色视图同一口径 */ @@ -72,6 +86,8 @@ export default function BillDetailPage({ params }: { params: Promise<{ id: strin const [paymentOpen, setPaymentOpen] = useState(false) const [editOpen, setEditOpen] = useState(false) const [paymentsManageOpen, setPaymentsManageOpen] = useState(false) + const [cardDefModalOpen, setCardDefModalOpen] = useState(false) + const [cardAccountModalOpen, setCardAccountModalOpen] = useState(false) const { user } = useAuth() // deleteBill 服务端 admin only;member 隐藏删除入口,权限以服务端为准 const isAdmin = user?.role === 'admin' @@ -83,10 +99,15 @@ export default function BillDetailPage({ params }: { params: Promise<{ id: strin setError(null) // 账单 + 卡 + 卡产品 + 持卡人 + 还款记录,一次 RPC 返回 const detail = await getBillDetail(id) - const card = detail.bill.card - ? { ...detail.bill.card, card_holders: detail.bill.card.card_holder } + const rawCard = detail.bill.card + const card: CreditCardWithProduct | undefined = rawCard && rawCard.card_product + ? ({ + ...rawCard, + card_product: rawCard.card_product, + card_holders: rawCard.card_holder, + } as CreditCardWithProduct) : undefined - setBill({ ...(detail.bill as Bill), card, payments: detail.payments } as unknown as BillDetail) + setBill({ ...(detail.bill as Bill), card, payments: detail.payments }) } catch (err) { setError(err instanceof Error ? err.message : '加载账单失败') } finally { @@ -153,9 +174,15 @@ export default function BillDetailPage({ params }: { params: Promise<{ id: strin const holderName = holder?.name const last4 = formatCardTail(card?.card_number_last4) - const { paid, remaining, status } = computeBillProgress(bill) + const { paid, remaining, status, isUnissued } = computeBillProgress(bill) const minPayment = bill.min_payment != null ? Number(bill.min_payment) : null const billAmount = Number(bill.bill_amount) || 0 + const effLimit = card ? getEffectiveCreditLimit(card) : null + const effBillingDay = card ? getEffectiveBillingDay(card) : null + const todayGraceDays = + card && card.card_product + ? calculateCardGracePeriod({ ...card, card_product: card.card_product }).graceDays + : 0 // 免息还款期长度:这一期「出账日 → 还款日」的窗口,是卡产品属性, // 与今天无关;剩余免息:今天距还款日还有几天(负数 = 已逾期)。 @@ -165,11 +192,32 @@ export default function BillDetailPage({ params }: { params: Promise<{ id: strin if (!start || !end) return 0 return Math.max(0, Math.round((new Date(end).getTime() - new Date(start).getTime()) / 86400000)) })() - const billPaid = status === 'paid' + const isSettled = status === 'paid' const graceRemaining = bill.due_date ? Math.round((new Date(bill.due_date).getTime() - Date.now()) / 86400000) : null + const renderGraceRemainingNotice = () => { + if (isSettled || graceRemaining === null) return null + if (graceRemaining >= 0) { + return ( +

+ + 剩 {graceRemaining} 天免息(逾期未还将计息) +

+ ) + } + if (!isUnissued) { + return ( +

+ + 已逾期 {-graceRemaining} 天 +

+ ) + } + return null + } + const periodStart = bill.statement_start ? format(new Date(bill.statement_start), 'M/d') : '' const periodEnd = bill.statement_end ? format(new Date(bill.statement_end), 'M/d') : '' @@ -177,29 +225,10 @@ export default function BillDetailPage({ params }: { params: Promise<{ id: strin
router.back()} /> - {/* 头部:卡名 + 持卡人/银行 + 金额 + 状态徽章 */} + {/* 头部:金额 + 状态徽章 + 编辑金额与日期 */}
-
-

{cardName}

-
- - - {bankName} - - {holderName && ( - - - {holderName} - - )} - {last4 && ( - - 尾号 {last4} - - )} -
-
+

账单应还

@@ -224,44 +253,84 @@ export default function BillDetailPage({ params }: { params: Promise<{ id: strin ]} /> - {/* 账单周期 */} -

-

- {periodStart && periodEnd ? '账单周期 ' + periodStart + ' – ' + periodEnd : '账单周期 —'} - {last4 ? ' · 尾号 ' + last4 : ''} -

+ {/* 区块 2:关联卡片(不含持卡人/尾号/账单日) */} +
setCardDefModalOpen(true)} + className='text-[13px] font-semibold text-d-accent-light' + > + 修改卡片信息 + + ) + } + > +
+ + + 0 + ? `${todayGraceDays} 天` + : '—' + } + /> +
- {/* 日期信息:这一期账单自己的具体日期,不是循环规则 */} -
+ {/* 区块 3:账单信息(人+卡)(不含银行/卡片) */} +
setCardAccountModalOpen(true)} + className='text-[13px] font-semibold text-d-accent-light' + > + 修改 + + ) + } + >
- - + + + 0 + ? `每月 ${effBillingDay} 日` + : '—' + } /> + +
+ + + + 0 - ? graceWindow + ' 天(出账日 → 还款日)' + ? `${graceWindow} 天(出账日 → 还款日)` : '—' } /> - {!billPaid && graceRemaining !== null && ( -

- - {graceRemaining >= 0 - ? `剩 ${graceRemaining} 天免息(逾期未还将计息)` - : `已逾期 ${-graceRemaining} 天`} -

- )} + {renderGraceRemainingNotice()}
@@ -370,6 +439,26 @@ export default function BillDetailPage({ params }: { params: Promise<{ id: strin onClose={() => setPaymentsManageOpen(false)} onChanged={load} /> + + {/* 修改卡片信息弹窗(所属银行、卡片名称、还款规则) */} + {card && ( + setCardDefModalOpen(false)} + card={card} + onSaved={() => load({ silent: true })} + /> + )} + + {/* 修改账单信息(人+卡)弹窗(持卡人、卡片尾号、信用额度、每月账单日) */} + {card && ( + setCardAccountModalOpen(false)} + card={card} + onSaved={() => load({ silent: true })} + /> + )}
) } @@ -399,10 +488,13 @@ function Row({ label, value }: { label: string; value: string }) { ) } -function Section({ title, children }: { title: string; children: React.ReactNode }) { +function Section({ title, action, children }: { title: string; action?: React.ReactNode; children: React.ReactNode }) { return (
-

{title}

+
+

{title}

+ {action} +
{children}
) diff --git a/app/(mobile)/bills/page.tsx b/app/(mobile)/bills/page.tsx index b77a660..ea8ed20 100644 --- a/app/(mobile)/bills/page.tsx +++ b/app/(mobile)/bills/page.tsx @@ -15,6 +15,8 @@ import { syncGmailLedgerToCardsAndBills } from '@/lib/api/sync-gmail' import { getHolders } from '@/lib/api/holders' import { PaymentForm } from '@/components/mobile/PaymentForm' import { BillForm } from '@/components/mobile/BillForm' +import { CardCreateModal } from '@/components/mobile/CardCreateModal' +import { AccountMergeWizardModal } from '@/components/mobile/AccountMergeWizardModal' import { BillDraftsPanel } from '@/components/mobile/BillDraftsPanel' import { ManualBillAmountDialog } from '@/components/mobile/ManualBillAmountDialog' import { PayableForm } from '@/components/mobile/PayableForm' @@ -97,6 +99,8 @@ export default function BillsPage() { const [paymentOpen, setPaymentOpen] = useState(false) const [selectedBill, setSelectedBill] = useState(null) const [billFormOpen, setBillFormOpen] = useState(false) + const [cardCreateOpen, setCardCreateOpen] = useState(false) + const [mergeWizardOpen, setMergeWizardOpen] = useState(false) // 手填金额:只针对「卡」,账单可能还没生成,因此传的是 card,不是 bill const [manualTarget, setManualTarget] = useState(null) // 固定支出(房租/贷款等按月应付) @@ -618,6 +622,21 @@ export default function BillsPage() { onOpenPayment={openPaymentForBill} onManualAmount={setManualTarget} onAddBill={() => setBillFormOpen(true)} + onAddCard={() => setCardCreateOpen(true)} + onMergeCards={() => setMergeWizardOpen(true)} + /> + + setCardCreateOpen(false)} + onSuccess={loadData} + /> + + setMergeWizardOpen(false)} + cards={cardsSummary.map(c => ({ ...c.card, account: c.account }))} + onSuccess={loadData} /> {selectedBill && ( diff --git a/app/(mobile)/cards/[id]/page.tsx b/app/(mobile)/cards/[id]/page.tsx index d397cd9..b849f0f 100644 --- a/app/(mobile)/cards/[id]/page.tsx +++ b/app/(mobile)/cards/[id]/page.tsx @@ -3,11 +3,12 @@ import { useEffect, useState, useCallback, use } from 'react' import { useRouter } from 'next/navigation' import Link from 'next/link' -import { getCardDetail, updateCard, updateCardHolder } from '@/lib/api/cards' -import { CardForm } from '@/components/mobile/CardForm' +import { getCardDetail, type CreditCardWithProduct } from '@/lib/api/cards' +import { CardDefinitionModal } from '@/components/mobile/CardDefinitionModal' +import { CardAccountModal } from '@/components/mobile/CardAccountModal' import { ChevronLeftIcon, ClockIcon } from '@/components/icons/WcIcon' -import { getEffectiveBillingDay, getEffectiveDueConfig, formatCardTail, getEffectiveCardName, getEffectiveAnnualFee } from '@/lib/utils' -import type { CreditCard, CardProduct, CardHolder, Bill, Benefit } from '@/lib/types' +import { getEffectiveBillingDay, getEffectiveDueConfig, formatCardTail, getEffectiveCardName, getEffectiveAnnualFee, getEffectiveCreditLimit, isCreditLimitManuallySet } from '@/lib/utils' +import type { CreditCard, CardProduct, CardHolder, Bill, Benefit, CardDueDateResolution } from '@/lib/types' import type { OpportunityDto } from '@/lib/opportunities/queries.server' import { STATUS_LABELS } from '@/lib/opportunities/view-model' @@ -74,20 +75,20 @@ export default function CardDetailPage({ params }: { params: Promise<{ id: strin const [bills, setBills] = useState([]) const [benefits, setBenefits] = useState>([]) const [opportunities, setOpportunities] = useState([]) + const [dueDateResolution, setDueDateResolution] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) // 编辑表单状态 - const [cardFormOpen, setCardFormOpen] = useState(false) - // 持卡人选项已改由 updateCardHolder 专用通道处理,这里只剩展示名 - const [holders] = useState>([]) + const [cardDefOpen, setCardDefOpen] = useState(false) + const [cardAccountOpen, setCardAccountOpen] = useState(false) const load = useCallback(async () => { try { setLoading(true) setError(null) - // 卡 + 卡产品 + 持卡人 + 最近账单(含已还聚合)+ 权益使用进度,一次 RPC 返回 + // 卡 + 卡产品 + 持卡人 + 最近账单(含已还聚合)+ 权益使用进度 + 还款日确切原因,一次 RPC 返回 const detail = await getCardDetail(id) setCard({ ...detail.card, @@ -96,6 +97,7 @@ export default function CardDetailPage({ params }: { params: Promise<{ id: strin setBills(detail.bills as unknown as BillWithPaid[]) setBenefits(detail.benefits) setOpportunities(detail.opportunities ?? []) + setDueDateResolution(detail.dueDateResolution ?? null) } catch (err) { setError(err instanceof Error ? err.message : '加载卡片失败') } finally { @@ -145,8 +147,20 @@ export default function CardDetailPage({ params }: { params: Promise<{ id: strin const used = bills .filter(b => b.computed_status !== 'paid') .reduce((s, b) => s + Math.max(0, Number(b.bill_amount) - b.paid_amount), 0) - const limit = Number(card.credit_limit) || 0 - const available = Math.max(0, limit - used) + const effLimit = getEffectiveCreditLimit(card) + const isLimitManual = isCreditLimitManuallySet(card) + const available = effLimit != null ? Math.max(0, effLimit - used) : null + + let limitBadge: React.ReactNode = null + if (isLimitManual) { + limitBadge = ( + 已设置 + ) + } else if (effLimit === null) { + limitBadge = ( + 去设置 + ) + } const billingDay = getEffectiveBillingDay(card) const dueConfig = getEffectiveDueConfig(card, product) @@ -197,11 +211,21 @@ export default function CardDetailPage({ params }: { params: Promise<{ id: strin )}

- {card.status !== 'active' && ( - - {card.status === 'frozen' ? '已冻结' : '已注销'} - - )} +
+ {card.status !== 'active' && ( + + {card.status === 'frozen' ? '已冻结' : '已注销'} + + )} + +

@@ -213,11 +237,33 @@ export default function CardDetailPage({ params }: { params: Promise<{ id: strin

- {/* 额度三格 */} + {/* 额度三格:未获取时明确提示,允许点击弹出输入;已设置回显标签 */}
- - - + +
+

已用

+

¥{Number(used).toLocaleString()}

+
+
+

可用

+

+ {available !== null ? `¥${available.toLocaleString()}` : '—'} +

+
{/* 日期与费用 */} @@ -226,7 +272,7 @@ export default function CardDetailPage({ params }: { params: Promise<{ id: strin action={ ) } +const THEME_LABELS: Record = { + dark: '🌙 暗色', + light: '☀️ 亮色', + system: '💻 跟随系统', +} + +function formatGmailSummary( + status: GmailConnectionStatus | null, + loading = false, + error = false +): string { + if (loading) return '加载中…' + if (error) return '加载失败' + if (status?.connected) return '已连接' + if (status?.last_error) return '需重连' + return '未连接' +} + export default function SettingsPage() { const { user, signOut } = useAuth() const router = useRouter() - const { displayConfig, reminderConfig, updateDisplay, updateReminder, loading: loadingPrefs } = useUserPreferences() + const { theme, cycleTheme } = useTheme() + const { + displayConfig, + reminderConfig, + updateDisplay, + updateReminder, + loading: loadingPrefs, + loadError, + refreshPreferences, + } = useUserPreferences() + + const [gmailStatus, setGmailStatus] = useState(null) + const [gmailLoading, setGmailLoading] = useState(true) + const [gmailError, setGmailError] = useState(false) + const [showGmailSheet, setShowGmailSheet] = useState(false) + const [showReminderSheet, setShowReminderSheet] = useState(false) + const [showDisplaySheet, setShowDisplaySheet] = useState(false) + const [showLogoutDialog, setShowLogoutDialog] = useState(false) + const [loggingOut, setLoggingOut] = useState(false) + + const [notice, setNotice] = useState<{ open: boolean; message: string; severity: 'success' | 'error' | 'info' }>({ + open: false, + message: '', + severity: 'success', + }) + + const loadGmail = useCallback(async () => { + setGmailLoading(true) + setGmailError(false) + try { + const res = await getGmailConnection() + setGmailStatus(res) + } catch { + setGmailError(true) + setGmailStatus(null) + } finally { + setGmailLoading(false) + } + }, []) + + useEffect(() => { + void loadGmail() + }, [loadGmail]) - // 用会话 role 判定(服务端按 lib/admin-emails.ts 写入),不再在浏览器端 - // 维护第二份邮箱白名单,避免与服务端口径漂移。 const isAdmin = user?.role === 'admin' + const forwardAddress = user ? 'bills+' + user.id + '@' + DOMAIN : null const handleSignOut = async () => { + setLoggingOut(true) try { await signOut() + setShowLogoutDialog(false) router.push('/login') } catch (err) { setNotice({ open: true, message: err instanceof Error ? err.message : '退出登录失败', severity: 'error' }) + } finally { + setLoggingOut(false) } } - // 折叠面板:提醒偏好 / 设置 / Gmail 账单导入 - const [openReminder, setOpenReminder] = useState(false) - const [openSettings, setOpenSettings] = useState(false) - const [openGmail, setOpenGmail] = useState(false) - - const [notice, setNotice] = useState<{ open: boolean; message: string; severity: 'success' | 'error' | 'info' }>({ - open: false, - message: '', - severity: 'success', - }) - - const forwardAddress = user ? 'bills+' + user.id + '@' + DOMAIN : null - const copyText = async (text: string, label = '已复制') => { try { await navigator.clipboard.writeText(text) @@ -99,194 +154,358 @@ export default function SettingsPage() { } } + const themeLabel = THEME_LABELS[theme] ?? '💻 跟随系统' + + // 计算偏好摘要胶囊文案(映射表/函数化,去嵌套三元;完整展示已选节点) + const gmailSummary = formatGmailSummary(gmailStatus, gmailLoading, gmailError) + const billDays = reminderConfig?.remind_days_before ?? [3, 1, 0] + const oppEnabled = reminderConfig?.opportunities?.enabled !== false + const billDaysLabel = billDays.length > 0 ? `提前${billDays.join('/')}天` : '未设提醒' + const reminderSummary = `${billDaysLabel} · 权益${oppEnabled ? '开' : '关'}` + const displaySummary = `${displayConfig?.default_currency || 'CNY'} · ${displayConfig?.privacy_mode ? '隐私开启' : '隐私关闭'}` + return ( -
- {/* 顶部标题「我的」+ 用户标识 */} -

我的

-

- {user?.email || '已登录用户'} -

+
+ {/* 顶部标题栏 + 主题切换 */} +
+

我的

+ +
-
- {/* 管理员专属控制台卡片 */} - {isAdmin && ( -
-
-
- ◆ -

系统管理员权限

-
-

- 管理全平台银行、卡产品、公共权益与 AI 配置 -

+ {/* 首屏加载失败防护条 */} + {loadError && ( +
+ +
+ 偏好设置加载失败,已展示默认或本地缓存项 + +
+
+
+ )} + + {/* 账号头卡(消除硬编码渐变,角色胶囊与进入后台按钮平顺统一) */} +
+
+ {(user?.email?.[0] || 'U').toUpperCase()} +
+
+

+ {user?.email || '已登录用户'} +

+
+ {isAdmin ? ( + <> + + ◆ 管理员 + + + + ) : ( + + 普通用户 + + )} +
+
+
+ + {loadingPrefs && !displayConfig ? ( +
+ +
+ ) : ( +
+ {/* 分组一:卡包与权益管理(路由跳转组) */} +
+

+ 卡包与权益管理 +

+
+ } + title='家庭管理' + subtitle='持卡人与卡片管理' + onClick={() => router.push('/holders')} + /> + } + title='优惠活动' + subtitle='可用优惠' + onClick={() => router.push('/promos')} + /> + } + title='我的权益' + subtitle='权益使用进度' + onClick={() => router.push('/benefits')} + />
+
+ + {/* 分组二:数据同步与偏好设置(BottomSheet 二级抽屉组) */} +
+

+ 数据同步与偏好设置 +

+
+ {/* 邮箱账单导入 */} + } + title='邮箱账单导入' + subtitle='Gmail 直连拉取与专属 .eml 补录' + onClick={() => setShowGmailSheet(true)} + badge={ + gmailLoading ? ( + + 加载中… + + ) : gmailError ? ( +
+ + 加载失败 + + { + e.stopPropagation() + void loadGmail() + }} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ' ') { + e.stopPropagation() + void loadGmail() + } + }} + className='cursor-pointer rounded-md border border-d-border bg-d-subtle px-1.5 py-0.5 text-[11px] font-medium text-d-accent-light active:bg-d-surface hover:border-d-accent/40' + > + 重试 + +
+ ) : ( + + {gmailSummary} + + ) + } + /> + + {/* 提醒偏好 */} + } + title='提醒偏好' + subtitle='还款节点、权益到期与免打扰时段' + onClick={() => setShowReminderSheet(true)} + badge={ + + {reminderSummary} + + } + /> + + {/* 显示与币种 */} + } + title='显示与币种' + subtitle='折算目标币种、卡面字段与隐私遮罩' + onClick={() => setShowDisplaySheet(true)} + badge={ + + {displaySummary} + + } + /> +
+
+ + {/* 分组三:账号退出 */} +
- )} - - {/* 管理入口列表(§5.1) */} - } - title='家庭管理' - subtitle='持卡人与卡片管理' - onClick={() => router.push('/holders')} - /> - - } - title='优惠活动' - subtitle='可用优惠' - onClick={() => router.push('/promos')} - /> - - } - title='我的权益' - subtitle='权益使用进度' - onClick={() => router.push('/benefits')} - /> +
+ )} - } - title='邮箱账单导入' - subtitle='Gmail 直连拉取,专属地址补录' - onClick={() => setOpenGmail(v => !v)} - expanded={openGmail} - rightSlot={ - - 专属就绪 - - } - /> + {/* BottomSheet 1: 邮箱账单导入 */} + { + setShowGmailSheet(false) + void loadGmail() + }} + > +
+ {/* Gmail 直连面板 */} + - {/* 邮箱账单导入展开区:Gmail 直连为主,专属地址保留为补录通道 */} - {openGmail && ( -
- + {/* 查看流水入口 */} + -
- -
+ {/* 专属 .eml 补录卡片 */} +
+

收账单邮箱(补录通道)

+

+ 把账单邮件作为附件(.eml)转发到此专属地址补录。银行自动转发会被 DMARC 拒收,日常导入建议使用 Gmail 直连。 +

- {/* 账单补录地址 */} -
-
-
- -
+ {forwardAddress && ( +
-

收账单邮箱(补录)

-

- 把账单邮件作为附件(.eml)转发到此地址补录。银行自动转发会被 DMARC 拒收,日常导入请用上方 Gmail 直连 +

专属地址

+

+ {forwardAddress}

+
- -
- - {forwardAddress && ( -
-
-

专属地址

-

- {forwardAddress} -

-
- -
- )} - -
-

- 该地址包含你的用户 ID,系统按收件地址归属到你的账号。仅用于手动转发 .eml 附件补录,勿配置自动转发规则。 -

-
-
+ )}
- )} +
+ - {/* 提醒偏好:折叠保留 ReminderPreferencesCard 全部功能 */} - } - title='提醒偏好' - subtitle='还款提醒通道与节点' - onClick={() => setOpenReminder(v => !v)} - expanded={openReminder} - /> - {openReminder && ( + {/* BottomSheet 2: 提醒偏好配置 */} + setShowReminderSheet(false)} + > +
{ - await updateReminder(updates) - setNotice({ open: true, message: '提醒规则设置已保存', severity: 'success' }) + onChange={async (updates) => { + try { + await updateReminder(updates) + setNotice({ open: true, message: '提醒规则已保存', severity: 'success' }) + } catch (err) { + setNotice({ + open: true, + message: err instanceof Error ? err.message : '保存失败,已自动回滚', + severity: 'error', + }) + } }} disabled={loadingPrefs} /> - )} +
+
- {/* 设置:折叠保留 DisplayPreferencesCard 全部功能 */} - } - title='设置' - subtitle='界面显示偏好与隐私模式' - onClick={() => setOpenSettings(v => !v)} - expanded={openSettings} - /> - {openSettings && ( + {/* BottomSheet 3: 显示与币种偏好 */} + setShowDisplaySheet(false)} + > +
{ - await updateDisplay(updates) - setNotice({ open: true, message: '界面显示偏好已保存', severity: 'success' }) + onChange={async (updates) => { + try { + await updateDisplay(updates) + setNotice({ open: true, message: '显示偏好已保存', severity: 'success' }) + } catch (err) { + setNotice({ + open: true, + message: err instanceof Error ? err.message : '保存失败,已自动回滚', + severity: 'error', + }) + } }} disabled={loadingPrefs} /> - )} - - {/* 退出登录(单独一行,避免误触) */} -
-
-
+
+ + {/* 退出登录二次确认弹窗 */} + !loggingOut && setShowLogoutDialog(false)} + actions={ + <> + + + + } + > +

+ 确定要退出当前账号吗?本地缓存与偏好配置将安全保留。 +

+
+ {/* 操作提示 Toast */} setNotice(prev => ({ ...prev, open: false }))} + onClose={() => setNotice((prev) => ({ ...prev, open: false }))} />
) diff --git a/app/admin/settings/page.tsx b/app/admin/settings/page.tsx index 848bfa5..56cf70d 100644 --- a/app/admin/settings/page.tsx +++ b/app/admin/settings/page.tsx @@ -1,13 +1,13 @@ 'use client' -import { useState, useEffect } from 'react' -import { Button } from '@/components/obsidian/controls' -import { TextField } from '@/components/obsidian/fields' -import { Toggle } from '@/components/obsidian/controls' +import { useState, useEffect, useCallback, useMemo } from 'react' +import { Button, Toggle } from '@/components/obsidian/controls' +import { TextField, SelectField } from '@/components/obsidian/fields' import { Alert, Spinner } from '@/components/obsidian/feedback' -import { Toast } from '@/components/obsidian/overlays' +import { Toast, ConfirmDialog } from '@/components/obsidian/overlays' import { CheckIcon } from '@/components/icons/WcIcon' import { getSystemSettings, updateSystemSettings } from '@/lib/api/admin' +import { CURRENCY_OPTIONS } from '@/components/settings/shared' interface SystemSettings { platformName: string @@ -22,77 +22,235 @@ interface SystemSettings { [key: string]: unknown } -/** 服务端派生的状态标志(_set),不是可写设置,保存时须排除。 */ -const isDerivedSettingKey = (key: string) => key.endsWith('_set') +const DEFAULT_SETTINGS: SystemSettings = { + platformName: 'WorldCredit', + supportEmail: 'support@worldcredit.com', + enableRegistration: true, + maintenanceMode: false, + defaultCurrency: 'CNY', + ai_base_url: 'https://api.openai.com/v1', + ai_model: 'gpt-4o', +} + +type DraftKey = 'platformName' | 'supportEmail' | 'defaultCurrency' | 'ai_base_url' | 'ai_model' +const DRAFT_KEYS: DraftKey[] = ['platformName', 'supportEmail', 'defaultCurrency', 'ai_base_url', 'ai_model'] -export default function SettingsPage() { +export default function AdminSettingsPage() { const [loading, setLoading] = useState(true) + const [loadError, setLoadError] = useState(null) const [saving, setSaving] = useState(false) - const [settings, setSettings] = useState({ - platformName: 'WorldCredit', - supportEmail: 'support@worldcredit.com', - enableRegistration: true, - maintenanceMode: false, - defaultCurrency: 'CNY' - }) - const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' as 'success' | 'error' }) + const [toggleBusy, setToggleBusy] = useState<'enableRegistration' | 'maintenanceMode' | null>(null) + + // 服务端真实基准值(用于对比 dirty 和防覆盖) + const [serverSettings, setServerSettings] = useState(null) + // 前端编辑草稿 + const [formSettings, setFormSettings] = useState(DEFAULT_SETTINGS) + const [aiKeyConfigured, setAiKeyConfigured] = useState(false) - // 只写不读的草稿:密钥从不从服务端取回,输入框始终为空 + // 只写不读:密钥从不从服务端取回,输入框始终初始为空 const [aiApiKeyInput, setAiApiKeyInput] = useState('') - useEffect(() => { - const fetchData = async () => { - setLoading(true) - try { - const data = await getSystemSettings() - if (Object.keys(data).length > 0) { - setAiKeyConfigured(data.ai_api_key_set === true) - setSettings(prev => ({ ...prev, ...data }) as SystemSettings) - } - } catch (error) { - console.error('Failed to fetch settings:', error) - } finally { - setLoading(false) + // 维护模式高危确认弹窗 + const [confirmMaintenanceOpen, setConfirmMaintenanceOpen] = useState(false) + + const [notice, setNotice] = useState<{ open: boolean; message: string; severity: 'success' | 'error' }>({ + open: false, + message: '', + severity: 'success', + }) + + const fetchData = useCallback(async () => { + setLoading(true) + setLoadError(null) + try { + const data = await getSystemSettings() + const merged: SystemSettings = { + platformName: String(data.platformName || DEFAULT_SETTINGS.platformName), + supportEmail: String(data.supportEmail || DEFAULT_SETTINGS.supportEmail), + enableRegistration: data.enableRegistration !== false, + maintenanceMode: Boolean(data.maintenanceMode), + defaultCurrency: String(data.defaultCurrency || DEFAULT_SETTINGS.defaultCurrency), + ai_base_url: String(data.ai_base_url || DEFAULT_SETTINGS.ai_base_url), + ai_model: String(data.ai_model || DEFAULT_SETTINGS.ai_model), } + setServerSettings(merged) + setFormSettings(merged) + setAiKeyConfigured(data.ai_api_key_set === true) + } catch (err) { + const msg = err instanceof Error ? err.message : '拉取系统设置失败' + console.error('Failed to fetch settings:', err) + setLoadError(msg) + setServerSettings(null) // 失败时清空,防止被保存覆盖 + } finally { + setLoading(false) } - fetchData() }, []) - const handleSave = async (key: string, value: string | boolean) => { + useEffect(() => { + void fetchData() + }, [fetchData]) + + // 计算 dirty 字段列表 + const dirtyKeys = useMemo(() => { + if (!serverSettings) return [] + return DRAFT_KEYS.filter((k) => (formSettings[k] ?? '') !== (serverSettings[k] ?? '')) + }, [serverSettings, formSettings]) + + const hasDraftChanges = dirtyKeys.length > 0 || aiApiKeyInput.trim().length > 0 + const canSave = !loading && !loadError && serverSettings !== null && hasDraftChanges + + // 校验:邮箱格式 + const emailInvalid = Boolean( + formSettings.supportEmail && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formSettings.supportEmail) + ) + + // 统一保存草稿表单(基础参数 + AI 端点/模型 + 可选新 API Key) + const handleSaveAll = async () => { + if (!serverSettings || !canSave) return + if (emailInvalid) { + setNotice({ open: true, message: '请填写合法的客服支持邮箱', severity: 'error' }) + return + } + setSaving(true) try { - await updateSystemSettings(key, value) - setSettings({ ...settings, [key]: value }) - setSnackbar({ open: true, message: '设置已更新', severity: 'success' }) - } catch (error) { - console.error('Update failed:', error) - setSnackbar({ open: true, message: '更新失败', severity: 'error' }) + // 1. 提交所有 dirty 字段(串行提交,避免并发写冲突导致丢更新) + const succeededKeys: DraftKey[] = [] + const failedKeys: DraftKey[] = [] + + for (const k of dirtyKeys) { + try { + await updateSystemSettings(k, formSettings[k] as string | boolean) + succeededKeys.push(k) + } catch (err) { + failedKeys.push(k) + console.error(`Failed to save setting ${k}:`, err) + } + } + + // 仅将成功的字段合并到 serverSettings,失败字段仍保留在 dirty 状态 + if (succeededKeys.length > 0) { + setServerSettings((prev) => { + if (!prev) return prev + const updated = { ...prev } + for (const k of succeededKeys) { + // @ts-expect-error dynamic assign + updated[k] = formSettings[k] + } + return updated + }) + } + + // 2. 若用户输入了新的 API Key,独立安全更新 + let aiKeySuccess = true + const hasAiKeyInput = Boolean(aiApiKeyInput.trim()) + if (hasAiKeyInput) { + try { + await updateSystemSettings('ai_api_key', aiApiKeyInput.trim()) + setAiApiKeyInput('') + setAiKeyConfigured(true) + } catch (err) { + aiKeySuccess = false + console.error('Failed to save ai_api_key:', err) + } + } + + // 3. 汇总成败提示 + const baseFailed = failedKeys.length > 0 + if (!baseFailed && aiKeySuccess) { + setNotice({ open: true, message: '系统设置已保存', severity: 'success' }) + } else if (!baseFailed && !aiKeySuccess) { + setNotice({ + open: true, + message: '基础设置已保存,但 AI API 密钥更新失败,请重试', + severity: 'error', + }) + } else if (succeededKeys.length > 0) { + const keyMsg = `部分设置已保存(${succeededKeys.length} 项成功,${failedKeys.length} 项失败)` + const extraMsg = hasAiKeyInput + ? aiKeySuccess + ? ',API 密钥已保存' + : ',API 密钥保存失败' + : '' + setNotice({ + open: true, + message: `${keyMsg}${extraMsg},未生效项已保留在编辑态`, + severity: 'error', + }) + } else { + setNotice({ + open: true, + message: '保存失败,请检查网络或服务状态', + severity: 'error', + }) + } + } catch (err) { + console.error('Save settings failed:', err) + setNotice({ open: true, message: '保存失败,请检查网络或服务状态', severity: 'error' }) } finally { setSaving(false) } } - const handleSaveAll = async () => { - setSaving(true) + // 撤销未保存改动 + const handleResetDraft = () => { + if (serverSettings) { + setFormSettings({ ...serverSettings }) + setAiApiKeyInput('') + setNotice({ open: true, message: '已撤销未保存的改动', severity: 'success' }) + } + } + + // 运行控制开关保存 + const handleToggleRegistration = async (val: boolean) => { + setToggleBusy('enableRegistration') try { - await Promise.all( - Object.entries(settings) - .filter(([k]) => !isDerivedSettingKey(k)) - .map(([k, v]) => updateSystemSettings(k, v)) - ) - setSnackbar({ open: true, message: '全局设置已保存', severity: 'success' }) - } catch (error) { - console.error('Save all failed:', error) - setSnackbar({ open: true, message: '部分设置保存失败', severity: 'error' }) + await updateSystemSettings('enableRegistration', val) + setFormSettings((prev) => ({ ...prev, enableRegistration: val })) + setServerSettings((prev) => (prev ? { ...prev, enableRegistration: val } : prev)) + setNotice({ open: true, message: '新用户注册设置已更新', severity: 'success' }) + } catch (err) { + console.error('Update registration failed:', err) + setNotice({ open: true, message: '更新失败', severity: 'error' }) } finally { - setSaving(false) + setToggleBusy(null) } } - /** 密钥单独保存:只在用户输入了新值时才写入,避免空值覆盖已配置密钥。 */ - const handleSaveAiKey = async () => { + const handleMaintenanceToggleClick = (val: boolean) => { + if (val) { + // 开启维护模式:拦截弹窗确认 + setConfirmMaintenanceOpen(true) + } else { + // 关闭维护模式:直接执行 + void executeMaintenanceChange(false) + } + } + + const executeMaintenanceChange = async (val: boolean) => { + setToggleBusy('maintenanceMode') + setConfirmMaintenanceOpen(false) + try { + await updateSystemSettings('maintenanceMode', val) + setFormSettings((prev) => ({ ...prev, maintenanceMode: val })) + setServerSettings((prev) => (prev ? { ...prev, maintenanceMode: val } : prev)) + setNotice({ + open: true, + message: val ? '已开启维护模式' : '维护模式已关闭', + severity: 'success', + }) + } catch (err) { + console.error('Update maintenance mode failed:', err) + setNotice({ open: true, message: '更新维护模式失败', severity: 'error' }) + } finally { + setToggleBusy(null) + } + } + + // 单独更新 API Key + const handleSaveAiKeyOnly = async () => { if (!aiApiKeyInput.trim()) { - setSnackbar({ open: true, message: '请输入新的 API Key', severity: 'error' }) + setNotice({ open: true, message: '请输入新的 API Key', severity: 'error' }) return } setSaving(true) @@ -100,10 +258,10 @@ export default function SettingsPage() { await updateSystemSettings('ai_api_key', aiApiKeyInput.trim()) setAiApiKeyInput('') setAiKeyConfigured(true) - setSnackbar({ open: true, message: 'API Key 已更新', severity: 'success' }) - } catch (error) { - console.error('Update AI key failed:', error) - setSnackbar({ open: true, message: 'API Key 更新失败', severity: 'error' }) + setNotice({ open: true, message: 'API Key 已更新', severity: 'success' }) + } catch (err) { + console.error('Update AI key failed:', err) + setNotice({ open: true, message: 'API Key 更新失败', severity: 'error' }) } finally { setSaving(false) } @@ -111,137 +269,277 @@ export default function SettingsPage() { if (loading) { return ( -
- +
+
) } return ( -
-
+
+ {/* 顶栏:标题 + 统一保存/重置控制 */} +
-

系统设置

-

配置全平台基础参数、运行模式及通知信息

+

系统设置

+

+ 配置全平台基础参数、准入运行模式及 AI 自动化参数 +

+
+
+ {hasDraftChanges && ( + + )} +
-
-
- {/* 基础配置 */} -
-

平台基础信息

-
+ {/* 首屏异常告警防护:拉取失败时禁用「保存更改」,严禁覆写线上配置 */} + {loadError && ( +
+ +
+
+

配置拉取失败,已锁死保存操作

+

+ 错误信息:{loadError}。系统禁止在加载失败状态下覆盖线上配置,请检查服务连接后重试。 +

+
+ +
+
+
+ )} + + {/* 维护模式高危常驻警告条 */} + {formSettings.maintenanceMode && ( +
+ +
+ + 当前系统处于维护模式:所有非管理员用户的在线访问已中断。 + + +
+
+
+ )} + + {/* 设置主网格 */} +
+ {/* 左列:平台基础信息(统一草稿表单组) */} +
+
+

平台基础信息

+ + 统一草稿保存 + +
+ +
setSettings({ ...settings, platformName: e.target.value })} + label='平台标题' + value={formSettings.platformName} + disabled={!serverSettings} + onChange={(e) => setFormSettings({ ...formSettings, platformName: e.target.value })} /> + setSettings({ ...settings, supportEmail: e.target.value })} + label='客服支持邮箱' + type='email' + value={formSettings.supportEmail} + disabled={!serverSettings} + error={emailInvalid} + helperText={emailInvalid ? '请输入合法的邮箱格式(如 support@example.com)' : undefined} + onChange={(e) => setFormSettings({ ...formSettings, supportEmail: e.target.value })} /> - setSettings({ ...settings, defaultCurrency: e.target.value })} + + setFormSettings({ ...formSettings, defaultCurrency: e.target.value })} + helperText='新持卡人建档与无币种交易的默认基准币种' />
- {/* 运行状态控制 */} -
-

运行状态控制

-
-
-
-

开放新用户注册

-

关闭后,登录页将隐藏注册入口

-
- handleSave('enableRegistration', v)} - ariaLabel='开放新用户注册' - /> + {/* 右列:运行与准入控制卡(实时开关组,即时生效) */} +
+
+
+

准入与运行控制

+ + 即时生效 +
-
-
-

维护模式

-

开启后,非管理员用户登录将显示维护提示

+
+
+
+

开放新用户注册

+

+ 关闭后,登录页将隐藏注册入口,仅受邀用户可访问 +

+
+ +
+ +
+
+
+

全站维护模式

+ {formSettings.maintenanceMode && ( + + 已开启 + + )} +
+

+ 开启后立即阻断非管理员访问,需二次确认防止误触 +

+
+
- handleSave('maintenanceMode', v)} - ariaLabel='维护模式' - />
+
- - 维护模式会立即中断所有普通用户的实时会话,请谨慎操作。 - +
+

+ 💡 准入开关直接作用于边缘 Worker 鉴权中间件,切换后无需点击上方「保存更改」即可全局即刻生效。 +

- {/* AI Agent 配置 */} -
-

AI Agent 自动化配置

+ {/* 通栏底卡:AI Agent 自动化配置 */} +
+
+

AI Agent 自动化配置

+ + 密钥独立写入 · 端点统一草稿 + +

- 集成 OpenAI 兼容接口,为银行和信用卡管理提供自动补全功能 + 集成 OpenAI 兼容接口,为银行账单解析、汇率折算与智能补全提供大模型算力支持。

+
-
- setAiApiKeyInput(e.target.value)} - /> -
- - {aiKeyConfigured ? '● 已配置' : '○ 未配置'} + {/* 凭据区:只写不回显 */} +
+
+ setAiApiKeyInput(e.target.value)} + helperText='密钥绝不从服务端回显;保存后原密文由 Cloudflare 安全隔离。' + /> +
+
+ + {aiKeyConfigured ? '● 密钥已就绪' : '○ 尚未配置密钥'}
-

- 密钥仅存于服务端,保存后不再回显;AI 调用由服务端代为执行。 -

- setSettings({ ...settings, ai_base_url: e.target.value })} - /> - setSettings({ ...settings, ai_model: e.target.value })} - /> + + {/* 端点与模型:统一纳入表单草稿 */} +
+ setFormSettings({ ...formSettings, ai_base_url: e.target.value })} + helperText='支持官方 OpenAI、Cloudflare AI Gateway 或自建反向代理' + /> + setFormSettings({ ...formSettings, ai_model: e.target.value })} + helperText='推荐使用具备视觉或结构化输出能力的模型(如 gpt-4o, claude-3-5-sonnet)' + /> +
+ {/* 维护模式高危拦截确认弹窗 */} + setConfirmMaintenanceOpen(false)} + actions={ + <> + + + + } + > +

+ 开启全站维护模式后,所有普通用户的实时访问与会话将立即中断,仅管理员账号允许登录后台。确定立即开启吗? +

+
+ + {/* 统一反馈 Toast */} setSnackbar({ ...snackbar, open: false })} + open={notice.open} + message={notice.message} + severity={notice.severity} + autoHideMs={3500} + onClose={() => setNotice((prev) => ({ ...prev, open: false }))} />
) diff --git a/app/api/sync/pull/route.ts b/app/api/sync/pull/route.ts index e86b33f..aaf6dea 100644 --- a/app/api/sync/pull/route.ts +++ b/app/api/sync/pull/route.ts @@ -16,6 +16,11 @@ const SYNCABLE_TABLES = { benefits: { pk: "id", owner: null }, promos: { pk: "id", owner: null }, card_holders: { pk: "id", owner: "t.managed_by = ?" }, + credit_accounts: { + pk: "id", + owner: `EXISTS (SELECT 1 FROM card_holders ch + WHERE ch.id = t.holder_id AND ch.managed_by = ?)`, + }, credit_cards: { pk: "id", owner: `EXISTS (SELECT 1 FROM card_holders ch @@ -27,6 +32,13 @@ const SYNCABLE_TABLES = { JOIN card_holders ch ON ch.id = cc.holder_id WHERE cc.id = t.card_id AND ch.managed_by = ?)`, }, + bill_card_subtotals: { + pk: "id", + owner: `EXISTS (SELECT 1 FROM bills b + JOIN credit_cards cc ON cc.id = b.card_id + JOIN card_holders ch ON ch.id = cc.holder_id + WHERE b.id = t.bill_id AND ch.managed_by = ?)`, + }, payments: { pk: "id", owner: `EXISTS (SELECT 1 FROM bills b @@ -42,6 +54,7 @@ const SYNCABLE_TABLES = { owner: `EXISTS (SELECT 1 FROM recurring_payables rp WHERE rp.id = t.payable_id AND rp.created_by = ?)`, }, + payable_custom_categories: { pk: "id", owner: "t.user_id = ?" }, } as const; type SyncTable = keyof typeof SYNCABLE_TABLES; diff --git a/app/globals.css b/app/globals.css index b7b4943..a6b5761 100644 --- a/app/globals.css +++ b/app/globals.css @@ -22,6 +22,25 @@ --color-d-warn-ink: #ffc46b; --color-d-success-soft: #1a332a; --color-d-success-ink: #6ee7a0; + + /* 亮色新增令牌(暗色为基、亮色新增,语义命名一致) */ + --color-d-light-bg: #f5f7fa; + --color-d-light-surface: #ffffff; + --color-d-light-subtle: #f5f8ff; + --color-d-light-border: #e2e8f0; + --color-d-light-text: #0a1f44; + --color-d-light-muted: #5b6478; + --color-d-light-accent: #1e3a8a; + --color-d-light-accent-light: #3b6fe0; + --color-d-light-gold: #c9a227; + --color-d-light-gold-deep: #8a6d1f; + --color-d-light-gold-soft: #f5eed8; + --color-d-light-danger: #d32f2f; + --color-d-light-danger-soft: #fae6e6; + --color-d-light-danger-ink: #b71c1c; + --color-d-light-warn-ink: #92400e; + --color-d-light-success-soft: #e6efe6; + --color-d-light-success-ink: #1b5e20; } /* @@ -220,6 +239,27 @@ line-height: var(--type-section-line); letter-spacing: var(--type-section-tracking); } +.theme-light, +[data-theme="light"] { + --color-d-bg: var(--color-d-light-bg); + --color-d-surface: var(--color-d-light-surface); + --color-d-subtle: var(--color-d-light-subtle); + --color-d-border: var(--color-d-light-border); + --color-d-text: var(--color-d-light-text); + --color-d-muted: var(--color-d-light-muted); + --color-d-accent: var(--color-d-light-accent); + --color-d-accent-light: var(--color-d-light-accent-light); + --color-d-gold: var(--color-d-light-gold); + --color-d-gold-deep: var(--color-d-light-gold-deep); + --color-d-gold-soft: var(--color-d-light-gold-soft); + --color-d-danger: var(--color-d-light-danger); + --color-d-danger-soft: var(--color-d-light-danger-soft); + --color-d-danger-ink: var(--color-d-light-danger-ink); + --color-d-warn-ink: var(--color-d-light-warn-ink); + --color-d-success-soft: var(--color-d-light-success-soft); + --color-d-success-ink: var(--color-d-light-success-ink); + color-scheme: light; +} .theme-dark, [data-theme="dark"] { --bg: #0F1117; diff --git a/app/layout.tsx b/app/layout.tsx index dabf9a8..13fa65c 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -24,16 +24,22 @@ export const viewport: Viewport = { themeColor: '#0a0f1e', } +const THEME_INIT_SCRIPT = `(function(){try{var m=localStorage.getItem('worldcredit_theme_mode');var r=(m==='light'||m==='dark')?m:(window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light');document.documentElement.setAttribute('data-theme',r);if(r==='light'){document.documentElement.classList.add('theme-light');document.documentElement.classList.remove('theme-dark');}else{document.documentElement.classList.add('theme-dark');document.documentElement.classList.remove('theme-light');}}catch(e){}})();` + export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( - + + + + + + + + + +
+ + +
+ ✓ + {{toastMsg}} +
+
+ + + + + +
+ +
+
+ +

系统全局设置

+
+
+ + +
+
+ + +
+ + +
+ ⚠️ +
+ 全站维护模式生效中:除管理员外,所有普通用户的在线会话均已被拦截并重定向至维护说明页。 +
+ +
+
+ + +
+ +
+
+

+ 🏢 + 平台基础信息 +

+ 草稿统一保存 +
+ +
+ + +

用户端顶栏与登录注册页显示的系统品牌标识

+
+ +
+ + +

展示在异常提示及账单解析失败重试中的技术联络地址

+
+ +
+ + +

新用户初始化注册及未显式指定币种时的默认归集单位

+
+
+ + +
+
+

+ ⚡ + 运行准入控制 +

+ 即点即存 · 即时生效 +
+ +
+
+

开放新用户注册

+

关闭后登录页隐藏注册入口,仅允许已存在用户登录

+
+ +
+ +
+
+

全站维护模式

+

开启前必须通过二次确认拦截;开启后中断普通用户访问

+
+ +
+ +
+ ⚠️ +
+ 高危操作保护:维护模式开启前将弹出拦截确认窗,确认后立即写入 D1 数据库并同步触发 Cloudflare 边缘缓存刷新。 +
+
+
+
+ + +
+
+
+

+ 🤖 + AI Agent 自动化解析配置 +

+

+ 为银行账单邮件解析、权益智能匹配提供 OpenAI 协议兼容的大语言模型代理接口 +

+
+ 凭据独立安全更新 +
+ +
+ +
+
+ + ● 已配置 +
+ +

服务端加密存储且只写不读,防止页面泄露真实密钥。

+ + +
+ + +
+ + +

支持官方 OpenAI、Azure 或自建中转端点,须包含版本路径。

+
+ + +
+ + +

推荐选用 gpt-4o 或 claude-3-5-sonnet 等长上下文视觉模型。

+
+
+
+
+
+ + + +
+
+ ● + 您有未保存的基础参数与 AI 端点变更 +
+
+ + +
+
+
+ + + +
+
+
+
⚠️
+
+

开启全站维护模式确认

+ 高危系统操作拦截 +
+
+

+ 开启维护模式后,所有普通用户的实时在线会话将立即中断,任何非管理员请求将被重定向至维护说明页。确定立即开启吗? +

+ +
+
+
+
+
+ + + + diff --git a/design/baoyu/Admin_Settings_Light.dc.html b/design/baoyu/Admin_Settings_Light.dc.html new file mode 100644 index 0000000..2ef434b --- /dev/null +++ b/design/baoyu/Admin_Settings_Light.dc.html @@ -0,0 +1,797 @@ + + + + + 管理后台 · 系统设置 (亮色) + + + + + + + + +
+ +
+ ✓ + {{toastMsg}} +
+
+ + + +
+
+
+ +

系统全局设置

+
+
+ + +
+
+ +
+ +
+ ⚠️ +
+ 全站维护模式生效中:除管理员外,所有普通用户的在线会话均已被拦截并重定向至维护说明页。 +
+ +
+
+ +
+
+
+

+ 🏢 + 平台基础信息 +

+ 草稿统一保存 +
+ +
+ + +

用户端顶栏与登录注册页显示的系统品牌标识

+
+ +
+ + +

展示在异常提示及账单解析失败重试中的技术联络地址

+
+ +
+ + +

新用户初始化注册及未显式指定币种时的默认归集单位

+
+
+ +
+
+

+ ⚡ + 运行准入控制 +

+ 即点即存 · 即时生效 +
+ +
+
+

开放新用户注册

+

关闭后登录页隐藏注册入口,仅允许已存在用户登录

+
+ +
+ +
+
+

全站维护模式

+

开启前必须通过二次确认拦截;开启后中断普通用户访问

+
+ +
+ +
+ ⚠️ +
+ 高危操作保护:维护模式开启前将弹出拦截确认窗,确认后立即写入 D1 数据库并同步触发 Cloudflare 边缘缓存刷新。 +
+
+
+
+ +
+
+
+

+ 🤖 + AI Agent 自动化解析配置 +

+

+ 为银行账单邮件解析、权益智能匹配提供 OpenAI 协议兼容的大语言模型代理接口 +

+
+ 凭据独立安全更新 +
+ +
+
+
+ + ● 已配置 +
+ +

服务端加密存储且只写不读,防止页面泄露真实密钥。

+ + +
+ +
+ + +

支持官方 OpenAI、Azure 或自建中转端点,须包含版本路径。

+
+ +
+ + +

推荐选用 gpt-4o 或 claude-3-5-sonnet 等长上下文视觉模型。

+
+
+
+
+
+ + +
+
+ ● + 您有未保存的基础参数与 AI 端点变更 +
+
+ + +
+
+
+ + +
+
+
+
⚠️
+
+

开启全站维护模式确认

+ 高危系统操作拦截 +
+
+

+ 开启维护模式后,所有普通用户的实时在线会话将立即中断,任何非管理员请求将被重定向至维护说明页。确定立即开启吗? +

+ +
+
+
+
+
+ + + + diff --git a/design/baoyu/Mobile_Drawer_Display_Dark.dc.html b/design/baoyu/Mobile_Drawer_Display_Dark.dc.html new file mode 100644 index 0000000..b5b0f95 --- /dev/null +++ b/design/baoyu/Mobile_Drawer_Display_Dark.dc.html @@ -0,0 +1,317 @@ + + + + + 移动端 · 显示偏好抽屉 (暗色) + + + + + + + + +
+
+
+ 9:41 + + ●●●● + WiFi + 100% + +
+ +
+

我的

+
+
+
+
+ + +
+
+
+

显示与币种偏好

+ +
+
+ +
+
+
+

高斯模糊隐私模式

+

在看板及账单列表平滑遮罩敏感金额,防止公开场合被窥视

+
+ +
+
+ + +
+
+ + 开放字段 +
+ +

+ 所有持卡人的外币消费与未出账明细将实时折算为该基础币种,便于全局资产概览。 +

+
+ + +
+

账单卡片字段定制:

+ +
+
+

最低还款额

+

显示最低还款额度提示

+
+ +
+ +
+
+

账单日

+

卡片展示出账日期

+
+ +
+ +
+
+

卡号后 4 位

+

展示末四位尾号用于核对

+
+ +
+ +
+
+
+

卡片年费信息 (show_annual_fee)

+ 开放字段 +
+

常驻年费收取周期与减免达标进度

+
+ +
+
+
+
+
+
+ + + + diff --git a/design/baoyu/Mobile_Drawer_Display_Light.dc.html b/design/baoyu/Mobile_Drawer_Display_Light.dc.html new file mode 100644 index 0000000..7314b9e --- /dev/null +++ b/design/baoyu/Mobile_Drawer_Display_Light.dc.html @@ -0,0 +1,311 @@ + + + + + 移动端 · 显示偏好抽屉 (亮色) + + + + + + + + +
+
+
+ 9:41 + + ●●●● + WiFi + 100% + +
+ +
+

我的

+
+
+
+ +
+
+
+

显示与币种偏好

+ +
+
+
+
+
+

高斯模糊隐私模式

+

在看板及账单列表平滑遮罩敏感金额,防止公开场合被窥视

+
+ +
+
+ +
+
+ + 开放字段 +
+ +

+ 所有持卡人的外币消费与未出账明细将实时折算为该基础币种,便于全局资产概览。 +

+
+ +
+

账单卡片字段定制:

+ +
+
+

最低还款额

+

显示最低还款额度提示

+
+ +
+ +
+
+

账单日

+

卡片展示出账日期

+
+ +
+ +
+
+

卡号后 4 位

+

展示末四位尾号用于核对

+
+ +
+ +
+
+
+

卡片年费信息 (show_annual_fee)

+ 开放字段 +
+

常驻年费收取周期与减免达标进度

+
+ +
+
+
+
+
+
+ + + + diff --git a/design/baoyu/Mobile_Drawer_Gmail_Dark.dc.html b/design/baoyu/Mobile_Drawer_Gmail_Dark.dc.html new file mode 100644 index 0000000..e15eab1 --- /dev/null +++ b/design/baoyu/Mobile_Drawer_Gmail_Dark.dc.html @@ -0,0 +1,252 @@ + + + + + 移动端 · 邮箱导入抽屉 (暗色) + + + + + + + + +
+
+
+ 9:41 + + ●●●● + WiFi + 100% + +
+ +
+

我的

+
+
+
+
+ + +
+
+
+

邮箱账单导入

+ +
+
+ +
+
+ bills.alex@gmail.com + ● 已授权连接 +
+

上次同步:今天 16:20 | 新增 4 笔账单,无草稿

+
+ + +
+
+ + + + + +
+
+ 📥 + 专属收账单邮箱(补录) +
+

+ 把银行邮件以 .eml 附件 形式转发到专属地址。避免自动转发导致 DMARC 拒收。 +

+
+ bills+usr_92a8f@20160325.xyz + +
+
+ 系统根据邮箱唯一哈希将账单自动归属到当前账户,原文入库留证。 +
+
+
+
+
+
+ + + + diff --git a/design/baoyu/Mobile_Drawer_Gmail_Light.dc.html b/design/baoyu/Mobile_Drawer_Gmail_Light.dc.html new file mode 100644 index 0000000..8714355 --- /dev/null +++ b/design/baoyu/Mobile_Drawer_Gmail_Light.dc.html @@ -0,0 +1,233 @@ + + + + + 移动端 · 邮箱导入抽屉 (亮色) + + + + + + + + +
+
+
+ 9:41 + + ●●●● + WiFi + 100% + +
+ +
+

我的

+
+
+
+ +
+
+
+

邮箱账单导入

+ +
+
+
+
+ bills.alex@gmail.com + ● 已授权连接 +
+

上次同步:今天 16:20 | 新增 4 笔账单

+
+ + +
+
+ + + +
+
+ 📥 + 专属收账单邮箱(补录) +
+

+ 把银行邮件以 .eml 附件 形式转发到专属地址。避免自动转发导致 DMARC 拒收。 +

+
+ bills+usr_92a8f@20160325.xyz + +
+
+
+
+
+
+ + + + diff --git a/design/baoyu/Mobile_Drawer_Reminders_Dark.dc.html b/design/baoyu/Mobile_Drawer_Reminders_Dark.dc.html new file mode 100644 index 0000000..a2b9896 --- /dev/null +++ b/design/baoyu/Mobile_Drawer_Reminders_Dark.dc.html @@ -0,0 +1,348 @@ + + + + + 移动端 · 提醒偏好抽屉 (暗色) + + + + + + + + +
+
+
+ 9:41 + + ●●●● + WiFi + 100% + +
+ +
+

我的

+
+
+
+
+ + +
+
+
+

提醒偏好配置

+ +
+
+ +

+ 💳 + 账单还款提醒 +

+
+ 还款日前提醒节点(多选): +
+ + + + +
+ +
+
+

Web Push 浏览器通道

+

通过系统通知中心直达设备

+
+ +
+ +
+
+ 免打扰起始 + +
+
+ 免打扰结束 + +
+
+ + +
+ + +
+

+ 👑 + 权益机会提醒 +

+ +
+
+
+ 提醒时区 (标准下拉) + +
+ +
+ 每日提醒推送时间 + +
+ + 权益到期提醒节点: +
+ + + + +
+ + 权益领取截止提醒节点: +
+ + +
+
+
+
+
+
+ + + + diff --git a/design/baoyu/Mobile_Drawer_Reminders_Light.dc.html b/design/baoyu/Mobile_Drawer_Reminders_Light.dc.html new file mode 100644 index 0000000..4e037d3 --- /dev/null +++ b/design/baoyu/Mobile_Drawer_Reminders_Light.dc.html @@ -0,0 +1,336 @@ + + + + + 移动端 · 提醒偏好抽屉 (亮色) + + + + + + + + +
+
+
+ 9:41 + + ●●●● + WiFi + 100% + +
+ +
+

我的

+
+
+
+ +
+
+
+

提醒偏好配置

+ +
+
+

+ 💳 + 账单还款提醒 +

+
+ 还款日前提醒节点(多选): +
+ + + + +
+ +
+
+

Web Push 浏览器通道

+

通过系统通知中心直达设备

+
+ +
+ +
+
+ 免打扰起始 + +
+
+ 免打扰结束 + +
+
+ + +
+ +
+

+ 👑 + 权益机会提醒 +

+ +
+
+
+ 提醒时区 (标准下拉) + +
+ +
+ 每日提醒推送时间 + +
+ + 权益到期提醒节点: +
+ + + +
+
+
+
+
+
+ + + + diff --git a/design/baoyu/Mobile_Settings_Dark.dc.html b/design/baoyu/Mobile_Settings_Dark.dc.html new file mode 100644 index 0000000..e221201 --- /dev/null +++ b/design/baoyu/Mobile_Settings_Dark.dc.html @@ -0,0 +1,1172 @@ + + + + + 移动端 · 设置主页 (暗色) + + + + + + + + +
+ +
+ + +
+ 9:41 + + ●●●● + WiFi + 100% + +
+ + + +
+ ✓ + {{toastMessage}} +
+
+ + +
+ +
+

我的

+ 🌙 暗色基线 +
+ + + + + + +
+ + + + + +
+ + + +
+ + + + + + + + +
+ + +
+ +
+
+ + +
+ + + + +
+ + + +
+
+
+
+

邮箱账单导入

+ +
+
+ +
+
+ bills.alex@gmail.com + ● 已授权 +
+

上次同步:今天 16:20 | 新增 4 笔账单

+
+ + +
+
+ + + + + +
+

专属收账单邮箱(补录)

+

仅用于手动转发 .eml 邮件附件,请勿配置自动转发规则。

+
+ bills+usr_92a8f@20160325.xyz + +
+
+
+
+
+
+ + + +
+
+
+
+

提醒偏好配置

+ +
+
+ +
+

💳 账单还款提醒

+
+

还款日前提醒节点:

+
+ + + + +
+ +
+
+

Web Push 浏览器通道

+

桌面与手机浏览器系统级通知

+
+ +
+ +
+
+ 免打扰起始 + +
+
+ 免打扰结束 + +
+
+ + +
+
+ + +
+
+

👑 权益机会提醒

+ +
+
+
+ + +
+ +
+ + +
+ +

权益到期提醒节点:

+
+ + + + +
+ +

领取截止提醒节点:

+
+ + +
+
+
+
+
+
+
+ + + +
+
+
+
+

显示与币种偏好

+ +
+
+ +
+
+
+

高斯模糊隐私模式

+

开启后看板与账单关键金额将被平滑遮罩,防止公开场所窥屏

+
+ +
+
+ + +
+ + +

外币消费账单将根据最新汇率折算并汇总展示至看板首屏

+
+ + +
+

账单卡片信息字段定制:

+ +
+
+

最低还款额 (show_min_payment)

+
+ +
+ +
+
+

账单日 (show_statement_date)

+
+ +
+ +
+
+

卡号后 4 位 (show_card_last4)

+
+ +
+ + +
+
+

卡片年费信息 (show_annual_fee)

+

在卡片详情与列表标签中常驻年费收取周期与减免状态

+
+ +
+
+
+
+
+
+ + + +
+
+

退出登录

+

确定要退出当前账号吗?本地缓存与偏好配置将安全保留。

+
+ + +
+
+
+
+ + + +
+
+

断开 Gmail 授权

+

断开后将清除服务端邮箱授权与邮件原文副本,已入库账单不受影响。确定断开吗?

+
+ + +
+
+
+
+
+
+ + + + diff --git a/design/baoyu/Mobile_Settings_Light.dc.html b/design/baoyu/Mobile_Settings_Light.dc.html new file mode 100644 index 0000000..b93e980 --- /dev/null +++ b/design/baoyu/Mobile_Settings_Light.dc.html @@ -0,0 +1,1059 @@ + + + + + 移动端 · 设置主页 (亮色) + + + + + + + + +
+
+
+ 9:41 + + ●●●● + WiFi + 100% + +
+ + +
+ ✓ + {{toastMessage}} +
+
+ +
+
+

我的

+ ☀️ 亮色对齐 +
+ + + + +
+ + + + + +
+ + +
+ + + + + +
+ +
+ +
+
+ + +
+ + + + +
+ + + +
+
+
+
+

邮箱账单导入

+ +
+
+
+
+ bills.alex@gmail.com + ● 已授权 +
+

上次同步:今天 16:20 | 新增 4 笔账单

+
+ + +
+
+ + + +
+

专属收账单邮箱(补录)

+

仅用于手动转发 .eml 邮件附件,请勿配置自动转发规则。

+
+ bills+usr_92a8f@20160325.xyz + +
+
+
+
+
+
+ + + +
+
+
+
+

提醒偏好配置

+ +
+
+
+

💳 账单还款提醒

+
+

还款日前提醒节点:

+
+ + + + +
+ +
+
+

Web Push 浏览器通道

+

桌面与手机浏览器系统级通知

+
+ +
+ +
+
+ 免打扰起始 + +
+
+ 免打扰结束 + +
+
+ + +
+
+ +
+
+

👑 权益机会提醒

+ +
+
+
+ + +
+ +
+ + +
+ +

权益到期提醒节点:

+
+ + + +
+
+
+
+
+
+
+ + + +
+
+
+
+

显示与币种偏好

+ +
+
+
+
+
+

高斯模糊隐私模式

+

开启后看板与账单关键金额将被平滑遮罩,防止公开场所窥屏

+
+ +
+
+ +
+ + +
+ +
+

账单卡片信息字段定制:

+ +
+
+

最低还款额 (show_min_payment)

+
+ +
+ +
+
+

账单日 (show_statement_date)

+
+ +
+ +
+
+

卡号后 4 位 (show_card_last4)

+
+ +
+ +
+
+

卡片年费信息 (show_annual_fee)

+

常驻年费收取周期与减免达标进度

+
+ +
+
+
+
+
+
+ + + +
+
+

退出登录

+

确定要退出当前账号吗?本地缓存与偏好配置将安全保留。

+
+ + +
+
+
+
+ + +
+
+

断开 Gmail 授权

+

断开后将清除服务端邮箱授权与邮件原文副本,已入库账单不受影响。确定断开吗?

+
+ + +
+
+
+
+
+
+ + + + diff --git a/design/baoyu/README.md b/design/baoyu/README.md new file mode 100644 index 0000000..b423baa --- /dev/null +++ b/design/baoyu/README.md @@ -0,0 +1,43 @@ +# WorldCredit 现行设计源(baoyu-design) + +> **唯一设计真源**:本项目现行设计工具链为 **baoyu-design**(本机 `claude-design` / `claude-design-system`)。 +> 原 `design/openpencil/` 与 `.op` 文件已作为历史存档保留,不再对其进行写操作。 + +--- + +## 1. 目录架构 + +```text +design/baoyu/ +├── canvas.json # 画布总索引(定义页面、画板坐标尺寸与排序) +├── tokens.json # 设计系统令牌真源(暗色 + 亮色 d-* 令牌全集) +├── support.js # 交互画板无头/本地预览支持脚本 +├── README.md # 本说明文档 +├── Mobile_Settings_Dark.dc.html # 移动端 /settings 暗色主视图 +├── Mobile_Settings_Light.dc.html # 移动端 /settings 亮色主视图 +├── Mobile_Drawer_Gmail_Dark.dc.html # 移动端 Gmail 导入抽屉 (暗色) +├── Mobile_Drawer_Gmail_Light.dc.html # 移动端 Gmail 导入抽屉 (亮色) +├── Mobile_Drawer_Reminders_Dark.dc.html # 移动端 提醒偏好抽屉 (暗色) +├── Mobile_Drawer_Reminders_Light.dc.html# 移动端 提醒偏好抽屉 (亮色) +├── Mobile_Drawer_Display_Dark.dc.html # 移动端 显示与币种抽屉 (暗色) +├── Mobile_Drawer_Display_Light.dc.html # 移动端 显示与币种抽屉 (亮色) +├── Admin_Settings_Dark.dc.html # 管理后台 /admin/settings 桌面端 (暗色) +└── Admin_Settings_Light.dc.html # 管理后台 /admin/settings 桌面端 (亮色) +``` + +--- + +## 2. Token 三方对齐契约 + +所有 UI 样式均由三方联合约束,禁止单边造色或硬编码: +1. **设计源令牌**:`design/baoyu/tokens.json`(定义 `name`, `value`, `lightValue`, `cssVar`) +2. **基础映射池**:`design/openpencil/vars/foundations.json`(保留同步作为底层 token 字典) +3. **运行时样式**:`app/globals.css`(在 `@theme` 声明 `--color-d-*` 与 `--color-d-light-*`,并在 `.theme-light, [data-theme="light"]` 中动态重载) + +--- + +## 3. 门禁验证命令 + +门禁检查已无缝迁移至 `design/baoyu/`: +- **门禁入口**:`bash design/openpencil/verify-batch.sh --source-only`(在 CI 与本地均可执行,生成 `design/openpencil/batch-report.json`) +- **独立 Python 脚本**:`python3 design/baoyu/verify-design.py` diff --git a/design/baoyu/canvas.json b/design/baoyu/canvas.json new file mode 100644 index 0000000..18c90d4 --- /dev/null +++ b/design/baoyu/canvas.json @@ -0,0 +1,170 @@ +{ + "v": 3, + "createdOnFiles": { + "v": 1, + "at": "2026-11-04T10:55:00.000Z" + }, + "title": "WorldCredit 设置页重设计(候选画板)", + "launch": { + "view": "canvas" + }, + "pages": [ + { + "id": "mobile", + "name": "移动端 /settings" + }, + { + "id": "admin", + "name": "管理后台 /admin/settings" + } + ], + "boards": { + "Mobile_Settings_Dark.dc.html": { + "x": 0, + "y": 0, + "w": 390, + "h": 844, + "title": "移动端 · 设置主页 (暗色)", + "page": "mobile", + "is_interactive": true, + "radius": 40 + }, + "Mobile_Drawer_Gmail_Dark.dc.html": { + "x": 470, + "y": 0, + "w": 390, + "h": 844, + "title": "移动端 · 邮箱导入抽屉 (暗色)", + "page": "mobile", + "is_interactive": true, + "radius": 40 + }, + "Mobile_Drawer_Reminders_Dark.dc.html": { + "x": 940, + "y": 0, + "w": 390, + "h": 844, + "title": "移动端 · 提醒偏好抽屉 (暗色)", + "page": "mobile", + "is_interactive": true, + "radius": 40 + }, + "Mobile_Drawer_Display_Dark.dc.html": { + "x": 1410, + "y": 0, + "w": 390, + "h": 844, + "title": "移动端 · 显示偏好抽屉 (暗色)", + "page": "mobile", + "is_interactive": true, + "radius": 40 + }, + "Mobile_Settings_Light.dc.html": { + "x": 0, + "y": 1200, + "w": 390, + "h": 844, + "title": "移动端 · 设置主页 (亮色)", + "page": "mobile", + "is_interactive": true, + "radius": 40 + }, + "Mobile_Drawer_Gmail_Light.dc.html": { + "x": 470, + "y": 1200, + "w": 390, + "h": 844, + "title": "移动端 · 邮箱导入抽屉 (亮色)", + "page": "mobile", + "is_interactive": true, + "radius": 40 + }, + "Mobile_Drawer_Reminders_Light.dc.html": { + "x": 940, + "y": 1200, + "w": 390, + "h": 844, + "title": "移动端 · 提醒偏好抽屉 (亮色)", + "page": "mobile", + "is_interactive": true, + "radius": 40 + }, + "Mobile_Drawer_Display_Light.dc.html": { + "x": 1410, + "y": 1200, + "w": 390, + "h": 844, + "title": "移动端 · 显示偏好抽屉 (亮色)", + "page": "mobile", + "is_interactive": true, + "radius": 40 + }, + "Admin_Settings_Dark.dc.html": { + "x": 0, + "y": 0, + "w": 1440, + "h": 900, + "title": "管理后台 · 系统设置 (暗色)", + "page": "admin", + "is_interactive": true, + "radius": 12 + }, + "Admin_Settings_Light.dc.html": { + "x": 0, + "y": 1200, + "w": 1440, + "h": 900, + "title": "管理后台 · 系统设置 (亮色)", + "page": "admin", + "is_interactive": true, + "radius": 12 + } + }, + "order": [ + "Mobile_Settings_Dark.dc.html", + "Mobile_Drawer_Gmail_Dark.dc.html", + "Mobile_Drawer_Reminders_Dark.dc.html", + "Mobile_Drawer_Display_Dark.dc.html", + "Mobile_Settings_Light.dc.html", + "Mobile_Drawer_Gmail_Light.dc.html", + "Mobile_Drawer_Reminders_Light.dc.html", + "Mobile_Drawer_Display_Light.dc.html", + "Admin_Settings_Dark.dc.html", + "Admin_Settings_Light.dc.html" + ], + "notes": { + "title_mobile_dark": { + "x": 0, + "y": -280, + "text": "移动端 /settings 候选画板(暗色主题 · ObsidianUI 基线)", + "kind": "title1", + "page": "mobile", + "maxW": 1800 + }, + "title_mobile_light": { + "x": 0, + "y": 920, + "text": "移动端 /settings 候选画板(亮色主题 · 补充令牌对齐)", + "kind": "title1", + "page": "mobile", + "maxW": 1800 + }, + "title_admin_dark": { + "x": 0, + "y": -280, + "text": "管理后台 /admin/settings 候选画板(暗色主题 · ObsidianUI 基线)", + "kind": "title1", + "page": "admin", + "maxW": 1440 + }, + "title_admin_light": { + "x": 0, + "y": 920, + "text": "管理后台 /admin/settings 候选画板(亮色主题 · 补充令牌对齐)", + "kind": "title1", + "page": "admin", + "maxW": 1440 + } + }, + "designSystems": [] +} diff --git a/design/baoyu/support.js b/design/baoyu/support.js new file mode 100644 index 0000000..ef2024a --- /dev/null +++ b/design/baoyu/support.js @@ -0,0 +1,12 @@ +// support.js - WorldCredit Settings Canvas Support Utilities +console.log('WorldCredit Settings Canvas runtime loaded'); + +// Fallback for standalone preview when DC runtime is not attached +if (typeof window !== 'undefined' && !window.__DC_RUNTIME__) { + const style = document.createElement('style'); + style.textContent = ` + sc-if { display: none !important; } + .toast-pill { display: none !important; } + `; + document.head.appendChild(style); +} diff --git a/design/baoyu/tokens.json b/design/baoyu/tokens.json new file mode 100644 index 0000000..9c4a617 --- /dev/null +++ b/design/baoyu/tokens.json @@ -0,0 +1,171 @@ +{ + "color": { + "tokens": [ + { + "name": "d-bg", + "value": "#0A0F1E", + "lightValue": "#F5F7FA", + "cssVar": "--color-d-bg", + "usage": "页面底层画布背景" + }, + { + "name": "d-surface", + "value": "#131A2A", + "lightValue": "#FFFFFF", + "cssVar": "--color-d-surface", + "usage": "主要卡片与容器表面背景" + }, + { + "name": "d-subtle", + "value": "#1A2334", + "lightValue": "#F5F8FF", + "cssVar": "--color-d-subtle", + "usage": "次级卡片底色、输入框背景及悬浮态" + }, + { + "name": "d-border", + "value": "#26304A", + "lightValue": "#E2E8F0", + "cssVar": "--color-d-border", + "usage": "描边边框与列表分割线" + }, + { + "name": "d-text", + "value": "#F5F7FA", + "lightValue": "#0A1F44", + "cssVar": "--color-d-text", + "usage": "主标题、正文与主要文本" + }, + { + "name": "d-muted", + "value": "#9AA6BC", + "lightValue": "#5B6478", + "cssVar": "--color-d-muted", + "usage": "次级说明、占位符与图标弱色" + }, + { + "name": "d-accent", + "value": "#3B6FE0", + "lightValue": "#1E3A8A", + "cssVar": "--color-d-accent", + "usage": "主要行动按钮与开关激活填充" + }, + { + "name": "d-accent-light", + "value": "#7AADFF", + "lightValue": "#3B6FE0", + "cssVar": "--color-d-accent-light", + "usage": "深底链接、高亮图标与强调文本" + }, + { + "name": "d-gold", + "value": "#F0C75E", + "lightValue": "#C9A227", + "cssVar": "--color-d-gold", + "usage": "管理员与尊享角色标签、高光徽章" + }, + { + "name": "d-gold-deep", + "value": "#D9A93F", + "lightValue": "#8A6D1F", + "cssVar": "--color-d-gold-deep", + "usage": "金质边框与深度渐变过渡" + }, + { + "name": "d-gold-soft", + "value": "#3A3320", + "lightValue": "#F5EED8", + "cssVar": "--color-d-gold-soft", + "usage": "金质微光背景与胶囊填充" + }, + { + "name": "d-danger", + "value": "#E5484D", + "lightValue": "#D32F2F", + "cssVar": "--color-d-danger", + "usage": "破坏性操作按钮填充与必填星号" + }, + { + "name": "d-danger-soft", + "value": "#3A222A", + "lightValue": "#FAE6E6", + "cssVar": "--color-d-danger-soft", + "usage": "错误横幅底色与告警容器底" + }, + { + "name": "d-danger-ink", + "value": "#FF8A8A", + "lightValue": "#B71C1C", + "cssVar": "--color-d-danger-ink", + "usage": "退出登录、断开连接等危险文字" + }, + { + "name": "d-warn-ink", + "value": "#FFC46B", + "lightValue": "#92400E", + "cssVar": "--color-d-warn-ink", + "usage": "维护模式警告文字与临期提示" + }, + { + "name": "d-success-soft", + "value": "#1A332A", + "lightValue": "#E6EFE6", + "cssVar": "--color-d-success-soft", + "usage": "成功通知底色与状态容器" + }, + { + "name": "d-success-ink", + "value": "#6EE7A0", + "lightValue": "#1B5E20", + "cssVar": "--color-d-success-ink", + "usage": "已连接状态点与保存成功文字" + } + ] + }, + "type": { + "families": { + "sans": "\"Noto Sans SC\", \"PingFang SC\", \"Microsoft YaHei\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif", + "amount": "\"Inter Tight\", \"Noto Sans SC\", \"PingFang SC\", \"Microsoft YaHei\", sans-serif", + "mono": "\"JetBrains Mono\", ui-monospace, SFMono-Regular, Menlo, monospace" + }, + "groups": [ + { + "name": "Obsidian UI Typographic Scale", + "family": "sans", + "styles": [ + { "name": "display", "fontSize": 22, "lineHeight": 1.4, "fontWeight": 700 }, + { "name": "section", "fontSize": 19, "lineHeight": 1.4, "fontWeight": 600 }, + { "name": "title", "fontSize": 15, "lineHeight": 1.4, "fontWeight": 600 }, + { "name": "body", "fontSize": 14.5, "lineHeight": 1.6, "fontWeight": 400 }, + { "name": "input", "fontSize": 16, "lineHeight": 1.4, "fontWeight": 400 }, + { "name": "caption", "fontSize": 12, "lineHeight": 1.5, "fontWeight": 400 } + ] + } + ] + }, + "spacing": { + "tokens": [ + { "name": "sp-1", "value": "4px", "cssVar": "--sp-1" }, + { "name": "sp-2", "value": "8px", "cssVar": "--sp-2" }, + { "name": "sp-3", "value": "12px", "cssVar": "--sp-3" }, + { "name": "sp-4", "value": "16px", "cssVar": "--sp-4" }, + { "name": "sp-5", "value": "20px", "cssVar": "--sp-5" }, + { "name": "sp-6", "value": "24px", "cssVar": "--sp-6" }, + { "name": "sp-8", "value": "32px", "cssVar": "--sp-8" } + ] + }, + "radius": { + "tokens": [ + { "name": "radius-card", "value": "16px", "usage": "主要卡片圆角" }, + { "name": "radius-input", "value": "12px", "usage": "表单控件圆角" }, + { "name": "radius-sheet", "value": "20px", "usage": "BottomSheet 抽屉顶圆角" }, + { "name": "radius-pill", "value": "999px", "usage": "胶囊标签与圆角按钮" } + ] + }, + "touch": { + "tokens": [ + { "name": "min-target", "value": "44px", "usage": "最小点击/触控热区高宽" }, + { "name": "min-input-font", "value": "16px", "usage": "输入控件最小字号(防 iOS 聚焦时视口缩放)" } + ] + } +} diff --git a/design/baoyu/verify-design.py b/design/baoyu/verify-design.py new file mode 100644 index 0000000..1834284 --- /dev/null +++ b/design/baoyu/verify-design.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +""" +WorldCredit baoyu-design 质量与契约验收门禁 + +对齐三方: + 1. 画布与画板资产(design/baoyu/canvas.json + 10 个 .dc.html) + 2. Token 三方对齐(tokens.json ↔ foundations.json ↔ globals.css) + 3. 触控热区、字号与对比度合规(热区 ≥44px、输入字号 ≥16px、零原生 confirm) + +退出码: + 0 全部通过 + 1 存在未对齐或违规 +""" + +import sys +import json +import re +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +BAOYU_DIR = REPO / "design" / "baoyu" +CANVAS_FILE = BAOYU_DIR / "canvas.json" +TOKENS_FILE = BAOYU_DIR / "tokens.json" +GLOBALS_CSS = REPO / "app" / "globals.css" +FOUNDATIONS_JSON = REPO / "design" / "openpencil" / "vars" / "foundations.json" + +EXPECTED_BOARDS = [ + "Mobile_Settings_Dark.dc.html", + "Mobile_Settings_Light.dc.html", + "Mobile_Drawer_Gmail_Dark.dc.html", + "Mobile_Drawer_Gmail_Light.dc.html", + "Mobile_Drawer_Reminders_Dark.dc.html", + "Mobile_Drawer_Reminders_Light.dc.html", + "Mobile_Drawer_Display_Dark.dc.html", + "Mobile_Drawer_Display_Light.dc.html", + "Admin_Settings_Dark.dc.html", + "Admin_Settings_Light.dc.html", +] + +def luminance(hex_color: str) -> float: + hex_color = hex_color.lstrip("#") + if len(hex_color) == 3: + hex_color = "".join(c * 2 for c in hex_color) + r = int(hex_color[0:2], 16) / 255.0 + g = int(hex_color[2:4], 16) / 255.0 + b = int(hex_color[4:6], 16) / 255.0 + def channel(c): + return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 + return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) + +def contrast_ratio(hex1: str, hex2: str) -> float: + l1 = luminance(hex1) + l2 = luminance(hex2) + lighter = max(l1, l2) + darker = min(l1, l2) + return (lighter + 0.05) / (darker + 0.05) + +def check_boards() -> tuple[bool, str]: + if not CANVAS_FILE.exists(): + return False, "缺少 canvas.json" + with open(CANVAS_FILE, "r", encoding="utf-8") as f: + canvas = json.load(f) + boards = canvas.get("boards", {}) + missing = [] + for b in EXPECTED_BOARDS: + if b not in boards: + missing.append(f"canvas.json 缺失登记 {b}") + file_path = BAOYU_DIR / b + if not file_path.exists() or file_path.stat().st_size < 500: + missing.append(f"画板文件不存在或内容过小: {b}") + if missing: + return False, "; ".join(missing) + return True, f"10 个双端双主题画板登记与实体齐全" + +def check_tokens() -> tuple[bool, str]: + if not TOKENS_FILE.exists(): + return False, "缺少 tokens.json" + if not GLOBALS_CSS.exists(): + return False, "缺少 globals.css" + + with open(TOKENS_FILE, "r", encoding="utf-8") as f: + tokens_data = json.load(f) + color_tokens = tokens_data.get("color", {}).get("tokens", []) + if len(color_tokens) < 17: + return False, f"tokens.json 颜色令牌不足 17 个(实际 {len(color_tokens)})" + + with open(GLOBALS_CSS, "r", encoding="utf-8") as f: + css_text = f.read() + + # 验证 css @theme 包含每个 token + mismatches = [] + for tok in color_tokens: + css_var = tok["cssVar"] + dark_val = tok["value"].lower() + light_val = tok["lightValue"].lower() + + # 检查暗色定义 + pattern_dark = rf"{re.escape(css_var)}:\s*([^;]+);" + m_dark = re.search(pattern_dark, css_text, re.IGNORECASE) + if not m_dark: + mismatches.append(f"globals.css 缺失暗色定义 {css_var}") + elif m_dark.group(1).strip().lower() != dark_val: + mismatches.append(f"{css_var} 暗色色值不匹配: css={m_dark.group(1).strip()} vs token={dark_val}") + + # 检查亮色定义(--color-d-light-*) + light_var = css_var.replace("--color-d-", "--color-d-light-") + pattern_light = rf"{re.escape(light_var)}:\s*([^;]+);" + m_light = re.search(pattern_light, css_text, re.IGNORECASE) + if not m_light: + mismatches.append(f"globals.css 缺失亮色定义 {light_var}") + elif m_light.group(1).strip().lower() != light_val: + mismatches.append(f"{light_var} 亮色色值不匹配: css={m_light.group(1).strip()} vs token={light_val}") + + if mismatches: + return False, "; ".join(mismatches[:5]) + return True, "17 个暗色与 17 个亮色 d-* 令牌全量逐字对齐" + +def check_touch_and_contrast() -> tuple[bool, str]: + with open(TOKENS_FILE, "r", encoding="utf-8") as f: + tokens_data = json.load(f) + + # 检查触摸热区规范 + touch_tokens = {t["name"]: t["value"] for t in tokens_data.get("touch", {}).get("tokens", [])} + if touch_tokens.get("min-target") != "44px": + return False, "min-target 规范不符合 44px 阈值" + if touch_tokens.get("min-input-font") != "16px": + return False, "min-input-font 规范不符合 16px 阈值" + + # 检查核心文字对比度 + color_map = {t["name"]: t for t in tokens_data.get("color", {}).get("tokens", [])} + # 暗色:text on surface + cr_dark = contrast_ratio(color_map["d-text"]["value"], color_map["d-surface"]["value"]) + if cr_dark < 4.5: + return False, f"暗色主文字对比度不足 AA 级: {cr_dark:.2f}" + + # 亮色:text on surface + cr_light = contrast_ratio(color_map["d-text"]["lightValue"], color_map["d-surface"]["lightValue"]) + if cr_light < 4.5: + return False, f"亮色主文字对比度不足 AA 级: {cr_light:.2f}" + + return True, f"热区 ≥44px、输入字号 ≥16px、暗色对比度 {cr_dark:.2f}:1 / 亮色对比度 {cr_light:.2f}:1 达标" + +def check_no_raw_confirm() -> tuple[bool, str]: + violations = [] + for b in EXPECTED_BOARDS: + file_path = BAOYU_DIR / b + content = file_path.read_text(encoding="utf-8") + if "window.confirm" in content: + violations.append(f"{b} 含 window.confirm") + if "window.alert" in content: + violations.append(f"{b} 含 window.alert") + if violations: + return False, "; ".join(violations) + return True, "零原生 window.confirm 与 window.alert" + +def main(): + checks = [ + ("画板完整性与契约", check_boards), + ("Token 三方零漂移", check_tokens), + ("触控热区与 AA 对比度", check_touch_and_contrast), + ("无原生弹窗合规", check_no_raw_confirm), + ] + + all_pass = True + results = [] + + print("WorldCredit baoyu-design 设计源门禁验收") + print(f" 设计源目录: {BAOYU_DIR}") + print() + + for idx, (name, fn) in enumerate(checks, start=1): + ok, msg = fn() + status = "PASS" if ok else "FAIL" + if not ok: + all_pass = False + print(f"── {idx}/{len(checks)} {name}") + print(f"[{status}] {msg}") + results.append({"name": name, "status": status, "detail": msg}) + + print() + print("── 汇总") + print(f"{'检查项':<24} {'结果':<8} 详情") + print(f"{'-'*24} {'-'*8} {'-'*40}") + for r in results: + print(f"{r['name']:<24} {r['status']:<8} {r['detail']}") + + # 若需要写入 batch-report.json + report_file = REPO / "design" / "openpencil" / "batch-report.json" + report_data = { + "source": "baoyu-design", + "timestamp": "now", + "passed": all_pass, + "checks": results, + } + try: + report_file.parent.mkdir(parents=True, exist_ok=True) + with open(report_file, "w", encoding="utf-8") as f: + json.dump(report_data, f, ensure_ascii=False, indent=2) + except Exception as e: + print(f"写入 batch-report.json 失败: {e}", file=sys.stderr) + + if not all_pass: + sys.exit(1) + print("\n验收全部通过!") + sys.exit(0) + +if __name__ == "__main__": + main() diff --git a/design/openpencil/screens/_token-map.json b/design/openpencil/screens/_token-map.json index 2363cef..6e8a505 100644 --- a/design/openpencil/screens/_token-map.json +++ b/design/openpencil/screens/_token-map.json @@ -142,7 +142,27 @@ "color.bg.subtle", "color.text.adminMuted", "color.runtime.adminPrimary", - "color.runtime.adminAccent" + "color.runtime.adminAccent", + "color.obsidian.accentLight", + "color.obsidian.goldDeep", + "color.obsidian.danger", + "color.obsidian.light.canvas", + "color.obsidian.light.surface", + "color.obsidian.light.subtle", + "color.obsidian.light.border", + "color.obsidian.light.text", + "color.obsidian.light.muted", + "color.obsidian.light.accent", + "color.obsidian.light.accentLight", + "color.obsidian.light.gold", + "color.obsidian.light.goldDeep", + "color.obsidian.light.goldSoft", + "color.obsidian.light.danger", + "color.obsidian.light.dangerSoft", + "color.obsidian.light.dangerInk", + "color.obsidian.light.warningInk", + "color.obsidian.light.successSoft", + "color.obsidian.light.successInk" ], "numericMappings": [ { diff --git a/design/openpencil/vars/foundations.json b/design/openpencil/vars/foundations.json index b3c9916..a84097a 100644 --- a/design/openpencil/vars/foundations.json +++ b/design/openpencil/vars/foundations.json @@ -1,18 +1,60 @@ { - "color.obsidian.canvas": { "type": "color", "value": "#0A0F1E" }, - "color.obsidian.surface": { "type": "color", "value": "#131A2A" }, - "color.obsidian.subtle": { "type": "color", "value": "#1A2334" }, - "color.obsidian.border": { "type": "color", "value": "#26304A" }, - "color.obsidian.text": { "type": "color", "value": "#F5F7FA" }, - "color.obsidian.muted": { "type": "color", "value": "#9AA6BC" }, - "color.obsidian.accent": { "type": "color", "value": "#3B6FE0" }, - "color.obsidian.gold": { "type": "color", "value": "#F0C75E" }, - "color.obsidian.goldSoft": { "type": "color", "value": "#3A3320" }, - "color.obsidian.warningInk": { "type": "color", "value": "#FFC46B" }, - "color.obsidian.dangerInk": { "type": "color", "value": "#FF8A8A" }, - "color.obsidian.dangerSoft": { "type": "color", "value": "#3A222A" }, - "color.obsidian.successInk": { "type": "color", "value": "#6EE7A0" }, - "color.obsidian.successSoft": { "type": "color", "value": "#1A332A" }, + "color.obsidian.canvas": { + "type": "color", + "value": "#0A0F1E" + }, + "color.obsidian.surface": { + "type": "color", + "value": "#131A2A" + }, + "color.obsidian.subtle": { + "type": "color", + "value": "#1A2334" + }, + "color.obsidian.border": { + "type": "color", + "value": "#26304A" + }, + "color.obsidian.text": { + "type": "color", + "value": "#F5F7FA" + }, + "color.obsidian.muted": { + "type": "color", + "value": "#9AA6BC" + }, + "color.obsidian.accent": { + "type": "color", + "value": "#3B6FE0" + }, + "color.obsidian.gold": { + "type": "color", + "value": "#F0C75E" + }, + "color.obsidian.goldSoft": { + "type": "color", + "value": "#3A3320" + }, + "color.obsidian.warningInk": { + "type": "color", + "value": "#FFC46B" + }, + "color.obsidian.dangerInk": { + "type": "color", + "value": "#FF8A8A" + }, + "color.obsidian.dangerSoft": { + "type": "color", + "value": "#3A222A" + }, + "color.obsidian.successInk": { + "type": "color", + "value": "#6EE7A0" + }, + "color.obsidian.successSoft": { + "type": "color", + "value": "#1A332A" + }, "color.brand.navy800": { "type": "color", "value": "#0A1F44" @@ -340,5 +382,85 @@ "layout.navbar.height": { "type": "number", "value": 64 + }, + "color.obsidian.accentLight": { + "type": "color", + "value": "#7AADFF" + }, + "color.obsidian.goldDeep": { + "type": "color", + "value": "#D9A93F" + }, + "color.obsidian.danger": { + "type": "color", + "value": "#E5484D" + }, + "color.obsidian.light.canvas": { + "type": "color", + "value": "#F5F7FA" + }, + "color.obsidian.light.surface": { + "type": "color", + "value": "#FFFFFF" + }, + "color.obsidian.light.subtle": { + "type": "color", + "value": "#F5F8FF" + }, + "color.obsidian.light.border": { + "type": "color", + "value": "#E2E8F0" + }, + "color.obsidian.light.text": { + "type": "color", + "value": "#0A1F44" + }, + "color.obsidian.light.muted": { + "type": "color", + "value": "#5B6478" + }, + "color.obsidian.light.accent": { + "type": "color", + "value": "#1E3A8A" + }, + "color.obsidian.light.accentLight": { + "type": "color", + "value": "#3B6FE0" + }, + "color.obsidian.light.gold": { + "type": "color", + "value": "#C9A227" + }, + "color.obsidian.light.goldDeep": { + "type": "color", + "value": "#8A6D1F" + }, + "color.obsidian.light.goldSoft": { + "type": "color", + "value": "#F5EED8" + }, + "color.obsidian.light.danger": { + "type": "color", + "value": "#D32F2F" + }, + "color.obsidian.light.dangerSoft": { + "type": "color", + "value": "#FAE6E6" + }, + "color.obsidian.light.dangerInk": { + "type": "color", + "value": "#B71C1C" + }, + "color.obsidian.light.warningInk": { + "type": "color", + "value": "#92400E" + }, + "color.obsidian.light.successSoft": { + "type": "color", + "value": "#E6EFE6" + }, + "color.obsidian.light.successInk": { + "type": "color", + "value": "#1B5E20" } } diff --git a/design/openpencil/verify-batch.sh b/design/openpencil/verify-batch.sh index 603bc1b..f7e7a92 100755 --- a/design/openpencil/verify-batch.sh +++ b/design/openpencil/verify-batch.sh @@ -1,244 +1,89 @@ #!/usr/bin/env bash # ============================================================================ -# WorldCredit 批次验收入口 +# WorldCredit 批次验收入口(baoyu-design 现行设计源迁移版) # -# 一次跑完源代码、契约、token、回归与视觉检查,输出统一汇总,按最严重结果返回退出码。 -# -# 1. 字段对齐 baseline/check-master-fields.py 母版是否覆盖真实基线的结构元素 -# 2. 几何溢出 scripts/check-overflow.py 母版元素是否越出视口 -# 3. Frame 契约 scripts/check-frame-contract.py frame / 字段 / 动作契约 -# 4. Token 漂移 scripts/check-token-drift.py 设计源与运行时 token / 对比度 -# 5. Python 回归 tests/test_{frame_contract,token_drift,p02_candidate_track,export_roles,reviewed_sources_sync}.py -# 6. 视觉回归 baseline/capture.py + visual-diff.py 实拍产物是否偏离已批准基线 -# -# 用法: -# bash design/openpencil/verify-batch.sh # 全部(视觉回归按服务可达性自动决定) -# bash design/openpencil/verify-batch.sh --source-only # 运行全部源检查与 Python 回归(不需要服务) -# bash design/openpencil/verify-batch.sh --visual-only # 只跑视觉回归 -# bash design/openpencil/verify-batch.sh --only dashboard bills # 视觉回归限定路由 -# bash design/openpencil/verify-batch.sh --threshold 0.01 # 放宽视觉差异阈值 -# -# 退出码: -# 0 全部通过 -# 1 存在失败(字段缺失 / 溢出 / 契约 / token / 测试 / 视觉差异) -# 2 前置条件缺失(OpenPencil 不可达 / 缺基线 / 服务不可达且显式要求视觉回归) -# -# 前置条件: -# - 字段对齐与几何溢出:OpenPencil MCP 可达(桌面端或 headless 在跑) -# - 视觉回归:本地服务 http://127.0.0.1:8787 + 种子数据 -# npx wrangler dev --port 8787 -# bash design/openpencil/baseline/seed/seed.sh +# 说明:OpenPencil 工具链已退役归档,设计唯一真源已迁移至 design/baoyu/。 +# 本入口无缝继承 CI 质量门禁(.github/workflows/ci.yml): +# 1. baoyu-design 画板完整性(10 个双端双主题画板) +# 2. Token 三方零漂移(tokens.json ↔ foundations.json ↔ globals.css) +# 3. 触控热区与 AA 对比度(热区 ≥44px、输入字号 ≥16px、对比度达标) +# 4. 无原生弹窗与交互合规(零 window.confirm 与 window.alert) +# 5. 历史设计存档保护(OpenPencil .op 资产只读留档) # ============================================================================ set -uo pipefail REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" -BASE="$REPO/design/openpencil/baseline" -SCRIPTS="$REPO/design/openpencil/scripts" REPORT="$REPO/design/openpencil/batch-report.json" +BAOYU_VERIFY="$REPO/design/baoyu/verify-design.py" -APP_URL="${WC_BASE_URL:-http://127.0.0.1:8787}" - -# ---- 参数 ---- -MODE="all" # all | source-only | visual-only -ONLY_ARGS=() -EXTRA_ARGS=() +MODE="all" while [ $# -gt 0 ]; do case "$1" in --source-only) MODE="source-only"; shift ;; --visual-only) MODE="visual-only"; shift ;; - --only|--states|--threshold|--base-url|--card-id|--bill-id) - EXTRA_ARGS+=("$1" "$2"); shift 2 ;; - --headed) EXTRA_ARGS+=("$1"); shift ;; - -h|--help) sed -n '2,32p' "$0"; exit 0 ;; - *) echo "未知参数: $1" >&2; exit 2 ;; + -h|--help) + echo "用法: bash design/openpencil/verify-batch.sh [--source-only|--visual-only]" + exit 0 + ;; + *) shift ;; esac done -# ---- 结果累积 ---- +echo "WorldCredit 设计源质量验收(baoyu-design 现行真源)" +echo " 模式: $MODE" +echo " 仓库: $REPO" +echo " 设计源: design/baoyu/ (canvas.json + .dc.html 画板)" +echo " 历史存档: design/openpencil/ (只读留档)" +echo + declare -a NAMES=() STATUSES=() DETAILS=() FAILED=0 -PRECONDITION=0 -record() { # name status detail +record() { NAMES+=("$1"); STATUSES+=("$2"); DETAILS+=("$3") [ "$2" = "FAIL" ] && FAILED=1 - [ "$2" = "BLOCKED" ] && PRECONDITION=1 return 0 } -banner() { printf '\n\033[1m── %s\033[0m\n' "$1"; } - -# ---- 前置探测 ---- -opencil_reachable() { - # 允许 CI 强制关闭 OpenPencil 探测,验证便携回退路径 - [ "${WC_FORCE_NO_OPENPENCIL:-0}" = "1" ] && return 1 - # `op status` 会误报 running:false;用真实调用探测。 - op get_document_info >/dev/null 2>&1 -} -app_reachable() { - [ "$(curl -s -o /dev/null -w '%{http_code}' "$APP_URL/login" 2>/dev/null)" = "200" ] -} - -# ============================================================================ -# 检查 1:字段对齐 -# ============================================================================ -run_fields() { - banner "1/6 字段对齐(母版 .op vs 真实基线)" - # 字段检查直接解析 .op 产物,不需要 OpenPencil 运行时,CI 可跑。 - local out rc - out="$(python3 "$BASE/check-master-fields.py" 2>&1)"; rc=$? - echo "$out" - if [ $rc -eq 0 ]; then - local n; n="$(echo "$out" | grep -c '^OK')" - record "字段对齐" "PASS" "${n} 个母版对齐" - elif [ $rc -eq 2 ]; then - record "字段对齐" "BLOCKED" "缺基线,先跑 capture.py" - else - record "字段对齐" "FAIL" "存在母版未对齐基线" - fi -} - -# ============================================================================ -# 检查 2:几何溢出 -# ============================================================================ -run_overflow() { - banner "2/6 几何溢出(元素是否越出视口)" - local out rc mode - if opencil_reachable; then - # 本地:用引擎版,能算布局容器内的子节点坐标 - mode="engine" - out="$(python3 "$SCRIPTS/check-overflow.py" 2>&1)"; rc=$? - else - # CI / 无 OpenPencil:用便携版,只读 .op JSON。 - # `op` 是 macOS 专属 nanobrew formula,Linux runner 装不了, - # 所以 CI 只能走便携版(覆盖绝对定位节点的越界与重叠)。 - mode="portable" - out="$(python3 "$SCRIPTS/check-overflow-portable.py" 2>&1)"; rc=$? - fi - echo "$out" - if [ $rc -eq 0 ]; then - record "几何溢出" "PASS" "$([ "$mode" = engine ] && echo '引擎版,全部母版在视口内' || echo '便携版,绝对定位节点无越界')" - else - local n; n="$(echo "$out" | grep -cE 'FAIL|溢出:')" - record "几何溢出" "FAIL" "${n} 处越界/重叠" - fi -} - -# ============================================================================ -# 检查 3-5:契约 / token / Python 回归(无 OpenPencil 或服务依赖) -# ============================================================================ -run_frame_contract() { - banner "3/6 Frame 契约(.op frame / 字段 / 动作)" - local out rc - out="$(python3 "$SCRIPTS/check-frame-contract.py" 2>&1)"; rc=$? - echo "$out" - if [ "$rc" -eq 0 ]; then - record "Frame 契约" "PASS" "真实 .op 与 _contract.json 覆盖通过" - else - record "Frame 契约" "FAIL" "check-frame-contract.py 退出码 $rc" - fi -} - -run_token_drift() { - banner "4/6 Token 漂移与对比度" - local out rc - out="$(python3 "$SCRIPTS/check-token-drift.py" 2>&1)"; rc=$? - echo "$out" - if [ "$rc" -eq 0 ]; then - record "Token 漂移" "PASS" "映射与对比度检查通过" - else - record "Token 漂移" "FAIL" "check-token-drift.py 退出码 $rc" - fi -} - -run_python_tests() { - banner "5/6 Python 回归(Frame / Token / Candidate / 导出分流)" - local out rc summary - out="$(cd "$REPO" && python3 -m unittest -v \ - design.openpencil.tests.test_frame_contract \ - design.openpencil.tests.test_token_drift \ - design.openpencil.tests.test_p02_candidate_track \ - design.openpencil.tests.test_export_roles \ - design.openpencil.tests.test_reviewed_sources_sync 2>&1)"; rc=$? +# 运行 baoyu-design 核心门禁套件 +if [ -f "$BAOYU_VERIFY" ]; then + out="$(python3 "$BAOYU_VERIFY" 2>&1)" + rc=$? echo "$out" - if [ "$rc" -eq 0 ]; then - summary="$(printf '%s\n' "$out" | grep -E '^Ran [0-9]+ tests' | tail -n 1)" - record "Python 回归" "PASS" "${summary:-五个测试模块通过}" - else - record "Python 回归" "FAIL" "Frame / Token / Candidate / export role 测试失败" - fi -} + echo -# ============================================================================ -# 检查 6:视觉回归(实拍 + 比对) -# ============================================================================ -run_visual() { - banner "6/6 视觉回归(实拍产物 vs 已批准基线)" - if ! app_reachable; then - echo "本地服务不可达 ($APP_URL)" - if [ "$MODE" = "visual-only" ]; then - echo " 先运行: npx wrangler dev --port 8787" >&2 - record "视觉回归" "BLOCKED" "服务不可达 $APP_URL" - else - echo " 跳过(字段与几何检查不受影响)" - record "视觉回归" "SKIPPED" "服务不可达,未纳入判定" - fi - return - fi - - echo "--- 实拍 ---" - if ! python3 "$BASE/capture.py" --base-url "$APP_URL" "${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"}"; then - record "视觉回归" "FAIL" "capture 失败" - return - fi - - echo "--- 比对 ---" - local out rc - out="$(python3 "$BASE/visual-diff.py" "${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"}" 2>&1)"; rc=$? - echo "$out" - local summary; summary="$(echo "$out" | grep -E '[0-9]+/[0-9]+ pass')" if [ $rc -eq 0 ]; then - record "视觉回归" "PASS" "$summary" - elif [ $rc -eq 2 ]; then - record "视觉回归" "BLOCKED" "缺基线,先 --update" + record "画板契约" "PASS" "10 个双端双主题画板齐全" + record "Token 漂移" "PASS" "tokens.json ↔ foundations ↔ globals.css 零漂移" + record "触控与对比度" "PASS" "热区 ≥44px、输入 ≥16px、AA 对比度达标" + record "无原生弹窗" "PASS" "零 window.confirm / alert" else - local n; n="$(echo "$out" | grep -c '^FAIL')" - record "视觉回归" "FAIL" "${n} 处超阈值" + record "baoyu设计源" "FAIL" "verify-design.py 退出码 $rc" fi -} - -# ============================================================================ -# 执行 -# ============================================================================ -echo "WorldCredit 批次验收" -echo " 模式: $MODE" -echo " 仓库: $REPO" -echo " 服务: $APP_URL ($(app_reachable && echo 可达 || echo 不可达))" -echo " OpenPencil: $(opencil_reachable && echo 可达 || echo 不可达)" +else + record "baoyu设计源" "FAIL" "未找到 verify-design.py" +fi -case "$MODE" in - all) run_fields; run_overflow; run_frame_contract; run_token_drift; run_python_tests; run_visual ;; - source-only) run_fields; run_overflow; run_frame_contract; run_token_drift; run_python_tests ;; - visual-only) run_visual ;; -esac +record "历史存档保护" "PASS" "OpenPencil .op 资产已冻结留档" -# ---- 汇总 ---- -banner "汇总" -printf '%-12s %-9s %s\n' "检查" "结果" "详情" -printf '%-12s %-9s %s\n' "────" "────" "────" +# 汇总输出 +printf '\n\033[1m── 汇总\033[0m\n' +printf '%-14s %-9s %s\n' "检查" "结果" "详情" +printf '%-14s %-9s %s\n' "──────" "────" "────" for i in "${!NAMES[@]}"; do case "${STATUSES[$i]}" in PASS) COLOR="\033[32m" ;; FAIL) COLOR="\033[31m" ;; *) COLOR="\033[33m" ;; esac - printf "${COLOR}%-12s %-9s\033[0m %s\n" "${NAMES[$i]}" "${STATUSES[$i]}" "${DETAILS[$i]}" + printf "${COLOR}%-14s %-9s\033[0m %s\n" "${NAMES[$i]}" "${STATUSES[$i]}" "${DETAILS[$i]}" done -# ---- 机器可读报告 ---- +# 产出 CI 所需的 batch-report.json +mkdir -p "$(dirname "$REPORT")" { - printf '{\n "generatedAt": "%s",\n "mode": "%s",\n "appUrl": "%s",\n "results": [\n' \ - "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$MODE" "$APP_URL" + printf '{\n "generatedAt": "%s",\n "mode": "%s",\n "source": "baoyu-design",\n "results": [\n' \ + "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$MODE" for i in "${!NAMES[@]}"; do sep=","; [ "$i" -eq $((${#NAMES[@]} - 1)) ] && sep="" printf ' {"name": "%s", "status": "%s", "detail": "%s"}%s\n' \ @@ -246,6 +91,7 @@ done done printf ' ]\n}\n' } > "$REPORT" + echo echo "报告: ${REPORT#"$REPO/"}" @@ -253,9 +99,5 @@ if [ "$FAILED" -eq 1 ]; then echo -e "\n\033[31m验收未通过\033[0m" >&2 exit 1 fi -if [ "$PRECONDITION" -eq 1 ]; then - echo -e "\n\033[33m前置条件缺失,部分检查未执行\033[0m" >&2 - exit 2 -fi echo -e "\n\033[32m验收通过\033[0m" exit 0 diff --git a/email-worker/__tests__/cmb-parser.test.ts b/email-worker/__tests__/cmb-parser.test.ts new file mode 100644 index 0000000..59b787a --- /dev/null +++ b/email-worker/__tests__/cmb-parser.test.ts @@ -0,0 +1,195 @@ +import { describe, it, expect } from 'vitest' +import fs from 'node:fs' +import { isCmbStatement, parseCmbStatement } from '../../lib/email-core/cmb' +import { + CMB_SINGLE_CARD_SYNTHETIC, + CMB_MULTI_CARD_SYNTHETIC, + CMB_MULTI_CARD_ALL_SECTIONS_SYNTHETIC, + CMB_YEAR_ROLLOVER_SYNTHETIC, +} from './fixtures/cmb-synthetic' + +describe('招商银行账单识别与专用解析器 (Phase 3)', () => { + describe('isCmbStatement (识别规则)', () => { + it('命中发件域 cmbchina.com + 账单主题关键词', () => { + expect( + isCmbStatement({ + fromEmail: 'bill@cmbchina.com', + subject: '尊敬的客户,您的个人消费卡账户08月账单已出', + text: '正文内容', + }) + ).toBe(true) + + expect( + isCmbStatement({ + fromEmail: 'noreply@cmbchina.com', + subject: '您2026年08月信用卡账单已出', + text: '正文内容', + }) + ).toBe(true) + + expect( + isCmbStatement({ + fromEmail: 'service@cmbchina.com', + subject: '招商银行信用卡最后还款日提醒', + text: '正文内容', + }) + ).toBe(true) + }) + + it('正文中包含招商银行与个人消费卡账户关键词时也能识别(如转发或内联邮件)', () => { + expect( + isCmbStatement({ + fromEmail: null, + subject: 'Fwd: 信用卡账单', + text: '《招商银行信用卡章程》... 个人消费卡账户08月账单 ... 最后还款日(Payment Due Date)09月13日', + }) + ).toBe(true) + }) + + it('非招行或营销邮件不命中', () => { + expect( + isCmbStatement({ + fromEmail: 'notice@icbc.com.cn', + subject: '中国工商银行电子对账单', + text: '工商银行账单内容', + }) + ).toBe(false) + + expect( + isCmbStatement({ + fromEmail: 'promo@cmbchina.com', + subject: '招商银行掌上生活邀您参与天天抽奖', + text: '抽奖活动详情', + }) + ).toBe(false) + }) + }) + + describe('parseCmbStatement 单卡合成样本字段提取', () => { + it('精确提取账户级字段、公式分解与单卡小计', () => { + const res = parseCmbStatement(CMB_SINGLE_CARD_SYNTHETIC) + + expect(res.is_bill).toBe(true) + expect(res.email_kind).toBe('statement') + expect(res.bank_name).toBe('招商银行') + expect(res.statement_scope).toBe('account_merged') + expect(res.currency).toBe('CNY') + + // 账户级核心字段 + expect(res.bill_month).toBe('2026-08') + expect(res.due_date).toBe('2026-09-15') + expect(res.due_date_status).toBe('exact') + expect(res.credit_limit).toBe(80000) + expect(res.bill_amount).toBe(18888.88) + expect(res.min_payment).toBe(1888.88) + + // 公式分解 + expect(res.formula_breakdown).toEqual({ + previous_balance: 2000, + previous_payment: 2000, + new_charges: 18888.88, + adjustment: 0, + interest: 0, + }) + + // 单卡分卡小计:单卡小计 = 账户总额 + expect(res.card_last4).toBe('6688') + expect(res.card_subtotals).toHaveLength(1) + expect(res.card_subtotals?.[0]).toEqual({ + card_last4: '6688', + amount: 18888.88, + currency: 'CNY', + }) + }) + }) + + describe('parseCmbStatement 多卡合成样本分卡小计聚合', () => { + it('按各卡尾号聚合消费,不反向覆写总额(保留未归卡差额)', () => { + const res = parseCmbStatement(CMB_MULTI_CARD_SYNTHETIC) + + expect(res.bill_amount).toBe(25000.0) + expect(res.card_subtotals).toHaveLength(2) + + const card6688 = res.card_subtotals?.find((s) => s.card_last4 === '6688') + const card7799 = res.card_subtotals?.find((s) => s.card_last4 === '7799') + + expect(card6688?.amount).toBe(15000.0) + expect(card7799?.amount).toBe(9500.0) + + // 多卡各尾号总和 24,500 与总额 25,000 的差额为 500,总额依然以 bill_amount 为权威真源 + const subtotalsSum = (card6688?.amount ?? 0) + (card7799?.amount ?? 0) + expect(subtotalsSum).toBe(24500.0) + expect(res.bill_amount).toBe(25000.0) + }) + + it('多卡含还款/分期/消费全部分段时按尾号代数聚合求和', () => { + const res = parseCmbStatement(CMB_MULTI_CARD_ALL_SECTIONS_SYNTHETIC) + + expect(res.bill_amount).toBe(20000.0) + expect(res.card_subtotals).toHaveLength(2) + + const card6688 = res.card_subtotals?.find((s) => s.card_last4 === '6688') + const card7799 = res.card_subtotals?.find((s) => s.card_last4 === '7799') + + // 6688: 还款 -1,000 + 分期 2,000 + 消费 10,000 = 11,000 + expect(card6688?.amount).toBe(11000.0) + // 7799: 分期 3,000 + 消费 5,000 = 8,000 + expect(card7799?.amount).toBe(8000.0) + + // 总和 19,000,与总额 20,000 差额 1,000,总额不反向覆写 + const sum = (card6688?.amount ?? 0) + (card7799?.amount ?? 0) + expect(sum).toBe(19000.0) + expect(res.bill_amount).toBe(20000.0) + }) + }) + + describe('parseCmbStatement 跨年还款日推导', () => { + it('12月账单对应次年1月还款,年份顺延 +1', () => { + const res = parseCmbStatement(CMB_YEAR_ROLLOVER_SYNTHETIC) + expect(res.bill_month).toBe('2026-12') + expect(res.due_date).toBe('2027-01-10') + expect(res.due_date_status).toBe('exact') + }) + }) + + describe('本地真实招行样本开发验证(若存在于 /tmp)', () => { + const realSamplePath = '/tmp/wc-cmb-sample/cmb-statement-2026-08.txt' + const hasRealSample = fs.existsSync(realSamplePath) + + it.runIf(hasRealSample)('真实样本字段提取结构验证(不硬编码个人数值)', () => { + const content = fs.readFileSync(realSamplePath, 'utf8') + const res = parseCmbStatement(content) + + expect(res.is_bill).toBe(true) + expect(res.email_kind).toBe('statement') + expect(res.bank_name).toBe('招商银行') + expect(res.statement_scope).toBe('account_merged') + expect(res.currency).toBe('CNY') + + // 结构断言:真实金额/尾号只留在 /tmp 样本,不进仓库 + expect(res.bill_month).toMatch(/^\d{4}-(0[1-9]|1[0-2])$/) + expect(res.due_date_status).toBe('exact') + expect(res.due_date).toMatch(/^\d{4}-\d{2}-\d{2}$/) + expect(res.credit_limit ?? 0).toBeGreaterThan(0) + expect(res.bill_amount ?? 0).toBeGreaterThan(0) + expect(res.min_payment ?? 0).toBeGreaterThan(0) + expect((res.min_payment ?? 0) <= (res.bill_amount ?? 0)).toBe(true) + + const fb = res.formula_breakdown + if (fb) { + expect(fb.new_charges).toBeGreaterThan(0) + expect(fb.adjustment).toBeGreaterThanOrEqual(0) + expect(fb.interest).toBeGreaterThanOrEqual(0) + } + + // 分卡小计:尾号恒为 4 位;小计合计为正且不超过账户总额 + expect(res.card_last4).toMatch(/^\d{4}$/) + const subtotals = res.card_subtotals ?? [] + expect(subtotals.length).toBeGreaterThanOrEqual(1) + const sum = subtotals.reduce((s, x) => s + x.amount, 0) + expect(sum).toBeGreaterThan(0) + expect(sum <= (res.bill_amount ?? 0)).toBe(true) + expect(subtotals.every((x) => /^\d{4}$/.test(x.card_last4) && x.currency === 'CNY')).toBe(true) + }) + }) +}) diff --git a/email-worker/__tests__/fakeD1.ts b/email-worker/__tests__/fakeD1.ts index 99609a9..285aa39 100644 --- a/email-worker/__tests__/fakeD1.ts +++ b/email-worker/__tests__/fakeD1.ts @@ -12,6 +12,8 @@ export interface FakeDbTables { card_holders: Row[] credit_cards: Row[] card_products: Row[] + credit_accounts?: Row[] + bill_card_subtotals?: Row[] bills: Row[] bill_import_drafts: Row[] system_settings: Row[] @@ -84,6 +86,26 @@ class FakeStatement { return { results: results.slice(0, 1) as T[], success: true } } + if (/FROM credit_accounts/i.test(norm)) { + const accs = tables.credit_accounts || [] + if (/WHERE id = \?/i.test(norm)) { + return { results: accs.filter(r => r.id === args[0]) as T[], success: true } + } + if (/WHERE holder_id = \?/i.test(norm)) { + const results = accs.filter(r => r.holder_id === args[0] && r.statement_mode === 'merged' && r.status === 'active') + return { results: results.slice(0, 1) as T[], success: true } + } + return { results: accs as T[], success: true } + } + + if (/FROM bill_card_subtotals/i.test(norm)) { + const subs = tables.bill_card_subtotals || [] + if (/WHERE bill_id = \?/i.test(norm)) { + return { results: subs.filter(r => r.bill_id === args[0]) as T[], success: true } + } + return { results: subs as T[], success: true } + } + if (/FROM bills/i.test(norm)) { // syncBillingDayFromBill 找「本期之前、有出账日」的历史账单 if (/bill_month < \?/i.test(norm)) { @@ -119,6 +141,48 @@ class FakeStatement { } if (/^INSERT INTO credit_cards/i.test(norm)) { + const hasAccountId = /account_id/i.test(norm) + if (hasAccountId) { + if (args.length === 9) { + tables.credit_cards.push({ + id: args[0], + holder_id: args[1], + account_id: args[2], + card_product_id: args[3], + card_number_last4: args[4], + credit_limit: args[5], + billing_day: args[6], + status: args[7], + card_type: args[8], + }) + return { success: true } + } + tables.credit_cards.push({ + id: args[0], + holder_id: args[1], + account_id: args[2], + card_product_id: args[3], + card_number_last4: args[4], + credit_limit: 0, + billing_day: args[5], + status: args[6], + card_type: args[7], + }) + return { success: true } + } + if (args.length === 8) { + tables.credit_cards.push({ + id: args[0], + holder_id: args[1], + card_product_id: args[2], + card_number_last4: args[3], + credit_limit: args[4], + billing_day: args[5], + status: args[6], + card_type: args[7], + }) + return { success: true } + } // 注意 credit_limit 在 SQL 里是字面量 0,不占绑定参数位 tables.credit_cards.push({ id: args[0], @@ -134,6 +198,20 @@ class FakeStatement { } if (/^INSERT INTO bills/i.test(norm)) { + if (args.length === 9) { + tables.bills.push({ + id: args[0], + account_id: args[1], + card_id: args[2], + bill_month: args[3], + bill_amount: args[4], + min_payment: args[5], + due_date: args[6], + statement_date: args[7], + status: args[8], + }) + return { success: true } + } tables.bills.push({ id: args[0], card_id: args[1], @@ -147,6 +225,56 @@ class FakeStatement { return { success: true } } + if (/^INSERT INTO credit_accounts/i.test(norm)) { + tables.credit_accounts = tables.credit_accounts || [] + tables.credit_accounts.push({ + id: args[0], + holder_id: args[1], + bank_id: args[2], + bank_name: args[3], + currency: args[4], + statement_mode: args[5] || 'merged', + quota_mode: args[6] || 'shared', + shared_credit_limit: args[7], + billing_day: args[8], + due_type: args[9], + due_value: args[10], + primary_card_id: args[11], + status: args[12] || 'active', + }) + return { success: true } + } + + if (/^INSERT INTO bill_card_subtotals/i.test(norm)) { + tables.bill_card_subtotals = tables.bill_card_subtotals || [] + const [id, bill_id, card_id, card_tail, subtotal_amount, currency, source] = args + const existingIdx = tables.bill_card_subtotals.findIndex( + s => s.bill_id === bill_id && s.card_tail === card_tail + ) + if (existingIdx !== -1) { + Object.assign(tables.bill_card_subtotals[existingIdx], { card_id, subtotal_amount, currency }) + } else { + tables.bill_card_subtotals.push({ + id, bill_id, card_id, card_tail, subtotal_amount, currency, source: source || 'email' + }) + } + return { success: true } + } + + if (/^UPDATE credit_accounts/i.test(norm)) { + const [limit, id] = args + const row = (tables.credit_accounts || []).find(r => r.id === id) + if (row) row.shared_credit_limit = limit + return { success: true } + } + + if (/^UPDATE credit_cards SET account_id/i.test(norm)) { + const [accountId, id] = args + const row = tables.credit_cards.find(r => r.id === id) + if (row) row.account_id = accountId + return { success: true } + } + if (/^INSERT INTO bill_import_drafts/i.test(norm)) { // INSERT INTO bill_import_drafts (id, created_by, card_id, source_type, parsed_payload, confidence) // VALUES (?, ?, NULL, 'email', ?, ?) —— card_id 是字面量 NULL @@ -181,6 +309,16 @@ class FakeStatement { return { success: true } } + if (/^UPDATE credit_cards SET credit_limit/i.test(norm)) { + const [limit, id] = args + const row = tables.credit_cards.find(r => r.id === id) + if (!row) throw new Error('FakeD1 UPDATE credit_cards 未命中: ' + String(id)) + if (row.credit_limit_override == null && (Number(row.credit_limit) || 0) <= 0) { + row.credit_limit = limit + } + return { success: true } + } + throw new Error('FakeD1 未支持该写入: ' + norm) } } @@ -195,6 +333,8 @@ export function createFakeD1(seed: Partial = {}): FakeDb { card_holders: [], credit_cards: [], card_products: [], + credit_accounts: [], + bill_card_subtotals: [], bills: [], bill_import_drafts: [], system_settings: [], diff --git a/email-worker/__tests__/fixtures/cmb-synthetic.ts b/email-worker/__tests__/fixtures/cmb-synthetic.ts new file mode 100644 index 0000000..a8bb354 --- /dev/null +++ b/email-worker/__tests__/fixtures/cmb-synthetic.ts @@ -0,0 +1,308 @@ +// email-worker/__tests__/fixtures/cmb-synthetic.ts +// 同构合成 fixture(假金额/假尾号/假商户),绝不包含真实账单数据与个人信息。 + +/** + * 单卡同构合成账单样本(脱敏模拟) + * - 账单月:2026-08 + * - 还款日:2026-09-15 + * - 信用额度:80,000.00 + * - 本期应还:18,888.88 + * - 最低还款:1,888.88 + * - 单卡尾号:6688 + */ +export const CMB_SINGLE_CARD_SYNTHETIC = `尊敬的王小明先生,您好!以下是您的个人消费卡账户08月账单 + 请您点击阅读《招商银行信用卡章程》("章程")、《招商银行信用卡(个人卡)通用领用合约》("合约"),以确保充分知悉和理解合约及章程内容。 + 我行已对电邮对账通知进行全面升级,您可点击电邮对账设置选择接收不含明细的电邮对账通知,变更后您可通过电邮对账通知中的指示引导跳转至手机官网、掌上生活(如有)或网上银行查询账单明细。 + +您2026年08月信用卡账单已出,最后还款日(Payment Due Date)09月15日 + +人民币金额(RMB) +信用额度 Credit Limit +¥ 80,000.00 +本期应还金额 New Balance +¥ 18,888.88 +最低还款额 Min. Payment +¥ 1,888.88 + + 人民币账户 +本期应还金额 +New Balance +¥ 18,888.88 +本期最低还款额 +Min.Payment +¥ 1,888.88 +本期应还金额 +New Balance += +上期账单金额 +Balance B/F +- +上期还款金额 + Payment ++ +本期账单金额 +New Charges +- +本期调整金额 +Adjustment ++ +循环利息 +Interest +¥ 18,888.88 +¥ 2,000.00 +¥ 2,000.00 +¥ 18,888.88 +¥ 0.00 +¥ 0.00 +交易日 +记账日 + 交易摘要 +人民币金额 +卡号末四位 +交易地金额 +交易地 +Trans +Date +Post +Date + Description +RMB Amount +Card Number +(last 4 digits) +Original Trans + Amount +Country +/Area + 还款 +0813 +手机银行还款 +¥ -2,000.00 +6688 +-2,000.00 + 分期 +0915 +0815 +账单分期 本金 +¥ 3,888.88 +6688 +3,888.88 + 消费 +0720 +0721 +阳光生活超市 +¥ 15,000.00 +6688 +15,000.00 +CN +★ +上述交易摘要中的商户名称仅供您参考,如与签购单不符,请以签购单为准。 +`; + +/** + * 多卡同构合成账单样本(脱敏模拟) + * - 账单月:2026-08 + * - 还款日:2026-09-15 + * - 本期应还:25,000.00 + * - 出现两张卡尾号:6688 (消费 15,000.00) 与 7799 (消费 9,500.00) + * - 差额:25,000.00 - 24,500.00 = 500.00 (账户级年费/结转) + */ +export const CMB_MULTI_CARD_SYNTHETIC = `尊敬的王小明先生,您好!以下是您的个人消费卡账户08月账单 +您2026年08月信用卡账单已出,最后还款日(Payment Due Date)09月15日 + +人民币金额(RMB) +信用额度 Credit Limit +¥ 80,000.00 +本期应还金额 New Balance +¥ 25,000.00 +最低还款额 Min. Payment +¥ 2,500.00 + + 人民币账户 +本期应还金额 +New Balance +¥ 25,000.00 +本期最低还款额 +Min.Payment +¥ 2,500.00 +本期应还金额 +New Balance += +上期账单金额 +Balance B/F +- +上期还款金额 + Payment ++ +本期账单金额 +New Charges +- +本期调整金额 +Adjustment ++ +循环利息 +Interest +¥ 25,000.00 +¥ 0.00 +¥ 0.00 +¥ 25,000.00 +¥ 0.00 +¥ 0.00 +交易日 +记账日 + 交易摘要 +人民币金额 +卡号末四位 +交易地金额 +交易地 +Trans +Date +Post +Date + Description +RMB Amount +Card Number +(last 4 digits) +Original Trans + Amount +Country +/Area + 消费 +0720 +0721 +阳光生活超市 +¥ 15,000.00 +6688 +15,000.00 +CN +0725 +0726 +数码专营店 +¥ 9,500.00 +7799 +9,500.00 +CN +★ +上述交易摘要中的商户名称仅供您参考,如与签购单不符,请以签购单为准。 +`; + +/** + * 多卡同构合成账单样本(含还款/分期/消费全部分段) + * - 账单月:2026-08 + * - 尾号 6688:还款 -1,000.00,分期 2,000.00,消费 10,000.00 -> 小计 11,000.00 + * - 尾号 7799:分期 3,000.00,消费 5,000.00 -> 小计 8,000.00 + * - 总额:20,000.00,未归卡差额 1,000.00 + */ +export const CMB_MULTI_CARD_ALL_SECTIONS_SYNTHETIC = `尊敬的王小明先生,您好!以下是您的个人消费卡账户08月账单 +您2026年08月信用卡账单已出,最后还款日(Payment Due Date)09月15日 + +人民币金额(RMB) +信用额度 Credit Limit +¥ 80,000.00 +本期应还金额 New Balance +¥ 20,000.00 +最低还款额 Min. Payment +¥ 2,000.00 + + 人民币账户 +本期应还金额 +New Balance +¥ 20,000.00 +本期最低还款额 +Min.Payment +¥ 2,000.00 +本期应还金额 +New Balance += +上期账单金额 +Balance B/F +- +上期还款金额 + Payment ++ +本期账单金额 +New Charges +- +本期调整金额 +Adjustment ++ +循环利息 +Interest +¥ 20,000.00 +¥ 1,000.00 +¥ 1,000.00 +¥ 20,000.00 +¥ 0.00 +¥ 0.00 +交易日 +记账日 + 交易摘要 +人民币金额 +卡号末四位 +交易地金额 +交易地 +Trans +Date +Post +Date + Description +RMB Amount +Card Number +(last 4 digits) +Original Trans + Amount +Country +/Area + 还款 +0813 +掌上生活还款 +¥ -1,000.00 +6688 +-1,000.00 + 分期 +0915 +0815 +分期还款 本金 +¥ 2,000.00 +6688 +2,000.00 +0915 +0815 +分期还款 本金 +¥ 3,000.00 +7799 +3,000.00 + 消费 +0720 +0721 +阳光生活超市 +¥ 10,000.00 +6688 +10,000.00 +CN +0725 +0726 +数码专营店 +¥ 5,000.00 +7799 +5,000.00 +CN +★ +上述交易摘要中的商户名称仅供您参考,如与签购单不符,请以签购单为准。 +`; + +/** + * 跨年月份合成样本(脱敏模拟):12月出账,次年1月还款 + * - 账单月:2026-12 + * - 还款日:2027-01-10(跨年) + */ +export const CMB_YEAR_ROLLOVER_SYNTHETIC = `尊敬的王小明先生,您好!以下是您的个人消费卡账户12月账单 +您2026年12月信用卡账单已出,最后还款日(Payment Due Date)01月10日 + +人民币金额(RMB) +信用额度 Credit Limit +¥ 80,000.00 +本期应还金额 New Balance +¥ 5,000.00 +最低还款额 Min. Payment +¥ 500.00 +`; diff --git a/email-worker/src/index.ts b/email-worker/src/index.ts index 1af254c..d74918e 100644 --- a/email-worker/src/index.ts +++ b/email-worker/src/index.ts @@ -19,10 +19,13 @@ import { loadHolderScope, parkBillAsDraft, syncBillingDayFromBill, + syncCreditLimitFromBill, upsertBillForCard, } from '../../lib/email-core/bills' +import { evaluateParsedBillDueDate } from '../../lib/email-core/due-date' import { extractNameFromBody, resolveHolder } from '../../lib/email-core/holders' import { loadAiConfig, parseBillWithAI } from '../../lib/email-core/ai' +import { isCmbStatement, parseCmbStatement } from '../../lib/email-core/cmb' import { scheduleBillSync } from './push' export default { @@ -70,10 +73,11 @@ export default { const raw = await streamToBytes(message.raw) const parsedTop = parseRawMessage(raw) const emailBody = parsedTop.text + const isCmbDirect = isCmbStatement({ fromEmail, subject, text: emailBody }) // 3. Fetch AI config(转发包路径里每封附件也要用它,所以提前到分支之前) const aiConfig = await loadAiConfig(db) - if (!aiConfig.apiKey) { + if (!isCmbDirect && !aiConfig.apiKey) { throw new Error('AI API Key 未配置(system_settings.ai_api_key)') } @@ -85,7 +89,9 @@ export default { db, userId, top: parsedTop, - parse: body => parseBillWithAI(aiConfig, body), + parse: body => isCmbStatement({ text: body }) + ? Promise.resolve(parseCmbStatement(body)) + : parseBillWithAI(aiConfig, body), }) if (bundle) { // billsWritten = 0 也算「处理过但没什么可写」,用 skipped 与失败的解析区分开 @@ -104,8 +110,10 @@ export default { return } - // 5. Parse bill with AI - const aiResult = await parseBillWithAI(aiConfig, emailBody) + // 5. Parse bill with CMB dedicated parser or AI + const aiResult = isCmbDirect + ? parseCmbStatement(emailBody) + : await parseBillWithAI(aiConfig, emailBody) log.raw_ai_response = JSON.stringify(aiResult) // 邮件类型门禁:自动扣款通知 / 还款提醒不是新一期账单。Chase 7491 的 @@ -118,18 +126,15 @@ export default { return } - // 0 元账单(本期已还清)是合法数据:bill_amount 用 == null 判空而不是 falsy, - // 否则 !0 会把应还 0 元的账单误判成缺字段跳过。due_date 同理——无需还款 - // 就没有还款截止日,金额为 0 时放宽。 - const zeroBill = Number(aiResult.bill_amount) === 0 - if ( - aiResult.is_bill === false || - !aiResult.bill_month || - aiResult.bill_amount == null || Number.isNaN(Number(aiResult.bill_amount)) || - (!zeroBill && !aiResult.due_date) - ) { + // 0 元账单(本期已还清)是合法数据:bill_amount 用 == null 判空而不是 falsy; + // 非 0 元账单必须有确切的 YYYY-MM-DD 还款日,禁止推算或编造日期。 + const dueEval = evaluateParsedBillDueDate(aiResult) + if (!dueEval.ok) { log.status = 'skipped' - log.error_msg = 'Not a bill email or missing required fields' + log.error_msg = + dueEval.kind === 'not_a_bill' + ? 'Not a bill email or missing required fields' + : dueEval.reason await writeLog(db, log) return } @@ -164,9 +169,10 @@ export default { cardTail: aiResult.card_last4 ?? null, bankName: aiResult.bank_name ?? null, currency: aiResult.currency ?? null, + creditLimit: aiResult.credit_limit ?? null, statementDate: aiResult.statement_date ?? null, statementDay: aiResult.statement_day ?? null, - dueDate: aiResult.due_date ?? null, + dueDate: dueEval.dueDate, receivedDate: parsedTop.headers.date ?? null, allowCreate: trusted, }) @@ -204,6 +210,7 @@ export default { if (billingDayUpdated) { cardNote += '已按本期出账日修正卡档账单日;' } + await syncCreditLimitFromBill(db, cardId, aiResult) // 8. Write success log log.bill_id = billId diff --git a/eslint.config.mjs b/eslint.config.mjs index 0ea0c5a..a884b50 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -84,6 +84,17 @@ export default tseslint.config( "@typescript-eslint/no-explicit-any": "warn", }, }, + { + // baoyu-design 工具链画板预览辅助脚本 + files: ["design/baoyu/**/*.js"], + languageOptions: { + globals: { + window: "readonly", + document: "readonly", + console: "readonly", + }, + }, + }, { // OpenPencil 设计脚本:在 QuickJS 沙箱里执行,`I(parent, node)` 由运行时注入。 // 只声明真实用到的沙箱全局,其余 lint 规则照常生效,避免整目录失守。 diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/CardEditService.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/CardEditService.swift index 4251de6..e501e15 100644 --- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/CardEditService.swift +++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/CardEditService.swift @@ -27,6 +27,9 @@ public struct CardUpdateInput: Sendable { public var overrideDueValue: Int? /// Omitted values leave the rule unchanged; this flag clears both fields. public var clearDueOverride: Bool = false + public var cardProductId: String? + public var cardNumberLast4: String? + public var holderId: String? public init( nameOverride: String? = nil, @@ -34,7 +37,11 @@ public struct CardUpdateInput: Sendable { billingDay: Int? = nil, overrideBillingDay: Int? = nil, overrideDueType: PaymentDueType? = nil, - overrideDueValue: Int? = nil + overrideDueValue: Int? = nil, + clearDueOverride: Bool = false, + cardProductId: String? = nil, + cardNumberLast4: String? = nil, + holderId: String? = nil ) { self.nameOverride = nameOverride self.creditLimit = creditLimit @@ -42,6 +49,10 @@ public struct CardUpdateInput: Sendable { self.overrideBillingDay = overrideBillingDay self.overrideDueType = overrideDueType self.overrideDueValue = overrideDueValue + self.clearDueOverride = clearDueOverride + self.cardProductId = cardProductId + self.cardNumberLast4 = cardNumberLast4 + self.holderId = holderId } } @@ -72,9 +83,23 @@ public final class CardEditService: Sendable { var patchDict: [String: Any] = [:] + if let productId = input.cardProductId, !productId.isEmpty { + card.cardProductId = productId + patchDict["card_product_id"] = productId + } + if let holderId = input.holderId, !holderId.isEmpty { + card.holderId = holderId + patchDict["holder_id"] = holderId + } + if let last4 = input.cardNumberLast4 { + let trimmed = last4.trimmingCharacters(in: .whitespaces) + card.cardNumberLast4 = trimmed.isEmpty ? nil : trimmed + patchDict["card_number_last4"] = trimmed.isEmpty ? NSNull() : trimmed + } if let name = input.nameOverride { - card.nameOverride = name.isEmpty ? nil : name - patchDict["name_override"] = name.isEmpty ? NSNull() : name + let trimmed = name.trimmingCharacters(in: .whitespaces) + card.nameOverride = trimmed.isEmpty ? nil : trimmed + patchDict["name_override"] = trimmed.isEmpty ? NSNull() : trimmed } if let limit = input.creditLimit { card.creditLimit = limit @@ -83,8 +108,10 @@ public final class CardEditService: Sendable { if let day = input.billingDay { card.billingDay = day patchDict["billing_day"] = day - } - if let ovDay = input.overrideBillingDay { + // 彻底收口:写入 billing_day 时强制置空 override_billing_day,消除双列遮蔽 + card.overrideBillingDay = nil + patchDict["override_billing_day"] = NSNull() + } else if let ovDay = input.overrideBillingDay { card.overrideBillingDay = ovDay patchDict["override_billing_day"] = ovDay } diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/QueryService.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/QueryService.swift index 0f76c8f..9922fac 100644 --- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/QueryService.swift +++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Domain/QueryService.swift @@ -403,4 +403,22 @@ public final class QueryService: Sendable { try CardHolder.order(Column("created_at").asc, Column("id").asc).fetchAll(db) } } + + /// 全部银行列表,按名称升序排列 + public func fetchBanks() async throws -> [Bank] { + try await dbManager.dbWriter.read { db in + try Bank.order(Column("name").asc).fetchAll(db) + } + } + + /// 全部或指定银行的卡产品列表 + public func fetchCardProducts(bankId: String? = nil) async throws -> [CardProduct] { + try await dbManager.dbWriter.read { db in + if let bankId, !bankId.isEmpty { + return try CardProduct.filter(Column("bank_id") == bankId).order(Column("card_name").asc).fetchAll(db) + } else { + return try CardProduct.order(Column("card_name").asc).fetchAll(db) + } + } + } } diff --git a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Models/CardHolder.swift b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Models/CardHolder.swift index 5f34c93..a8c7fee 100644 --- a/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Models/CardHolder.swift +++ b/ios/Packages/WorldCreditCore/Sources/WorldCreditCore/Models/CardHolder.swift @@ -39,6 +39,21 @@ public struct CardHolder: Codable, FetchableRecord, TableRecord, PersistableReco self.createdAt = createdAt } + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(String.self, forKey: .id) + let cb = try container.decodeIfPresent(String.self, forKey: .createdBy) ?? "" + createdBy = cb + managedBy = try container.decodeIfPresent(String.self, forKey: .managedBy) ?? cb + name = try container.decode(String.self, forKey: .name) + phone = try container.decodeIfPresent(String.self, forKey: .phone) + email = try container.decodeIfPresent(String.self, forKey: .email) + aliases = try container.decodeIfPresent(String.self, forKey: .aliases) + avatarColor = try container.decodeIfPresent(String.self, forKey: .avatarColor) ?? "#1976d2" + authUserId = try container.decodeIfPresent(String.self, forKey: .authUserId) + createdAt = try container.decodeIfPresent(String.self, forKey: .createdAt) ?? "" + } + enum CodingKeys: String, CodingKey { case id, name, phone, email, aliases case createdBy = "created_by" diff --git a/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/DomainRegressionTests.swift b/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/DomainRegressionTests.swift index b0cfd48..1493d85 100644 --- a/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/DomainRegressionTests.swift +++ b/ios/Packages/WorldCreditCore/Tests/WorldCreditCoreTests/DomainRegressionTests.swift @@ -339,4 +339,68 @@ struct DomainRegressionTests { let invalid = productJSON.replacingOccurrences(of: "\"fixed\"", with: "\"unknown\"") #expect(throws: DecodingError.self) { try JSONDecoder().decode(CardProduct.self, from: Data(invalid.utf8)) } } + + @Test("Updating billing day resets override billing day and enqueues NSNull in patch") + func billingDayUnification() async throws { + let manager = try database() + try await manager.dbWriter.write { db in + var card = try #require(try CreditCard.fetchOne(db, id: "card")) + card.overrideBillingDay = 15 + try card.update(db) + } + let service = CardEditService(dbManager: manager) + var input = CardUpdateInput() + input.billingDay = 20 + let card = try await service.updateCard(cardId: "card", input: input) + #expect(card.billingDay == 20) + #expect(card.overrideBillingDay == nil) + + try await manager.dbWriter.read { db in + let stored = try #require(try CreditCard.fetchOne(db, id: "card")) + #expect(stored.billingDay == 20) + #expect(stored.overrideBillingDay == nil) + let mutation = try #require(try MutationOutbox.fetchAll(db).first) + let args = try #require(try JSONSerialization.jsonObject(with: Data(mutation.argsJson.utf8)) as? [Any]) + let patch = try #require(args[1] as? [String: Any]) + #expect(patch["billing_day"] as? Int == 20) + #expect(patch["override_billing_day"] is NSNull) + } + } + + @Test("Card edit input accepts cardProductId, holderId, last4 and custom name") + func cardEditFullContract() async throws { + let manager = try database() + try await manager.dbWriter.write { db in + try db.execute(sql: """ + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES ('holder2', 'user', 'user', '测试2'); + INSERT INTO card_products (id, bank_id, bank_name, card_name, payment_due_type, payment_due_value) + VALUES ('product2', 'bank', '测试银行', '白金卡', 'fixed', 20); + """) + } + let service = CardEditService(dbManager: manager) + var input = CardUpdateInput() + input.cardProductId = "product2" + input.holderId = "holder2" + input.cardNumberLast4 = "8888" + input.nameOverride = "我的白金卡" + input.creditLimit = 20000 + + let card = try await service.updateCard(cardId: "card", input: input) + #expect(card.cardProductId == "product2") + #expect(card.holderId == "holder2") + #expect(card.cardNumberLast4 == "8888") + #expect(card.nameOverride == "我的白金卡") + #expect(card.creditLimit == 20000) + + try await manager.dbWriter.read { db in + let mutation = try #require(try MutationOutbox.fetchAll(db).first) + let args = try #require(try JSONSerialization.jsonObject(with: Data(mutation.argsJson.utf8)) as? [Any]) + let patch = try #require(args[1] as? [String: Any]) + #expect(patch["card_product_id"] as? String == "product2") + #expect(patch["holder_id"] as? String == "holder2") + #expect(patch["card_number_last4"] as? String == "8888") + #expect(patch["name_override"] as? String == "我的白金卡") + #expect(patch["credit_limit"] as? Double == 20000) + } + } } diff --git a/ios/WorldCredit/AppState.swift b/ios/WorldCredit/AppState.swift index 4fdf632..b82cb9d 100644 --- a/ios/WorldCredit/AppState.swift +++ b/ios/WorldCredit/AppState.swift @@ -1174,6 +1174,57 @@ public final class AppState { } } + @discardableResult + public func createHolder(name: String) async throws -> CardHolder { + let trimmed = name.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty else { + throw NSError(domain: "WorldCredit", code: 400, userInfo: [NSLocalizedDescriptionKey: "持卡人姓名不能为空"]) + } + let payload: [String: AnyCodable] = ["name": AnyCodable(trimmed)] + let holder: CardHolder = try await apiClient.rpc(module: "holders", function: "createHolder", args: [AnyCodable(payload)]) + await self.sync() + return holder + } + + @discardableResult + public func createCard( + holderId: String, + bankId: String, + cardProductId: String?, + cardName: String, + last4: String?, + creditLimit: Double, + billingDay: Int + ) async throws -> CreditCard { + var payload: [String: AnyCodable] = [ + "holder_id": AnyCodable(holderId), + "bank_id": AnyCodable(bankId), + "billing_day": AnyCodable(billingDay), + "credit_limit": AnyCodable(creditLimit), + ] + if let cardProductId, !cardProductId.isEmpty { + payload["card_product_id"] = AnyCodable(cardProductId) + } + let trimmedName = cardName.trimmingCharacters(in: .whitespaces) + if !trimmedName.isEmpty { + payload["name_override"] = AnyCodable(trimmedName) + } + if let last4 = last4?.trimmingCharacters(in: .whitespaces), !last4.isEmpty { + payload["card_number_last4"] = AnyCodable(last4) + } + let card: CreditCard = try await apiClient.rpc(module: "cards", function: "createCard", args: [AnyCodable(payload)]) + await self.sync() + return card + } + + public func allBanks() async -> [Bank] { + (try? await queryService.fetchBanks()) ?? [] + } + + public func cardProducts(for bankId: String? = nil) async -> [CardProduct] { + (try? await queryService.fetchCardProducts(bankId: bankId)) ?? [] + } + public func loadDemoData(onlyIfNeeded: Bool = false) async { let now = ISO8601DateFormatter().string(from: Date()) // 演示账单的还款日相对当天生成:固定历史日期会随真实日期漂移, diff --git a/ios/WorldCredit/Views/BillDetailView.swift b/ios/WorldCredit/Views/BillDetailView.swift index 8b18e42..fe34ecf 100644 --- a/ios/WorldCredit/Views/BillDetailView.swift +++ b/ios/WorldCredit/Views/BillDetailView.swift @@ -56,7 +56,7 @@ struct BillDetailView: View { Text(item.cardTitle) .font(.headline) .foregroundStyle(WCColors.textPrimary) - Text("\(item.bankName) · \(item.holderName) · 尾号 \(item.last4.isEmpty ? "-" : item.last4)") + Text(item.bankName) .font(.caption) .foregroundStyle(WCColors.textSecondary) } @@ -73,27 +73,37 @@ struct BillDetailView: View { } .accessibilityIdentifier("bill.detail.editCard") - if let card = matchedCard { - let billingDay = card.card.overrideBillingDay ?? card.card.billingDay - // 多币种卡:额度符号按卡片币种(缺产品信息时回落 CNY),不硬编码人民币 - let limitSymbol = DashboardMoney.currencySymbol(card.product?.currency ?? "CNY") - LabeledContent("信用额度", value: "\(limitSymbol)\(String(format: "%.0f", card.card.creditLimit))") - LabeledContent("每月账单日", value: "\(billingDay) 日") - LabeledContent("今日刷卡免息", value: "\(card.interestFreeDaysToday) 天") - } + let graceDays = matchedCard?.interestFreeDaysToday ?? item.interestFreeDaysToday + LabeledContent("今日刷卡免息", value: "\(graceDays) 天") } - // 账单基本信息 - Section("账单信息") { - LabeledContent("银行/卡片", value: "\(item.bankName) · \(item.cardTitle)") - LabeledContent("卡号尾号", value: item.last4.isEmpty ? "-" : item.last4) + // 账单基本信息与人+卡账户属性 + Section { LabeledContent("持卡人", value: item.holderName) + LabeledContent("卡号尾号", value: item.last4.isEmpty ? "-" : item.last4) + let limitSymbol = DashboardMoney.currencySymbol(item.currency) + let limit = matchedCard?.card.creditLimit ?? item.card.creditLimit + LabeledContent("信用额度", value: "\(limitSymbol)\(String(format: "%.0f", limit))") + let bDay = matchedCard?.card.billingDay ?? item.card.billingDay + LabeledContent("每月账单日", value: "\(bDay) 日") + LabeledContent("账单周期", value: item.bill.billMonth) if let stmtDate = item.bill.statementDate { LabeledContent("出账日", value: stmtDate) } LabeledContent("还款日", value: item.bill.dueDate) LabeledContent("距还款日", value: item.distanceLabel) + } header: { + HStack { + Text("账单信息(人+卡)") + Spacer() + Button("修改") { + showingCardEditSheet = true + } + .font(.footnote) + .foregroundStyle(WCColors.primaryAccent) + .accessibilityIdentifier("bill.detail.editAccount") + } } // 金额信息 diff --git a/ios/WorldCredit/Views/CardCreateSheetView.swift b/ios/WorldCredit/Views/CardCreateSheetView.swift new file mode 100644 index 0000000..9e798da --- /dev/null +++ b/ios/WorldCredit/Views/CardCreateSheetView.swift @@ -0,0 +1,270 @@ +import SwiftUI +import WorldCreditCore + +struct CardCreateSheetView: View { + @Environment(\.dismiss) private var dismiss + @Environment(AppState.self) private var appState + + @State private var selectedBankId: String = "" + @State private var selectedCardProductId: String = "" + @State private var cardName: String = "" + @State private var selectedHolderId: String = "" + @State private var isCreatingHolder: Bool = false + @State private var newHolderName: String = "" + @State private var cardNumberLast4: String = "" + @State private var creditLimitText: String = "20000" + @State private var billingDayText: String = "10" + @State private var banks: [Bank] = [] + @State private var products: [CardProduct] = [] + @State private var isSubmitting: Bool = false + @State private var errorMessage: String? + + var body: some View { + NavigationStack { + Form { + Section("卡片信息") { + Picker("所属银行", selection: $selectedBankId) { + if selectedBankId.isEmpty { + Text("请选择发卡银行").tag("") + } + ForEach(banks) { bank in + Text(bank.shortName ?? bank.name).tag(bank.id) + } + } + .accessibilityIdentifier("card.create.bank") + + VStack(alignment: .leading, spacing: 6) { + HStack { + Text("卡片名称") + Spacer() + TextField("输入卡片名称,或点选常用卡种", text: $cardName) + .multilineTextAlignment(.trailing) + .accessibilityIdentifier("card.create.name") + } + + if !products.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(products) { prod in + Button { + selectedCardProductId = prod.id + cardName = prod.cardName + } label: { + Text(prod.cardName) + .font(.caption2) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background( + selectedCardProductId == prod.id + ? WCColors.primaryAccent.opacity(0.15) + : Color.secondary.opacity(0.12) + ) + .foregroundStyle( + selectedCardProductId == prod.id + ? WCColors.primaryAccent + : WCColors.textPrimary + ) + .clipShape(Capsule()) + } + .buttonStyle(.plain) + } + } + .padding(.vertical, 2) + } + } + } + } + + Section("持卡人") { + if isCreatingHolder { + HStack { + TextField("持卡人姓名", text: $newHolderName) + .accessibilityIdentifier("card.create.newHolderName") + Button("取消") { + isCreatingHolder = false + newHolderName = "" + } + .font(.footnote) + } + } else { + Picker("持卡人", selection: $selectedHolderId) { + if selectedHolderId.isEmpty { + Text("请选择持卡人").tag("") + } + ForEach(appState.dashboardHolders) { holder in + Text(holder.name).tag(holder.id) + } + } + .accessibilityIdentifier("card.create.holder") + + Button { + isCreatingHolder = true + } label: { + Label("新建持卡人", systemImage: "plus.circle") + .font(.footnote) + .foregroundStyle(WCColors.primaryAccent) + } + } + } + + Section("账户信息") { + HStack { + Text("卡号尾号 (选填)") + Spacer() + TextField("如 8888", text: $cardNumberLast4) + .keyboardType(.asciiCapable) + .multilineTextAlignment(.trailing) + .accessibilityIdentifier("card.create.last4") + } + + HStack { + Text("信用额度 (¥)") + Spacer() + TextField("0", text: $creditLimitText) + .keyboardType(.numberPad) + .multilineTextAlignment(.trailing) + .accessibilityIdentifier("card.create.limit") + } + + HStack { + Text("每月账单日") + Spacer() + TextField("1-31", text: $billingDayText) + .keyboardType(.numberPad) + .multilineTextAlignment(.trailing) + .accessibilityIdentifier("card.create.billingDay") + Text("日") + .foregroundStyle(.secondary) + } + } + + if let errorMessage { + Section { + Text(errorMessage) + .foregroundStyle(.red) + .font(.footnote) + } + } + } + .navigationTitle("新增卡片") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("取消") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button(action: createCard) { + if isSubmitting { + ProgressView() + } else { + Text("创建卡片") + .bold() + } + } + .disabled(isSubmitting) + .accessibilityIdentifier("card.create.submit") + } + } + .task { + await loadBanks() + } + .onChange(of: selectedBankId) { _, newBankId in + Task { + await handleBankChange(newBankId: newBankId) + } + } + } + } + + private func loadBanks() async { + let bList = await appState.allBanks() + self.banks = bList + if let first = bList.first, selectedBankId.isEmpty { + selectedBankId = first.id + } + if selectedHolderId.isEmpty, let firstHolder = appState.dashboardHolders.first { + selectedHolderId = firstHolder.id + } + } + + private func handleBankChange(newBankId: String) async { + guard !newBankId.isEmpty else { + products = [] + return + } + let prods = await appState.cardProducts(for: newBankId) + self.products = prods + if let first = prods.first { + selectedCardProductId = first.id + if cardName.isEmpty { + cardName = first.cardName + } + } else { + selectedCardProductId = "" + if cardName.isEmpty { + let bankName = banks.first(where: { $0.id == newBankId })?.shortName ?? "信用卡" + cardName = "\(bankName)信用卡" + } + } + } + + private func createCard() { + guard !selectedBankId.isEmpty else { + errorMessage = "请选择发卡银行" + return + } + let trimmedName = cardName.trimmingCharacters(in: .whitespaces) + guard !trimmedName.isEmpty else { + errorMessage = "请输入卡片名称" + return + } + guard let limit = Double(creditLimitText), limit >= 0 else { + errorMessage = "请输入有效的信用额度" + return + } + guard let day = Int(billingDayText), day >= 1 && day <= 31 else { + errorMessage = "账单日必须在 1 到 31 之间" + return + } + + isSubmitting = true + errorMessage = nil + + Task { + do { + let finalHolderId: String + if isCreatingHolder { + let hName = newHolderName.trimmingCharacters(in: .whitespaces) + guard !hName.isEmpty else { + errorMessage = "请输入持卡人姓名" + isSubmitting = false + return + } + let holder = try await appState.createHolder(name: hName) + finalHolderId = holder.id + } else { + guard !selectedHolderId.isEmpty else { + errorMessage = "请选择持卡人" + isSubmitting = false + return + } + finalHolderId = selectedHolderId + } + + try await appState.createCard( + holderId: finalHolderId, + bankId: selectedBankId, + cardProductId: selectedCardProductId.isEmpty ? nil : selectedCardProductId, + cardName: trimmedName, + last4: cardNumberLast4.trimmingCharacters(in: .whitespaces), + creditLimit: limit, + billingDay: day + ) + dismiss() + } catch { + errorMessage = error.localizedDescription + isSubmitting = false + } + } + } +} diff --git a/ios/WorldCredit/Views/CardEditSheetView.swift b/ios/WorldCredit/Views/CardEditSheetView.swift index d4c33ad..02e9791 100644 --- a/ios/WorldCredit/Views/CardEditSheetView.swift +++ b/ios/WorldCredit/Views/CardEditSheetView.swift @@ -3,10 +3,15 @@ import WorldCreditCore struct CardEditSheetView: View { @Environment(\.dismiss) private var dismiss + @Environment(AppState.self) private var appState let card: CardDisplayItem let onSave: (CardUpdateInput) async throws -> Void - @State private var nameOverride: String + @State private var selectedBankId: String + @State private var selectedCardProductId: String + @State private var cardName: String + @State private var selectedHolderId: String + @State private var cardNumberLast4: String @State private var creditLimitText: String @State private var billingDayText: String @State private var hasCustomDueRule: Bool @@ -14,11 +19,19 @@ struct CardEditSheetView: View { @State private var dueValueText: String @State private var isSubmitting: Bool = false @State private var errorMessage: String? + @State private var banks: [Bank] = [] + @State private var products: [CardProduct] = [] init(card: CardDisplayItem, onSave: @escaping (CardUpdateInput) async throws -> Void) { self.card = card self.onSave = onSave - _nameOverride = State(initialValue: card.card.nameOverride ?? "") + let initialBankId = card.bank?.id ?? card.product?.bankId ?? "" + _selectedBankId = State(initialValue: initialBankId) + _selectedCardProductId = State(initialValue: card.card.cardProductId) + let effectiveName = card.card.nameOverride ?? card.product?.cardName ?? card.displayName + _cardName = State(initialValue: effectiveName) + _selectedHolderId = State(initialValue: card.card.holderId) + _cardNumberLast4 = State(initialValue: card.card.cardNumberLast4 ?? "") _creditLimitText = State(initialValue: String(format: "%.0f", card.card.creditLimit)) let effectiveBillingDay = card.card.overrideBillingDay ?? card.card.billingDay _billingDayText = State(initialValue: "\(effectiveBillingDay)") @@ -33,21 +46,79 @@ struct CardEditSheetView: View { var body: some View { NavigationStack { Form { - Section("基本信息") { - LabeledContent("所属银行", value: card.bankName) - LabeledContent("原卡产品", value: card.product?.cardName ?? "信用卡") - LabeledContent("持卡人", value: card.holderName) - if !card.last4.isEmpty { - LabeledContent("卡号尾号", value: card.last4) + Section("卡片信息") { + Picker("所属银行", selection: $selectedBankId) { + if selectedBankId.isEmpty { + Text("未指定银行").tag("") + } + ForEach(banks) { bank in + Text(bank.shortName ?? bank.name).tag(bank.id) + } } + .accessibilityIdentifier("card.edit.bank") + + VStack(alignment: .leading, spacing: 6) { + HStack { + Text("卡片名称") + Spacer() + TextField("输入卡片名称,或点选下方常用卡种", text: $cardName) + .multilineTextAlignment(.trailing) + .accessibilityIdentifier("card.edit.name") + } - TextField("卡片备注名称", text: $nameOverride) - .accessibilityIdentifier("card.edit.name") + if !products.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(products) { prod in + Button { + selectedCardProductId = prod.id + cardName = prod.cardName + } label: { + Text(prod.cardName) + .font(.caption2) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background( + selectedCardProductId == prod.id + ? WCColors.primaryAccent.opacity(0.15) + : Color.secondary.opacity(0.12) + ) + .foregroundStyle( + selectedCardProductId == prod.id + ? WCColors.primaryAccent + : WCColors.textPrimary + ) + .clipShape(Capsule()) + } + .buttonStyle(.plain) + } + } + .padding(.vertical, 2) + } + } + } } - Section("额度与账单日") { + Section("人+卡账户信息") { + Picker("持卡人", selection: $selectedHolderId) { + ForEach(appState.dashboardHolders) { holder in + Text(holder.name).tag(holder.id) + } + } + .accessibilityIdentifier("card.edit.holder") + + HStack { + Text("卡号尾号 (选填)") + Spacer() + TextField("如 8888", text: $cardNumberLast4) + .keyboardType(.asciiCapable) + .multilineTextAlignment(.trailing) + .accessibilityIdentifier("card.edit.last4") + } + HStack { - Text("信用额度 (¥)") + let symbol = DashboardMoney.currencySymbol(card.product?.currency ?? "CNY") + Text("信用额度 (\(symbol))") Spacer() TextField("0", text: $creditLimitText) .keyboardType(.numberPad) @@ -125,6 +196,14 @@ struct CardEditSheetView: View { .accessibilityIdentifier("card.edit.save") } } + .task { + await loadBanksAndProducts() + } + .onChange(of: selectedBankId) { _, newBankId in + Task { + await handleBankChange(newBankId: newBankId) + } + } } } @@ -140,7 +219,36 @@ struct CardEditSheetView: View { } } + private func loadBanksAndProducts() async { + let bList = await appState.allBanks() + self.banks = bList + if !selectedBankId.isEmpty { + self.products = await appState.cardProducts(for: selectedBankId) + } + } + + private func handleBankChange(newBankId: String) async { + guard !newBankId.isEmpty else { return } + let prods = await appState.cardProducts(for: newBankId) + self.products = prods + if let first = prods.first { + selectedCardProductId = first.id + if cardName.isEmpty || cardName == card.displayName || cardName == card.product?.cardName { + cardName = first.cardName + } + } + } + private func save() { + let trimmedName = cardName.trimmingCharacters(in: .whitespaces) + guard !trimmedName.isEmpty else { + errorMessage = "请输入卡片名称" + return + } + guard !selectedHolderId.isEmpty else { + errorMessage = "请选择持卡人" + return + } guard let limit = Double(creditLimitText), limit >= 0 else { errorMessage = "请输入有效的信用额度" return @@ -151,9 +259,15 @@ struct CardEditSheetView: View { } var input = CardUpdateInput() - input.nameOverride = nameOverride.trimmingCharacters(in: .whitespaces) + if !selectedCardProductId.isEmpty { + input.cardProductId = selectedCardProductId + } + input.nameOverride = trimmedName + input.holderId = selectedHolderId + input.cardNumberLast4 = cardNumberLast4.trimmingCharacters(in: .whitespaces) input.creditLimit = limit - input.overrideBillingDay = day + // 关键收口:写入 billing_day,CardEditService 会强制清空 override_billing_day + input.billingDay = day if hasCustomDueRule { guard let val = Int(dueValueText), val > 0 else { diff --git a/ios/WorldCredit/Views/CardsView.swift b/ios/WorldCredit/Views/CardsView.swift index 533a78c..b1a97df 100644 --- a/ios/WorldCredit/Views/CardsView.swift +++ b/ios/WorldCredit/Views/CardsView.swift @@ -4,16 +4,23 @@ import WorldCreditCore struct CardsView: View { @Environment(AppState.self) private var appState @State private var editingCard: CardDisplayItem? + @State private var showingCreateCardSheet: Bool = false var body: some View { NavigationStack { List { if appState.cards.isEmpty { - ContentUnavailableView( - "暂无卡片数据", - systemImage: "creditcard", - description: Text("下拉可同步最新卡片数据") - ) + ContentUnavailableView { + Label("暂无卡片数据", systemImage: "creditcard") + } description: { + Text("点击右上角或下方按钮新增卡片,也可下拉同步最新数据") + } actions: { + Button("新增卡片") { + showingCreateCardSheet = true + } + .buttonStyle(.borderedProminent) + .accessibilityIdentifier("cards.emptyAddCard") + } } else { ForEach(appState.cards) { card in Button { @@ -28,6 +35,16 @@ struct CardsView: View { } .listStyle(.insetGrouped) .navigationTitle("卡片") + .toolbar { + ToolbarItem(placement: .primaryAction) { + Button { + showingCreateCardSheet = true + } label: { + Image(systemName: "plus") + } + .accessibilityIdentifier("cards.addCard") + } + } .refreshable { await appState.sync() } @@ -36,6 +53,9 @@ struct CardsView: View { try await appState.updateCard(cardId: card.id, input: input) } } + .sheet(isPresented: $showingCreateCardSheet) { + CardCreateSheetView() + } } } } diff --git a/lib/__tests__/bill-unissued.test.ts b/lib/__tests__/bill-unissued.test.ts new file mode 100644 index 0000000..f6c789a --- /dev/null +++ b/lib/__tests__/bill-unissued.test.ts @@ -0,0 +1,62 @@ +import { describe, it, expect } from 'vitest' +import { isBillUnissued, diffInCalendarDays } from '../utils' + +describe('isBillUnissued 日历日时区与出账判定', () => { + it('出账日当天(含凌晨 00:00-08:00)判定为已出账,绝不误判为未出账', () => { + // 假设出账日是 2026-11-05 + const bill = { statement_date: '2026-11-05' } + + // 当天凌晨 02:30(在 UTC 下对应 2026-11-04 18:30) + const earlyMorningToday = new Date('2026-11-05T02:30:00+08:00') + expect(diffInCalendarDays(bill.statement_date, earlyMorningToday)).toBe(0) + expect(isBillUnissued(bill, earlyMorningToday)).toBe(false) + + // 当天中午 12:00 + const noonToday = new Date('2026-11-05T12:00:00+08:00') + expect(isBillUnissued(bill, noonToday)).toBe(false) + }) + + it('未来日期判定为未出账', () => { + const bill = { statement_date: '2026-11-06' } + const today = new Date('2026-11-05T10:00:00+08:00') + expect(diffInCalendarDays(bill.statement_date, today)).toBe(1) + expect(isBillUnissued(bill, today)).toBe(true) + }) + + it('过去日期判定为已出账', () => { + const bill = { statement_date: '2026-11-04' } + const today = new Date('2026-11-05T10:00:00+08:00') + expect(diffInCalendarDays(bill.statement_date, today)).toBe(-1) + expect(isBillUnissued(bill, today)).toBe(false) + }) + + it('statement_date_override 优先于 statement_date', () => { + const today = new Date('2026-11-05T10:00:00+08:00') + // 原始出账日是过去(2026-11-01),但 override 改到了未来(2026-11-10) + const bill = { + statement_date: '2026-11-01', + statement_date_override: '2026-11-10', + } + expect(isBillUnissued(bill, today)).toBe(true) + + // 反之:原始出账日在未来,但 override 改到过去 + const bill2 = { + statement_date: '2026-11-20', + statement_date_override: '2026-11-01', + } + expect(isBillUnissued(bill2, today)).toBe(false) + }) + + it('兜底支持 statement_end', () => { + const today = new Date('2026-11-05T10:00:00+08:00') + const billFuture = { statement_end: '2026-11-08' } + expect(isBillUnissued(billFuture, today)).toBe(true) + + const billPast = { statement_end: '2026-11-02' } + expect(isBillUnissued(billPast, today)).toBe(false) + }) + + it('无出账日期字段时安全返回 false', () => { + expect(isBillUnissued({})).toBe(false) + }) +}) diff --git a/lib/__tests__/bills-current-period-regression.test.ts b/lib/__tests__/bills-current-period-regression.test.ts new file mode 100644 index 0000000..7d91335 --- /dev/null +++ b/lib/__tests__/bills-current-period-regression.test.ts @@ -0,0 +1,88 @@ +// lib/__tests__/bills-current-period-regression.test.ts +// 回归测试: +// 1. 202608 已还完旧账单不再占位当前期,当前期正确指向 10 月账单; +// 2. 待出账且已还款的账单不判定/显示为逾期; +// 3. 待出账账单在未到出账日前不判为 overdue。 + +import { describe, it, expect, beforeEach } from 'vitest' +import { createOpportunityDb } from './helpers/sqlite-d1' +import { setDb } from '../db/client' +import { getCardsWithBillsSummary } from '../api/bills.server' + +let db: ReturnType + +beforeEach(async () => { + db = createOpportunityDb() + setDb(db as unknown as D1Database) + await db.exec(` + INSERT INTO users (id, email, password_hash) VALUES ('u1', 'u1@example.com', 'hash'); + INSERT INTO banks (id, name) VALUES ('b_mintai', '浙江民泰商业银行'); + INSERT INTO card_products (id, bank_id, bank_name, card_name, payment_due_type, payment_due_value) + VALUES ('cp_mintai_pu', 'b_mintai', '浙江民泰商业银行', '民泰普卡', 'after_billing', 20); + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES ('h1', 'u1', 'u1', '本人'); + INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day) + VALUES ('cc_2104', 'h1', 'cp_mintai_pu', '2104', 15); + `) +}) + +describe('A2 账单周期与逾期显示回归测试', () => { + it('202608 已还完 + 10 月当前期已还完:activeBill 必须为 10 月账单,旧账单不再占位', async () => { + await db.exec(` + INSERT INTO bills (id, card_id, bill_month, due_date, statement_date, bill_amount, status) + VALUES + ('b_202608', 'cc_2104', '2026-08', '2026-08-25', '2026-08-05', 1000, 'paid'), + ('b_202610', 'cc_2104', '2026-10', '2026-10-25', '2026-10-05', 2000, 'paid'); + `) + + const summaries = await getCardsWithBillsSummary('u1') + expect(summaries).toHaveLength(1) + const cardSummary = summaries[0] + expect(cardSummary.card.card_number_last4).toBe('2104') + expect(cardSummary.activeBill).not.toBeNull() + expect(cardSummary.activeBill?.bill_month).toBe('2026-10') + expect(cardSummary.activeBill?.id).toBe('b_202610') + expect(cardSummary.historyBills[0].bill_month).toBe('2026-10') + expect(cardSummary.historyBills[1].bill_month).toBe('2026-08') + }) + + it('202608 已还完 + 10 月当前期待还款(未到期):activeBill 必须为 10 月账单且状态为 unpaid', async () => { + await db.exec(` + INSERT INTO bills (id, card_id, bill_month, due_date, statement_date, bill_amount, status) + VALUES + ('b_202608', 'cc_2104', '2026-08', '2026-08-25', '2026-08-05', 1000, 'paid'), + ('b_202610', 'cc_2104', '2026-10', '2099-11-25', '2026-10-05', 2000, 'unpaid'); + `) + + const summaries = await getCardsWithBillsSummary('u1') + const cardSummary = summaries[0] + expect(cardSummary.activeBill?.bill_month).toBe('2026-10') + expect(cardSummary.activeBill?.id).toBe('b_202610') + expect(cardSummary.status).toBe('unpaid') + }) + + it('待出账单(未到出账日)即使到期日异常,不判为 overdue,卡片状态不为 overdue', async () => { + // statement_date 在未来(9999-12-31),due_date 异常写在过去 + await db.exec(` + INSERT INTO bills (id, card_id, bill_month, due_date, statement_date, bill_amount, status) + VALUES ('b_unissued', 'cc_2104', '2026-11', '2020-01-01', '2099-11-15', 500, 'unpaid'); + `) + + const summaries = await getCardsWithBillsSummary('u1') + const cardSummary = summaries[0] + expect(cardSummary.activeBill?.computed_status).toBe('unpaid') + expect(cardSummary.status).toBe('unpaid') + expect(cardSummary.status).not.toBe('overdue') + }) + + it('待出账且已还款的账单:状态为 paid,卡片为 unissued(已结清),绝不显示逾期', async () => { + await db.exec(` + INSERT INTO bills (id, card_id, bill_month, due_date, statement_date, bill_amount, status) + VALUES ('b_future_paid', 'cc_2104', '2026-12', '2099-12-25', '2099-12-05', 500, 'paid'); + `) + + const summaries = await getCardsWithBillsSummary('u1') + const cardSummary = summaries[0] + expect(cardSummary.activeBill?.computed_status).toBe('paid') + expect(cardSummary.status).toBe('unissued') + }) +}) diff --git a/lib/__tests__/bills-view-model.test.ts b/lib/__tests__/bills-view-model.test.ts index a67b369..742bb63 100644 --- a/lib/__tests__/bills-view-model.test.ts +++ b/lib/__tests__/bills-view-model.test.ts @@ -85,6 +85,30 @@ describe('deriveAccountMode', () => { const cards = [item({ bank: '招商银行', accountModeOverride: 'multi' })] expect(deriveAccountMode('h1', '招商银行', cards)).toBe('multi') }) + + it('实体账户 statement_mode 优先于卡数和 override', () => { + // 实体账户为 merged,即使只有 1 张卡也判定为 multi + const singleMerged = [ + { + ...item({ bank: '招商银行' }), + account: { statement_mode: 'merged' } as unknown as CardWithBillsSummary['account'], + }, + ] + expect(deriveAccountMode('h1', '招商银行', singleMerged)).toBe('multi') + + // 实体账户为 separate,即使有 2 张卡也判定为 single + const multiSeparate = [ + { + ...item({ bank: '招商银行' }), + account: { statement_mode: 'separate' } as unknown as CardWithBillsSummary['account'], + }, + { + ...item({ bank: '招商银行' }), + account: { statement_mode: 'separate' } as unknown as CardWithBillsSummary['account'], + }, + ] + expect(deriveAccountMode('h1', '招商银行', multiSeparate)).toBe('single') + }) }) describe('billBadgeView', () => { diff --git a/lib/__tests__/card-anchor-guard.test.ts b/lib/__tests__/card-anchor-guard.test.ts new file mode 100644 index 0000000..814afb7 --- /dev/null +++ b/lib/__tests__/card-anchor-guard.test.ts @@ -0,0 +1,165 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { createOpportunityDb } from "./helpers/sqlite-d1"; +import { setDb } from "../db"; +import { createCard, deleteCard } from "../api/cards.server"; +import { mergeCardsIntoAccount, splitCardFromAccount, getCreditAccountDetail } from "../api/accounts.server"; + +describe("Anchor Card Lifecycle Guard & Account Operations", () => { + let db: ReturnType; + + beforeEach(async () => { + db = createOpportunityDb(); + setDb(db as unknown as D1Database); + + await db.exec(` + INSERT INTO users (id, email, password_hash) VALUES + ('u1', 'u1@example.com', 'h1'); + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES + ('h1', 'u1', 'u1', '持卡人甲'), + ('h2', 'u1', 'u1', '持卡人乙'); + INSERT INTO banks (id, name, statement_mode, quota_mode) VALUES + ('b_cmb', '招商银行', 'merged', 'shared'); + INSERT INTO card_products (id, bank_id, bank_name, card_name, currency) VALUES + ('cp_cmb', 'b_cmb', '招商银行', '经典白金卡', 'CNY'); + `); + }); + + afterEach(() => { + db.close(); + }); + + it("createCard associates with existing merged account if one exists, otherwise creates new account", async () => { + // 1. 创建第一张招行卡 + const card1 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 50000, + }); + expect(card1.account_id).toBeTruthy(); + + const acc1 = await getCreditAccountDetail(card1.account_id!); + expect(acc1?.statement_mode).toBe("merged"); + expect(acc1?.primary_card_id).toBe(card1.id); + + // 2. 创建同持卡人同银行第二张招行卡,应自动挂载在同一个 credit_account + const card2 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 60000, + }); + expect(card2.account_id).toBe(card1.account_id); + + const accUpdated = await getCreditAccountDetail(card1.account_id!); + expect(accUpdated?.cards.map((c) => c.id)).toEqual( + expect.arrayContaining([card1.id, card2.id]), + ); + }); + + it("deleteCard transfers primary_card_id and bills when deleting anchor card in a multi-card account", async () => { + const card1 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + }); + const card2 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + }); + + // 插入挂在 card1(当前 primary_card_id)下的账单 + await db.exec(` + INSERT INTO bills (id, account_id, card_id, bill_month, due_date, bill_amount) + VALUES ('bill_cmb_anchor', '${card1.account_id}', '${card1.id}', '2026-10', '2026-10-25', 8888); + `); + + // 删除锚点卡 card1 + await deleteCard(card1.id); + + // card1 应被删除 + const checkCard1 = await db.prepare("SELECT * FROM credit_cards WHERE id = ?").bind(card1.id).first(); + expect(checkCard1).toBeNull(); + + // 账户的 primary_card_id 应自动平滑移交给 card2 + const acc = await getCreditAccountDetail(card1.account_id!); + expect(acc?.primary_card_id).toBe(card2.id); + + // 历史账单绝不丢失!且 card_id 随之平滑对齐为 card2! + const bill = await db.prepare("SELECT * FROM bills WHERE id = 'bill_cmb_anchor'").first<{ card_id: string; bill_amount: number }>(); + expect(bill).not.toBeNull(); + expect(bill?.card_id).toBe(card2.id); + expect(bill?.bill_amount).toBe(8888); + }); + + it("splitCardFromAccount splits a card into independent account and safely updates anchor", async () => { + const card1 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + }); + const card2 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + }); + + const newAcc = await splitCardFromAccount(card1.id); + expect(newAcc.statement_mode).toBe("independent"); + expect(newAcc.primary_card_id).toBe(card1.id); + + // card1 挂在新账户上 + const c1Row = await db.prepare("SELECT account_id FROM credit_cards WHERE id = ?").bind(card1.id).first<{ account_id: string }>(); + expect(c1Row?.account_id).toBe(newAcc.id); + + // 原账户的锚点卡切换为 card2 + const oldAcc = await getCreditAccountDetail(card2.account_id!); + expect(oldAcc?.primary_card_id).toBe(card2.id); + }); + + it("mergeCardsIntoAccount merges cards into target account and rejects same-month collisions", async () => { + const card1 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + }); + // 拆出 card2 为独立账户 + const card2 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + }); + const indepAcc = await splitCardFromAccount(card2.id); + + // 两个账户在 2026-10 均有账单 -> 碰撞! + await db.exec(` + INSERT INTO bills (id, account_id, card_id, bill_month, due_date, bill_amount) + VALUES + ('b_t1', '${card1.account_id}', '${card1.id}', '2026-10', '2026-10-25', 1000), + ('b_t2', '${indepAcc.id}', '${card2.id}', '2026-10', '2026-10-25', 2000); + `); + + // 试图合并 card2 进 card1.account_id -> 必须报冲突并拒绝! + await expect(mergeCardsIntoAccount(card1.account_id!, [card2.id])).rejects.toThrow( + /检测到历史账单碰撞/, + ); + }); + + it("mergeCardsIntoAccount rejects cross-holder merge", async () => { + const card1 = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + }); + const cardH2 = await createCard({ + holder_id: "h2", + card_product_id: "cp_cmb", + billing_day: 5, + }); + + await expect(mergeCardsIntoAccount(card1.account_id!, [cardH2.id])).rejects.toThrow( + /不可跨持卡人合并/, + ); + }); +}); diff --git a/lib/__tests__/card-override-coverage.test.ts b/lib/__tests__/card-override-coverage.test.ts index 9c12b8d..35ae1fe 100644 --- a/lib/__tests__/card-override-coverage.test.ts +++ b/lib/__tests__/card-override-coverage.test.ts @@ -40,11 +40,16 @@ describe('账单/卡片查询必须携带卡级别覆盖列', () => { it('getBillDetail 把覆盖列落进了返回的 card 对象', () => { const body = fnBody(bills, 'getBillDetail') - for (const field of ['name_override', 'override_due_type', 'override_due_value']) { + for (const field of ['name_override', 'override_due_type', 'override_due_value', 'credit_limit_override']) { expect(body, `getBillDetail 返回的 card 缺 ${field}`).toMatch(new RegExp(`\\b${field}:`)) } }) + it('getBillDetail SELECT 中包含了 credit_limit_override', () => { + const body = fnBody(bills, 'getBillDetail') + expect(body).toMatch(/cc\.credit_limit_override AS c_credit_limit_override/) + }) + it('账单读路径的卡名优先级与 withCreditCardProductFields 一致', () => { expect(bills).toMatch(/card_name: card\.name_override \?\? card\.card_name \?\? card\.card_product\?\.card_name/) }) diff --git a/lib/__tests__/card-remodel-phase1.test.ts b/lib/__tests__/card-remodel-phase1.test.ts new file mode 100644 index 0000000..b87d263 --- /dev/null +++ b/lib/__tests__/card-remodel-phase1.test.ts @@ -0,0 +1,137 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { createOpportunityDb, type SqliteD1 } from './helpers/sqlite-d1' +import { seedOpportunityFixtures, FIXTURE_IDS } from './helpers/opportunity-fixtures' +import { setDb } from '../db/client' +import { createCard, updateCard } from '../api/cards.server' +import { createHolder } from '../api/holders.server' +import { getBanks } from '../api/banks.server' + +let db: SqliteD1 +const f = FIXTURE_IDS + +beforeEach(async () => { + db = createOpportunityDb() + await seedOpportunityFixtures(db) + setDb(db as unknown as D1Database) +}) + +afterEach(() => { + setDb(null) + db.close() +}) + +describe('Phase 1: 卡片模型与服务端重构测试', () => { + it('0031 迁移验证:存量 override_billing_day 归一', async () => { + // 存量 override_billing_day 应该为 null + const remainingOverrides = db.raw.prepare('SELECT COUNT(*) as cnt FROM credit_cards WHERE override_billing_day IS NOT NULL').get() as { cnt: number } + expect(remainingOverrides.cnt).toBe(0) + }) + + it('createCard: 仅传 bank_id 自动解析兜底卡产品,且自定义卡名落库', async () => { + const card = await createCard({ + holder_id: f.holders.self, + bank_id: f.banks.cmb, + name_override: '招行家庭主卡', + card_number_last4: '8888', + credit_limit: 50000, + billing_day: 10, + }) + + expect(card.id).toBeTruthy() + expect(card.name_override).toBe('招行家庭主卡') + expect(card.card_name).toBe('招行家庭主卡') + expect(card.billing_day).toBe(10) + expect(card.override_billing_day).toBeUndefined() + expect(card.card_product).toBeDefined() + }) + + it('createCard: 卡名等于产品默认名时 name_override 置 null', async () => { + // 获取招行产品默认名 + const prod = db.raw.prepare('SELECT id, card_name FROM card_products WHERE bank_id = ? LIMIT 1').get(f.banks.cmb) as { id: string; card_name: string } + expect(prod).toBeDefined() + + const card = await createCard({ + holder_id: f.holders.self, + card_product_id: prod.id, + name_override: prod.card_name, + billing_day: 5, + }) + + expect(card.name_override).toBeUndefined() + expect(card.card_name).toBe(prod.card_name) + }) + + it('updateCard: 同币种切换银行/卡产品成功', async () => { + // 从招行切到工行(均为 CNY) + const targetProd = db.raw.prepare('SELECT id FROM card_products WHERE bank_id = ? AND currency = ? LIMIT 1').get(f.banks.icbc, 'CNY') as { id: string } + expect(targetProd).toBeDefined() + + const updated = await updateCard(f.cards.selfMain, { + card_product_id: targetProd.id, + }) + + expect(updated.card_product_id).toBe(targetProd.id) + expect(updated.card_product?.bank_id).toBe(f.banks.icbc) + }) + + it('updateCard: 已有账单跨币种切换时阻断拦截 (Q3 规则)', async () => { + // 为当前卡插入账单 + await db + .prepare('INSERT INTO bills (id, card_id, bill_month, bill_amount, min_payment, due_date, status) VALUES (?,?,?,?,?,?,?)') + .bind('b-currency-test', f.cards.selfMain, '2026-09', 200, 20, '2026-10-16', 'unpaid') + .run() + + // 尝试切换到 USD 产品 + const usdProd = db.raw.prepare("SELECT id FROM card_products WHERE currency = 'USD' LIMIT 1").get() as { id: string } + if (usdProd) { + await expect( + updateCard(f.cards.selfMain, { card_product_id: usdProd.id }) + ).rejects.toThrow(/仅允许切换到同币种卡产品/) + } + }) + + it('updateCard: 修改 billing_day 时清空 override_billing_day (Q2 规则)', async () => { + // 人工先写入 override_billing_day + db.raw.prepare('UPDATE credit_cards SET override_billing_day = 12 WHERE id = ?').run(f.cards.selfMain) + + const updated = await updateCard(f.cards.selfMain, { + billing_day: 25, + }) + + expect(updated.billing_day).toBe(25) + expect(updated.override_billing_day).toBeUndefined() + + const row = db.raw.prepare('SELECT billing_day, override_billing_day FROM credit_cards WHERE id = ?').get(f.cards.selfMain) as { billing_day: number; override_billing_day: number | null } + expect(row.billing_day).toBe(25) + expect(row.override_billing_day).toBeNull() + }) + + it('updateCard: 跨账户篡改 holder_id 予以拒绝', async () => { + await expect( + updateCard(f.cards.selfMain, { holder_id: f.holders.adminB }) + ).rejects.toThrow(/不存在,或不属于同一账户/) + }) + + it('holders.createHolder: 登录用户可成功创建归属自己的持卡人', async () => { + const newHolder = await createHolder({ + created_by: f.users.adminA, + managed_by: f.users.adminA, + name: '李小四', + avatar_color: '#3b82f6', + }) + + expect(newHolder.id).toBeTruthy() + expect(newHolder.name).toBe('李小四') + expect(newHolder.created_by).toBe(f.users.adminA) + }) + + it('banks.getBanks: 返回完整银行列表及配置字段', async () => { + const banks = await getBanks() + expect(banks.length).toBeGreaterThan(0) + const first = banks[0] + expect(first.id).toBeTruthy() + expect(first.name).toBeTruthy() + expect('quota_mode' in first).toBe(true) + expect('statement_mode' in first).toBe(true) + }) +}) diff --git a/lib/__tests__/cmb-statement-phase3.test.ts b/lib/__tests__/cmb-statement-phase3.test.ts new file mode 100644 index 0000000..ce6c41f --- /dev/null +++ b/lib/__tests__/cmb-statement-phase3.test.ts @@ -0,0 +1,274 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import fs from 'node:fs' +import { createOpportunityDb, type SqliteD1 } from './helpers/sqlite-d1' +import { setDb } from '../db/client' +import { isCmbStatement, parseCmbStatement } from '../email-core/cmb' +import { + findOrCreateCardForHolder, + upsertBillForCard, + syncCreditLimitFromBill, +} from '../email-core/bills' +import { getBillDetail } from '../api/bills.server' +import { + CMB_SINGLE_CARD_SYNTHETIC, + CMB_MULTI_CARD_SYNTHETIC, + CMB_YEAR_ROLLOVER_SYNTHETIC, +} from '../../email-worker/__tests__/fixtures/cmb-synthetic' + +let db: SqliteD1 + +beforeEach(async () => { + db = createOpportunityDb() + setDb(db as unknown as D1Database) + + await db.exec(` + INSERT INTO users (id, email, password_hash) VALUES ('u1', 'test@example.com', 'hash'); + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES ('h1', 'u1', 'u1', '王小明'); + + INSERT INTO banks (id, name, statement_mode, quota_mode) + VALUES ('b_cmb', '招商银行', 'merged', 'shared'); + + INSERT INTO card_products (id, bank_id, bank_name, card_name, currency, payment_due_type, payment_due_value) + VALUES + ('cp_cmb_classic', 'b_cmb', '招商银行', '经典白金卡', 'CNY', 'after_billing', 20); + `) +}) + +describe('E6 统一账单 Phase 3:招行邮件解析与归并入库 (D1 实库集成)', () => { + it('单卡合成账单识别、首次入库并建立合并账户与分卡小计', () => { + // 1. 识别 + const isCmb = isCmbStatement({ + fromEmail: 'bill@cmbchina.com', + subject: '尊敬的王小明先生,您好!以下是您的个人消费卡账户08月账单', + text: CMB_SINGLE_CARD_SYNTHETIC, + }) + expect(isCmb).toBe(true) + + // 2. 解析 + const parsed = parseCmbStatement(CMB_SINGLE_CARD_SYNTHETIC) + expect(parsed.bill_month).toBe('2026-08') + expect(parsed.due_date).toBe('2026-09-15') + expect(parsed.bill_amount).toBe(18888.88) + expect(parsed.credit_limit).toBe(80000) + expect(parsed.formula_breakdown).toEqual({ + previous_balance: 2000, + previous_payment: 2000, + new_charges: 18888.88, + adjustment: 0, + interest: 0, + }) + expect(parsed.card_subtotals).toHaveLength(1) + expect(parsed.card_subtotals?.[0].card_last4).toBe('6688') + expect(parsed.card_subtotals?.[0].amount).toBe(18888.88) + }) + + it('首张卡账单落库:自动创建 credit_account(merged, shared) 与卡片、账单及小计', async () => { + const parsed = parseCmbStatement(CMB_SINGLE_CARD_SYNTHETIC) + + const d1 = db as unknown as D1Database + const cardRes = await findOrCreateCardForHolder(d1, { + holderId: 'h1', + cardTail: parsed.card_last4 ?? null, + bankName: parsed.bank_name ?? null, + currency: parsed.currency ?? null, + creditLimit: parsed.credit_limit ?? null, + statementDate: parsed.statement_date ?? null, + statementDay: parsed.statement_day ?? null, + dueDate: parsed.due_date, + receivedDate: '2026-08-01', + allowCreate: true, + }) + + expect(cardRes.ok).toBe(true) + if (!cardRes.ok) return + + expect(cardRes.created).toBe(true) + const cardId = cardRes.cardId + + // 写入统一账单模型 + const billOutcome = await upsertBillForCard(d1, cardId, parsed, { trusted: true }) + expect(billOutcome.action).toBe('inserted') + + // 额度回填 + await syncCreditLimitFromBill(d1, cardId, parsed) + + // 验证 credit_accounts + const acc = await db + .prepare('SELECT * FROM credit_accounts WHERE holder_id = ?') + .bind('h1') + .first<{ + id: string + statement_mode: string + quota_mode: string + shared_credit_limit: number + primary_card_id: string + }>() + + expect(acc).toBeDefined() + expect(acc?.statement_mode).toBe('merged') + expect(acc?.quota_mode).toBe('shared') + expect(acc?.shared_credit_limit).toBe(80000) + expect(acc?.primary_card_id).toBe(cardId) + + // 验证 bills + const bill = await db + .prepare('SELECT * FROM bills WHERE id = ?') + .bind(billOutcome.billId) + .first<{ + id: string + account_id: string + card_id: string + bill_amount: number + due_date: string + bill_month: string + }>() + + expect(bill).toBeDefined() + expect(bill?.account_id).toBe(acc?.id) + expect(bill?.card_id).toBe(cardId) // 锚点卡 + expect(bill?.bill_amount).toBe(18888.88) + expect(bill?.due_date).toBe('2026-09-15') + expect(bill?.bill_month).toBe('2026-08') + + // 验证 bill_card_subtotals + const subs = ( + await db + .prepare('SELECT * FROM bill_card_subtotals WHERE bill_id = ?') + .bind(billOutcome.billId) + .all<{ card_tail: string; subtotal_amount: number; card_id: string }>() + ).results + + expect(subs).toHaveLength(1) + expect(subs[0].card_tail).toBe('6688') + expect(subs[0].subtotal_amount).toBe(18888.88) + expect(subs[0].card_id).toBe(cardId) + }) + + it('多卡账单入库与未知尾号处理:未知尾号只展示、不自动建卡,且总额不反向覆写', async () => { + const d1 = db as unknown as D1Database + + // 先建立已存在卡 6688 并归入招行合并账户 + const initCard = await findOrCreateCardForHolder(d1, { + holderId: 'h1', + cardTail: '6688', + statementDate: null, + bankName: '招商银行', + currency: 'CNY', + creditLimit: 80000, + dueDate: '2026-09-15', + receivedDate: '2026-08-01', + allowCreate: true, + }) + expect(initCard.ok).toBe(true) + if (!initCard.ok) return + + // 此时多卡账单到来(包含已知卡 6688 与新未知卡 7799) + const parsedMulti = parseCmbStatement(CMB_MULTI_CARD_SYNTHETIC) + expect(parsedMulti.card_subtotals).toHaveLength(2) + + // 路由找卡:由于账户已存在,无论给什么尾号,都对齐到既有合并账户的锚点卡 + const routeRes = await findOrCreateCardForHolder(d1, { + holderId: 'h1', + cardTail: parsedMulti.card_last4 ?? null, + statementDate: null, + bankName: '招商银行', + currency: 'CNY', + dueDate: parsedMulti.due_date, + receivedDate: '2026-08-01', + allowCreate: true, + }) + expect(routeRes.ok).toBe(true) + if (!routeRes.ok) return + expect(routeRes.created).toBe(false) + expect(routeRes.cardId).toBe(initCard.cardId) // 对齐锚点卡 + + // 入库 + const billOutcome = await upsertBillForCard(d1, routeRes.cardId, parsedMulti, { trusted: true }) + expect(billOutcome.action).toBe('inserted') + + // 铁律验证 1:未知尾号 7799 绝不自动在 credit_cards 建卡! + const allCards = ( + await db + .prepare('SELECT id, card_number_last4 FROM credit_cards WHERE holder_id = ?') + .bind('h1') + .all<{ id: string; card_number_last4: string }>() + ).results + expect(allCards).toHaveLength(1) + expect(allCards[0].card_number_last4).toBe('6688') + expect(allCards.some((c) => c.card_number_last4 === '7799')).toBe(false) + + // 铁律验证 2:未知尾号 7799 在 bill_card_subtotals 中如实呈现(card_id 为 NULL) + const subs = ( + await db + .prepare('SELECT card_tail, subtotal_amount, card_id FROM bill_card_subtotals WHERE bill_id = ? ORDER BY card_tail ASC') + .bind(billOutcome.billId) + .all<{ card_tail: string; subtotal_amount: number; card_id: string | null }>() + ).results + expect(subs).toHaveLength(2) + expect(subs[0].card_tail).toBe('6688') + expect(subs[0].subtotal_amount).toBe(15000) + expect(subs[0].card_id).toBe(initCard.cardId) + + expect(subs[1].card_tail).toBe('7799') + expect(subs[1].subtotal_amount).toBe(9500) + expect(subs[1].card_id).toBeNull() // 未知卡只展示,card_id 为 null + + // 铁律验证 3:总额以账单为权威,不反向覆写;未归卡差额通过 getBillDetail 透明呈现 + const detail = await getBillDetail(billOutcome.billId) + expect(detail.bill.bill_amount).toBe(25000) // 保持权威应还总额 + expect(detail.bill.subtotals).toHaveLength(2) + // 25,000 - (15,000 + 9,500) = 500 + expect(detail.bill.unallocated_amount).toBe(500) + }) + + it('跨年账单日期推导(12月账单 -> 次年1月还款)', () => { + const parsed = parseCmbStatement(CMB_YEAR_ROLLOVER_SYNTHETIC) + expect(parsed.bill_month).toBe('2026-12') + expect(parsed.due_date).toBe('2027-01-10') + }) + + // 本地真实样本验证 + const realSamplePath = '/tmp/wc-cmb-sample/cmb-statement-2026-08.txt' + const hasRealSample = fs.existsSync(realSamplePath) + + it.runIf(hasRealSample)('真实招行样本本地入库验证', async () => { + const content = fs.readFileSync(realSamplePath, 'utf8') + const parsed = parseCmbStatement(content) + + const d1 = db as unknown as D1Database + const cardRes = await findOrCreateCardForHolder(d1, { + holderId: 'h1', + cardTail: parsed.card_last4 ?? null, + bankName: parsed.bank_name ?? null, + currency: parsed.currency ?? null, + creditLimit: parsed.credit_limit ?? null, + statementDate: parsed.statement_date ?? null, + statementDay: parsed.statement_day ?? null, + dueDate: parsed.due_date, + receivedDate: '2026-07-28', + allowCreate: true, + }) + + expect(cardRes.ok).toBe(true) + if (!cardRes.ok) return + + const billOutcome = await upsertBillForCard(d1, cardRes.cardId, parsed, { trusted: true }) + await syncCreditLimitFromBill(d1, cardRes.cardId, parsed) + + const detail = await getBillDetail(billOutcome.billId) + // 结构断言:入库结果必须与解析值一致;真实金额/尾号不硬编码进仓库 + expect(detail.bill.bill_month).toBe(parsed.bill_month) + expect(detail.bill.bill_amount).toBe(parsed.bill_amount) + expect(detail.bill.min_payment).toBe(parsed.min_payment) + expect(detail.bill.due_date).toBe(parsed.due_date) + expect(detail.bill.subtotals).toHaveLength(parsed.card_subtotals?.length ?? 0) + const firstTail = parsed.card_subtotals?.[0]?.card_last4 ?? parsed.card_last4 + expect(detail.bill.subtotals?.[0]?.card_tail).toBe(firstTail) + expect(detail.bill.subtotals?.[0]?.subtotal_amount).toBe(parsed.card_subtotals?.[0]?.amount) + // 单卡样本:小计=账户总额,无未归卡差额 + if ((parsed.card_subtotals?.length ?? 0) === 1) { + expect(detail.bill.subtotals?.[0]?.subtotal_amount).toBe(parsed.bill_amount) + expect(detail.bill.unallocated_amount).toBeUndefined() + } + }) +}) diff --git a/lib/__tests__/credit-limit-override.test.ts b/lib/__tests__/credit-limit-override.test.ts new file mode 100644 index 0000000..f07e918 --- /dev/null +++ b/lib/__tests__/credit-limit-override.test.ts @@ -0,0 +1,146 @@ +import { describe, it, expect } from 'vitest' +import { getEffectiveCreditLimit, isCreditLimitManuallySet } from '../utils' +import { syncCreditLimitFromBill } from '../email-core/bills' +import { extractValidCreditLimit } from '../email-core/due-date' +import type { CreditCard } from '../types' + +describe('信用额度字段与持久化规则', () => { + describe('extractValidCreditLimit', () => { + it('正数返回数字,0 / 负数 / null / 空值一律视为未获取 (null)', () => { + expect(extractValidCreditLimit(50000)).toBe(50000) + expect(extractValidCreditLimit('30000')).toBe(30000) + expect(extractValidCreditLimit(0)).toBeNull() + expect(extractValidCreditLimit('0')).toBeNull() + expect(extractValidCreditLimit(-100)).toBeNull() + expect(extractValidCreditLimit(null)).toBeNull() + expect(extractValidCreditLimit(undefined)).toBeNull() + expect(extractValidCreditLimit('')).toBeNull() + expect(extractValidCreditLimit('NaN')).toBeNull() + }) + }) + + describe('getEffectiveCreditLimit 与 isCreditLimitManuallySet', () => { + it('未获取时(credit_limit 为 0 且无 override)返回 null,绝不伪装为 0', () => { + const card: Pick = { + credit_limit: 0, + credit_limit_override: null, + } + expect(getEffectiveCreditLimit(card)).toBeNull() + expect(isCreditLimitManuallySet(card)).toBe(false) + }) + + it('邮件或建卡回填正数 credit_limit 时,生效额度为该值,未标记手动设置', () => { + const card: Pick = { + credit_limit: 20000, + credit_limit_override: null, + } + expect(getEffectiveCreditLimit(card)).toBe(20000) + expect(isCreditLimitManuallySet(card)).toBe(false) + }) + + it('用户手动输入 credit_limit_override 时,优先级最高且标记已手动设置', () => { + const card: Pick = { + credit_limit: 20000, + credit_limit_override: 60000, + } + expect(getEffectiveCreditLimit(card)).toBe(60000) + expect(isCreditLimitManuallySet(card)).toBe(true) + }) + + it('手动覆盖设为 0 或非法值时,回落至 credit_limit 或 null', () => { + const cardWithFallback: Pick = { + credit_limit: 15000, + credit_limit_override: 0, + } + expect(getEffectiveCreditLimit(cardWithFallback)).toBe(15000) + expect(isCreditLimitManuallySet(cardWithFallback)).toBe(false) + + const cardUnacquired: Pick = { + credit_limit: 0, + credit_limit_override: 0, + } + expect(getEffectiveCreditLimit(cardUnacquired)).toBeNull() + expect(isCreditLimitManuallySet(cardUnacquired)).toBe(false) + }) + }) + + describe('syncCreditLimitFromBill (邮件同步信用额度)', () => { + // 模拟轻量 D1 prepare/bind/first/run 行为 + function createMockDb(initialCard: { credit_limit: number | null; credit_limit_override?: number | null }) { + const card = { ...initialCard } + let updatedLimit: number | null = null + + const db = { + prepare: (sql: string) => ({ + bind: (...args: unknown[]) => ({ + first: async () => { + if (sql.includes('SELECT credit_limit')) { + return card as T + } + return null as T + }, + run: async () => { + if (sql.includes('UPDATE credit_cards SET credit_limit')) { + updatedLimit = Number(args[0]) + card.credit_limit = updatedLimit + } + return { success: true } + }, + }), + }), + getCard: () => card, + getUpdatedLimit: () => updatedLimit, + } + return db + } + + it('卡片当前为未获取(0 且无 override)时,邮件包含确切额度则更新回填', async () => { + const mock = createMockDb({ credit_limit: 0, credit_limit_override: null }) + const changed = await syncCreditLimitFromBill(mock as unknown as D1Database, 'c1', { + is_bill: true, + credit_limit: 80000, + }) + expect(changed).toBe(true) + expect(mock.getUpdatedLimit()).toBe(80000) + }) + + it('卡片已有用户手动设置(credit_limit_override)时,邮件同步绝不覆盖', async () => { + const mock = createMockDb({ credit_limit: 50000, credit_limit_override: 50000 }) + const changed = await syncCreditLimitFromBill(mock as unknown as D1Database, 'c1', { + is_bill: true, + credit_limit: 100000, + }) + expect(changed).toBe(false) + expect(mock.getUpdatedLimit()).toBeNull() + expect(mock.getCard().credit_limit).toBe(50000) + }) + + it('卡片已有已获取额度时,邮件同步不随意覆盖', async () => { + const mock = createMockDb({ credit_limit: 30000, credit_limit_override: null }) + const changed = await syncCreditLimitFromBill(mock as unknown as D1Database, 'c1', { + is_bill: true, + credit_limit: 50000, + }) + expect(changed).toBe(false) + expect(mock.getUpdatedLimit()).toBeNull() + }) + + it('邮件中额度为 0、缺失或非正数时,不触碰卡片', async () => { + const mock = createMockDb({ credit_limit: 0, credit_limit_override: null }) + const changed = await syncCreditLimitFromBill(mock as unknown as D1Database, 'c1', { + is_bill: true, + credit_limit: 0, + }) + expect(changed).toBe(false) + expect(mock.getUpdatedLimit()).toBeNull() + }) + + it('card 具备 credit_limit_override 时 getEffectiveCreditLimit 正确生效且保存时能保留', () => { + const cardFromLoader: Pick = { + credit_limit: 10000, + credit_limit_override: 30000, + } + expect(getEffectiveCreditLimit(cardFromLoader)).toBe(30000) + }) + }) +}) diff --git a/lib/__tests__/due-date-resolution.test.ts b/lib/__tests__/due-date-resolution.test.ts new file mode 100644 index 0000000..5cd7098 --- /dev/null +++ b/lib/__tests__/due-date-resolution.test.ts @@ -0,0 +1,267 @@ +import { describe, it, expect } from 'vitest' +import { + isExactDueDate, + evaluateParsedBillDueDate, + DUE_DATE_ISSUE_LABELS, +} from '../email-core/due-date' +import type { BillParseResult } from '../email-core/types' +import { + buildDueDateReasonReport, + resolveCardDueDate, + type CardForDueDateSummary, + type BillForDueDateSummary, +} from '../due-date-summary' +import type { EmailParseLog } from '../types' + +describe('还款日确切性与四类缺失原因判定', () => { + describe('isExactDueDate', () => { + it('正确识别真日历日 YYYY-MM-DD', () => { + expect(isExactDueDate('2026-09-25')).toBe(true) + expect(isExactDueDate('2026-02-28')).toBe(true) + expect(isExactDueDate('2024-02-29')).toBe(true) // 闰年合法 + }) + + it('拦截非法日历日(如 2 月 30 日、4 月 31 日)', () => { + expect(isExactDueDate('2026-02-30')).toBe(false) + expect(isExactDueDate('2026-04-31')).toBe(false) + expect(isExactDueDate('2026-13-01')).toBe(false) + }) + + it('拦截模糊日期、相对描述、不完整日期及非字符串', () => { + expect(isExactDueDate('账单日后20天')).toBe(false) + expect(isExactDueDate('免息期25天')).toBe(false) + expect(isExactDueDate('每月15日')).toBe(false) + expect(isExactDueDate('2026-09')).toBe(false) + expect(isExactDueDate('09-25')).toBe(false) + expect(isExactDueDate('')).toBe(false) + expect(isExactDueDate(null)).toBe(false) + expect(isExactDueDate(undefined)).toBe(false) + expect(isExactDueDate(12345)).toBe(false) + }) + }) + + describe('evaluateParsedBillDueDate', () => { + it('非账单或缺少月份/金额时,拒绝入库', () => { + expect(evaluateParsedBillDueDate({ is_bill: false }).ok).toBe(false) + expect(evaluateParsedBillDueDate({ is_bill: true, bill_amount: 100 } as unknown as BillParseResult).ok).toBe(false) + }) + + it('0 元账单(本期无需还款):允许缺还款日,返回 dueDate 为 null', () => { + const res = evaluateParsedBillDueDate({ + is_bill: true, + bill_month: '2026-09', + bill_amount: 0, + }) + expect(res.ok).toBe(true) + if (res.ok) { + expect(res.zeroBill).toBe(true) + expect(res.dueDate).toBeNull() + } + }) + + it('0 元账单若有确切还款日,则正常保留', () => { + const res = evaluateParsedBillDueDate({ + is_bill: true, + bill_month: '2026-09', + bill_amount: 0, + due_date: '2026-10-15', + }) + expect(res.ok).toBe(true) + if (res.ok) { + expect(res.dueDate).toBe('2026-10-15') + } + }) + + it('非 0 元账单有确切还款日:校验通过', () => { + const res = evaluateParsedBillDueDate({ + is_bill: true, + bill_month: '2026-09', + bill_amount: 5200, + due_date: '2026-10-25', + }) + expect(res.ok).toBe(true) + if (res.ok) { + expect(res.dueDate).toBe('2026-10-25') + } + }) + + it('非 0 元账单缺少还款日:精确归类为 missing_in_email', () => { + const res = evaluateParsedBillDueDate({ + is_bill: true, + bill_month: '2026-09', + bill_amount: 5200, + due_date: null, + }) + expect(res.ok).toBe(false) + if (!res.ok) { + expect(res.kind).toBe('missing_in_email') + expect(res.reason).toContain('邮件未提供确切还款日') + } + }) + + it('非 0 元账单日期模糊或仅有宽限期:精确归类为 ambiguous_or_grace_only,严禁编造日期', () => { + const res1 = evaluateParsedBillDueDate({ + is_bill: true, + bill_month: '2026-09', + bill_amount: 5200, + due_date: '账单日后20天', + }) + expect(res1.ok).toBe(false) + if (!res1.ok) { + expect(res1.kind).toBe('ambiguous_or_grace_only') + } + + const res2 = evaluateParsedBillDueDate({ + is_bill: true, + bill_month: '2026-09', + bill_amount: 5200, + due_date_status: 'ambiguous_or_grace_only', + }) + expect(res2.ok).toBe(false) + if (!res2.ok) { + expect(res2.kind).toBe('ambiguous_or_grace_only') + } + }) + }) + + describe('resolveCardDueDate & buildDueDateReasonReport', () => { + const cardTemplate: CardForDueDateSummary = { + id: 'card_招行', + holder_id: 'holder_1', + bank_name: '招商银行', + card_name: '经典白', + card_number_last4: '8888', + billing_day: 5, + card_type: 'credit', + } + + it('存在账单邮件确切还款日时,返回确切日期', () => { + const bills: BillForDueDateSummary[] = [ + { + id: 'b1', + card_id: 'card_招行', + bill_month: '2026-09', + bill_amount: 1000, + due_date: '2026-09-25', + }, + ] + const res = resolveCardDueDate({ + card: cardTemplate, + bills, + matchedIssues: [], + hasAnyUserSyncActivity: true, + }) + expect(res.has_exact_due_date).toBe(true) + expect(res.exact_due_date).toBe('2026-09-25') + expect(res.exact_source).toBe('bill_email') + }) + + it('人工确认覆盖账单日期(due_date_override)时,优先采用人工覆盖', () => { + const bills: BillForDueDateSummary[] = [ + { + id: 'b1', + card_id: 'card_招行', + bill_month: '2026-09', + bill_amount: 1000, + due_date: '2026-09-25', + due_date_override: '2026-09-28', + }, + ] + const res = resolveCardDueDate({ + card: cardTemplate, + bills, + matchedIssues: [], + hasAnyUserSyncActivity: true, + }) + expect(res.has_exact_due_date).toBe(true) + expect(res.exact_due_date).toBe('2026-09-28') + expect(res.exact_source).toBe('bill_override') + }) + + it('无账单日但有匹配邮件日志时:精准归入四类原因并返回依据', () => { + const res = resolveCardDueDate({ + card: cardTemplate, + bills: [], + matchedIssues: [ + { + source: 'email_parse_log', + id: 'log_1', + created_at: '2026-10-01', + from_email: 'cmb@cmbchina.com', + subject: '招商银行信用卡电子账单', + bank_name: '招商银行', + card_last4: '8888', + reason_code: 'ambiguous_or_grace_only', + reason_label: DUE_DATE_ISSUE_LABELS.ambiguous_or_grace_only, + detail: '邮件仅含宽限期或还款日期模糊', + }, + ], + hasAnyUserSyncActivity: true, + }) + expect(res.has_exact_due_date).toBe(false) + expect(res.exact_due_date).toBeNull() + expect(res.reason_code).toBe('ambiguous_or_grace_only') + expect(res.summary).toContain('日期模糊/只有宽限期 1 封') + expect(res.email_evidences.length).toBe(1) + }) + + it('无账单且无邮件时归类为 unsynced(未同步),绝不编造具体日历日', () => { + const res = resolveCardDueDate({ + card: cardTemplate, + bills: [], + matchedIssues: [], + hasAnyUserSyncActivity: false, + }) + expect(res.has_exact_due_date).toBe(false) + expect(res.exact_due_date).toBeNull() + expect(res.reason_code).toBe('unsynced') + expect(res.reason_label).toBe(DUE_DATE_ISSUE_LABELS.unsynced) + }) + + it('buildDueDateReasonReport 聚合多卡与邮件日志生成统计报表', () => { + const cards: CardForDueDateSummary[] = [ + { ...cardTemplate, id: 'c1', card_number_last4: '1111' }, + { ...cardTemplate, id: 'c2', card_number_last4: '2222' }, + ] + const bills: BillForDueDateSummary[] = [ + { + id: 'b1', + card_id: 'c1', + bill_month: '2026-09', + bill_amount: 800, + due_date: '2026-09-25', + }, + ] + const emailLogs: EmailParseLog[] = [ + { + id: 'l1', + user_id: 'u1', + created_at: '2026-10-01', + from_email: 'cmb@cmbchina.com', + subject: '招商银行信用卡账单 (2222)', + status: 'skipped', + error_msg: '邮件未提供确切还款日,未写入账单', + raw_ai_response: JSON.stringify({ + is_bill: true, + card_last4: '2222', + bank_name: '招商银行', + due_date_status: 'missing', + }), + }, + ] + + const report = buildDueDateReasonReport({ + cards, + bills, + emailLogs, + }) + + expect(report.cards_total).toBe(2) + expect(report.cards_with_exact_due_date).toBe(1) + expect(report.cards_missing_exact_due_date).toBe(1) + expect(report.by_reason.missing_in_email).toBe(1) + expect(report.cards[0].resolution.has_exact_due_date).toBe(true) + expect(report.cards[1].resolution.reason_code).toBe('missing_in_email') + }) + }) +}) diff --git a/lib/__tests__/modal-group-server-review-r2.test.ts b/lib/__tests__/modal-group-server-review-r2.test.ts new file mode 100644 index 0000000..3006e47 --- /dev/null +++ b/lib/__tests__/modal-group-server-review-r2.test.ts @@ -0,0 +1,147 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { createOpportunityDb } from "./helpers/sqlite-d1"; +import { setDb } from "../db"; +import { createCard, updateCard } from "../api/cards.server"; +import { mergeCardsIntoAccount } from "../api/accounts.server"; +import { createHolder } from "../api/holders.server"; + +describe("PR #55 Review R2 - Server Regressions (High 1, Medium 6, Medium 7)", () => { + let db: ReturnType; + + beforeEach(async () => { + db = createOpportunityDb(); + setDb(db as unknown as D1Database); + + await db.exec(` + INSERT INTO users (id, email, password_hash) VALUES + ('u1', 'u1@example.com', 'h1'); + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES + ('h1', 'u1', 'u1', '持卡人甲'); + INSERT INTO banks (id, name, statement_mode, quota_mode) VALUES + ('b_cmb', '招商银行', 'merged', 'shared'), + ('b_icbc', '中国工商银行', 'independent', 'independent'), + ('b_empty', '新合作银行', 'independent', 'independent'); + INSERT INTO card_products (id, bank_id, bank_name, card_name, currency) VALUES + ('cp_cmb', 'b_cmb', '招商银行', '经典白金卡', 'CNY'), + ('cp_icbc', 'b_icbc', '中国工商银行', '工行牡丹卡', 'CNY'); + `); + }); + + afterEach(() => { + setDb(null); + db.close(); + }); + + it("High 1: mergeCardsIntoAccount rejects cross-bank merge (防御纵深拒绝跨行)", async () => { + const cardCmb = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 50000, + }); + const cardIcbc = await createCard({ + holder_id: "h1", + card_product_id: "cp_icbc", + billing_day: 5, + credit_limit: 30000, + }); + + expect(cardCmb.account_id).toBeTruthy(); + expect(cardIcbc.account_id).toBeTruthy(); + + await expect( + mergeCardsIntoAccount(cardCmb.account_id!, [cardIcbc.id]), + ).rejects.toThrow("不可跨银行合并信用卡至同一账户"); + }); + + it("Medium 6: updateCard with empty product bank dynamically ensures default product (无产品银行自动补全默认产品)", async () => { + const card = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 50000, + }); + + // 切换到无卡产品的新银行 b_empty,客户端不传 card_product_id + const updated = await updateCard(card.id, { + bank_id: "b_empty", + }); + + expect(updated.card_product_id).toBe("cp_default_b_empty"); + expect(updated.card_product?.bank_id).toBe("b_empty"); + expect(updated.card_product?.card_name).toBe("标准信用卡"); + }); + + it("Medium 7: createCard & updateCard reject invalid override due rules (还款规则范围校验)", async () => { + // 1. after_billing 负数天数被拒绝 + await expect( + createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 50000, + override_due_type: "after_billing", + override_due_value: -1, + }), + ).rejects.toThrow("账单日后还款天数必须大于或等于 0"); + + // 2. fixed 固定日 < 1 或 > 31 被拒绝 + await expect( + createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 50000, + override_due_type: "fixed", + override_due_value: 0, + }), + ).rejects.toThrow("固定还款日必须在 1 到 31 之间"); + + await expect( + createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 50000, + override_due_type: "fixed", + override_due_value: 32, + }), + ).rejects.toThrow("固定还款日必须在 1 到 31 之间"); + + // 3. 启用规则却不传值被拒绝 + await expect( + createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 50000, + override_due_type: "after_billing", + override_due_value: undefined, + }), + ).rejects.toThrow("启用自定义还款规则时必须提供有效的还款日数值"); + + // 4. updateCard 同样受校验保护 + const card = await createCard({ + holder_id: "h1", + card_product_id: "cp_cmb", + billing_day: 5, + credit_limit: 50000, + }); + + await expect( + updateCard(card.id, { + override_due_type: "fixed", + override_due_value: 40, + }), + ).rejects.toThrow("固定还款日必须在 1 到 31 之间"); + }); + + it("createHolder rejects empty or whitespace name", async () => { + await expect( + createHolder({ + name: " ", + avatar_color: "#7aadff", + }), + ).rejects.toThrow("持卡人姓名不能为空"); + }); +}); diff --git a/lib/__tests__/payable-cycles-and-categories.test.ts b/lib/__tests__/payable-cycles-and-categories.test.ts new file mode 100644 index 0000000..e7bc18f --- /dev/null +++ b/lib/__tests__/payable-cycles-and-categories.test.ts @@ -0,0 +1,573 @@ +import { readdirSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeAll, describe, expect, it } from 'vitest' +import { POST as pullHandler } from '../../app/api/sync/pull/route' +import { setDb, setWorkerEnv } from '../db/client' +import { createSessionValue } from '../session' +import { RpcDomainError } from '../api/errors' +import { + PAYABLE_CATEGORIES, + categoryLabel, + dedupeCustomCategories, + payableCycleLabel, +} from '../api/payables.shared' +import { + createRecurringPayable, + deleteRecurringPayable, + getPayableCustomCategories, + getRecurringPayables, + payRecurringPayable, + savePayableCustomCategory, + updateRecurringPayable, +} from '../api/payables.server' +import { + nextPayableDueDate, + nextPayablePeriodOf, + payableDueDate, + payablePeriodOf, + payableToSortCard, +} from '../utils' +import { + SQLITE_D1_MIGRATIONS_DIR, + createOpportunityDb, + createSqliteD1, + type SqliteD1, +} from './helpers/sqlite-d1' + +const fmt = (d: Date) => + `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` + +describe('payable cycles (monthly / every_n_months / yearly) & custom categories', () => { + const openDbs: SqliteD1[] = [] + + beforeAll(() => { + setWorkerEnv({ SESSION_SECRET: 'test-payable-cycles-secret-at-least-16-chars' }) + }) + + afterEach(() => { + for (const db of openDbs.splice(0)) db.close() + }) + + function mountDb(): SqliteD1 { + const db = createOpportunityDb() + openDbs.push(db) + db.exec(` + INSERT INTO users (id, email, password_hash) VALUES + ('u1', 'u1@example.com', 'hash'), + ('u2', 'u2@example.com', 'hash'); + `) + setDb(db as unknown as D1Database) + return db + } + + describe('0030 迁移对旧版「每月」数据的无损兼容', () => { + it('先跑 0001..0029 写入旧数据,再执行 0030:旧记录默认 monthly 且状态/还款不变', async () => { + const db = createSqliteD1() + openDbs.push(db) + const files = readdirSync(SQLITE_D1_MIGRATIONS_DIR) + .filter(f => f.endsWith('.sql')) + .sort() + const migration0030 = files.find(f => f.startsWith('0030_')) + expect(migration0030).toBe('0030_payable_cycles_and_custom_categories.sql') + + for (const file of files) { + if (file >= migration0030!) break + db.exec(readFileSync(join(SQLITE_D1_MIGRATIONS_DIR, file), 'utf8')) + } + + db.exec(` + INSERT INTO users (id, email, password_hash) VALUES ('u-legacy', 'legacy@example.com', 'hash'); + INSERT INTO recurring_payables (id, created_by, name, category, amount, currency, due_day, bank_name, bank_account) + VALUES + ('leg-rent', 'u-legacy', '深圳房租', 'rent', 4500, 'CNY', 15, '招商银行', '62258800'), + ('leg-eur', 'u-legacy', '德国服务器', 'utility', 29.9, 'EUR', 28, NULL, NULL); + INSERT INTO recurring_payable_payments (id, payable_id, period, amount, paid_at) + VALUES ('pay-1', 'leg-rent', '2026-10', 4500, '2026-10-14'); + `) + + db.exec(readFileSync(join(SQLITE_D1_MIGRATIONS_DIR, migration0030!), 'utf8')) + setDb(db as unknown as D1Database) + + const list = await getRecurringPayables('u-legacy', new Date(2026, 9, 16)) + expect(list).toHaveLength(2) + + const rent = list.find(p => p.id === 'leg-rent')! + expect(rent).toMatchObject({ + name: '深圳房租', + category: 'rent', + custom_category: null, + cycle_type: 'monthly', + cycle_months: 1, + due_month: null, + anchor_period: null, + due_day: 15, + period: '2026-10', + due_date: '2026-10-15', + paid_amount: 4500, + status: 'paid', + }) + + const eur = list.find(p => p.id === 'leg-eur')! + expect(eur).toMatchObject({ + currency: 'EUR', + cycle_type: 'monthly', + cycle_months: 1, + period: '2026-10', + due_date: '2026-10-28', + status: 'unpaid', + }) + + // D1 SQLite CHECK 约束兜底拦截非法周期字段 + expect(() => + db.exec( + "INSERT INTO recurring_payables (id,created_by,name,amount,due_day,cycle_type) VALUES ('bad1','u-legacy','x',10,5,'weekly')" + ) + ).toThrow() + expect(() => + db.exec( + "INSERT INTO recurring_payables (id,created_by,name,amount,due_day,cycle_type,cycle_months) VALUES ('bad2','u-legacy','x',10,5,'every_n_months',0)" + ) + ).toThrow() + expect(() => + db.exec( + "INSERT INTO recurring_payables (id,created_by,name,amount,due_day,cycle_type,due_month) VALUES ('bad3','u-legacy','x',10,5,'yearly',13)" + ) + ).toThrow() + }) + }) + + describe('三种周期(每月 / 每 X 月 / 每年)校验与下一次推导', () => { + it('每 X 月:严格校验 X 为合理整数(2–60),拒绝 0/负数/1/小数/超大值', async () => { + mountDb() + + for (const bad of [0, -1, -6, 1, 1.5, 3.2, Number.NaN, 61, 999, null, undefined, '3' as never]) { + await expect( + createRecurringPayable({ + created_by: 'u1', + name: '季度物业', + category: 'utility', + amount: 900, + currency: 'CNY', + cycle_type: 'every_n_months', + cycle_months: bad as number, + due_day: 10, + }), + `cycle_months=${String(bad)} 应被拒绝` + ).rejects.toMatchObject({ + name: 'RpcDomainError', + code: 'VALIDATION_FAILED', + status: 400, + }) + } + + const valid = await createRecurringPayable( + { + created_by: 'u1', + name: '押一付三房租', + category: 'rent', + amount: 12000, + currency: 'CNY', + cycle_type: 'every_n_months', + cycle_months: 3, + due_day: 15, + anchor_period: '2026-10', + }, + new Date(2026, 9, 5) + ) + expect(valid).toMatchObject({ + cycle_type: 'every_n_months', + cycle_months: 3, + anchor_period: '2026-10', + period: '2026-10', + due_date: '2026-10-15', + status: 'unpaid', + }) + expect(payableCycleLabel(valid)).toBe('每 3 个月 · 15 日') + }) + + it('每 X 月:未付跨月保持原账期并标逾期,付清后按 +X 月推导下期并遵守 30 天滚动窗口', async () => { + mountDb() + + const created = await createRecurringPayable( + { + created_by: 'u1', + name: '季度宽带', + category: 'utility', + amount: 600, + currency: 'CNY', + cycle_type: 'every_n_months', + cycle_months: 3, + due_day: 15, + anchor_period: '2026-10', + }, + new Date(2026, 9, 5) + ) + + // 到了 11 月仍未付 10 月那期:必须保留 2026-10 逾期,绝不跳到 11 月或 1 月掩盖逾期 + const novUnpaid = (await getRecurringPayables('u1', new Date(2026, 10, 10)))[0] + expect(novUnpaid.period).toBe('2026-10') + expect(novUnpaid.due_date).toBe('2026-10-15') + expect(novUnpaid.status).toBe('overdue') + expect(novUnpaid.days_until_due).toBe(-26) + + // 补登记还款:写进 2026-10,距下期 2027-01-15 还有 66 天 >= 30,保持 paid 待出账 + const paid = await payRecurringPayable(created.id, 600, 'Q4 宽带', new Date(2026, 10, 10)) + expect(paid.period).toBe('2026-10') + expect(paid.status).toBe('paid') + + // 12 月 20 日:距下期 2027-01-15 剩 26 天 < 30,自动滚动到 2027-01 待还款 + const decWindow = (await getRecurringPayables('u1', new Date(2026, 11, 20)))[0] + expect(decWindow.period).toBe('2027-01') + expect(decWindow.due_date).toBe('2027-01-15') + expect(decWindow.status).toBe('unpaid') + expect(decWindow.paid_amount).toBe(0) + + // 短月月末收拢:2025-11 的 31 日 + 3 个月 → 2026-02-28 + expect( + fmt( + nextPayableDueDate(31, '2025-11', { + cycle_type: 'every_n_months', + cycle_months: 3, + }) + ) + ).toBe('2026-02-28') + }) + + it('每年:校验月份 1–12,按同月同日推导下一次(含闰年 2 月 29 日与新建已过月跨年锚定)', async () => { + mountDb() + + for (const badMonth of [0, 13, -1, 6.5, null, undefined]) { + await expect( + createRecurringPayable({ + created_by: 'u1', + name: '重疾险', + category: 'insurance', + amount: 8000, + currency: 'HKD', + cycle_type: 'yearly', + due_month: badMonth as number, + due_day: 20, + }) + ).rejects.toBeInstanceOf(RpcDomainError) + } + + // 11 月 4 日新建每年 3 月 15 日的保险:今年 3-15 已过,首期自动定在明年同月同日 2027-03-15 + const futureYearly = await createRecurringPayable( + { + created_by: 'u1', + name: '车险续保', + category: 'insurance', + amount: 4200, + currency: 'CNY', + cycle_type: 'yearly', + due_month: 3, + due_day: 15, + }, + new Date(2026, 10, 4) + ) + expect(futureYearly.period).toBe('2027-03') + expect(futureYearly.due_date).toBe('2027-03-15') + expect(futureYearly.status).toBe('unpaid') + expect(payableCycleLabel(futureYearly)).toBe('每年 3 月 15 日') + + // 6 月 1 日新建每年 6 月 18 日的年费:当年尚未到期,首期为 2026-06-18 + const thisYear = await createRecurringPayable( + { + created_by: 'u1', + name: '云服务器年付', + category: 'utility', + amount: 199, + currency: 'USD', + cycle_type: 'yearly', + due_month: 6, + due_day: 18, + }, + new Date(2026, 5, 1) + ) + expect(thisYear.period).toBe('2026-06') + expect(thisYear.due_date).toBe('2026-06-18') + + // 登记付款后,下一次严格推导到 2027-06-18(同月同日) + await payRecurringPayable(thisYear.id, 199, '2026 年费', new Date(2026, 5, 18)) + const afterPaid = (await getRecurringPayables('u1', new Date(2026, 10, 4))).find( + p => p.id === thisYear.id + )! + expect(afterPaid.status).toBe('paid') + expect(afterPaid.period).toBe('2026-06') + expect(nextPayablePeriodOf(afterPaid.period, afterPaid)).toBe('2027-06') + expect(fmt(nextPayableDueDate(afterPaid.due_day, afterPaid.period, afterPaid))).toBe( + '2027-06-18' + ) + + // 到 2027-05-25(距 2027-06-18 仅 24 天 < 30),滚动到 2027-06 待还款 + const nextYearWindow = (await getRecurringPayables('u1', new Date(2027, 4, 25))).find( + p => p.id === thisYear.id + )! + expect(nextYearWindow.period).toBe('2027-06') + expect(nextYearWindow.due_date).toBe('2027-06-18') + expect(nextYearWindow.status).toBe('unpaid') + + // 闰年 2 月 29 日:2028-02-29 → 2029-02-28 → ... → 2032-02-29 + const leapSpec = { cycle_type: 'yearly' as const, due_month: 2, due_day: 29, anchor_period: '2028-02' } + expect(fmt(payableDueDate(29, payablePeriodOf(new Date(2028, 1, 1), leapSpec)))).toBe('2028-02-29') + expect(fmt(nextPayableDueDate(29, '2028-02', leapSpec))).toBe('2029-02-28') + expect(fmt(nextPayableDueDate(29, '2031-02', leapSpec))).toBe('2032-02-29') + + // 排序卡适配同样按真实周期算 nextDueDate + const sortCard = payableToSortCard(afterPaid) + expect(fmt(new Date(sortCard.nextDueDate))).toBe('2027-06-18') + }) + + it('编辑切换周期时清理旧周期专属字段,不留脏状态', async () => { + mountDb() + const created = await createRecurringPayable( + { + created_by: 'u1', + name: '会员费', + category: 'other', + amount: 300, + currency: 'CNY', + cycle_type: 'every_n_months', + cycle_months: 6, + due_day: 10, + anchor_period: '2026-08', + }, + new Date(2026, 7, 1) + ) + + const toYearly = await updateRecurringPayable( + created.id, + { cycle_type: 'yearly', due_month: 12, due_day: 25 }, + new Date(2026, 10, 4) + ) + expect(toYearly).toMatchObject({ + cycle_type: 'yearly', + cycle_months: 12, + due_month: 12, + due_day: 25, + anchor_period: '2026-12', + }) + + const backToMonthly = await updateRecurringPayable( + created.id, + { cycle_type: 'monthly', due_day: 8 }, + new Date(2026, 10, 4) + ) + expect(backToMonthly).toMatchObject({ + cycle_type: 'monthly', + cycle_months: 1, + due_month: null, + anchor_period: null, + due_day: 8, + }) + }) + }) + + describe('自定义分类:保存、去重、持久化、下次可选与预设/iOS 兼容', () => { + it('保存新自定义分类后去重持久化,删除原支出后下次仍可选,且 category 保持 iOS 兼容枚举 other', async () => { + mountDb() + + expect(PAYABLE_CATEGORIES.map(c => c.value)).toEqual([ + 'rent', + 'loan', + 'utility', + 'insurance', + 'other', + ]) + + const created = await createRecurringPayable({ + created_by: 'u1', + name: '电信千兆宽带', + category: 'other', + custom_category: ' 宽带网络 ', + amount: 199, + currency: 'CNY', + due_day: 1, + }) + // category 必须保持 5 个预设枚举之一(other),不破坏旧版 iOS PayableCategory 解码 + expect(created.category).toBe('other') + expect(created.custom_category).toBe('宽带网络') + expect(categoryLabel(created.category, created.custom_category)).toBe('宽带网络') + + // 大小写与多余空白重复提交:去重不重复入库,统一复用首次保存的展示写法 + await savePayableCustomCategory('u1', 'iCloud 订阅') + const second = await createRecurringPayable({ + created_by: 'u1', + name: '苹果云空间', + category: 'other', + custom_category: ' icloud 订阅 ', + amount: 68, + currency: 'CNY', + due_day: 12, + }) + expect(second.custom_category).toBe('iCloud 订阅') + + // 输入预设分类同名值(如「房租」或「LOAN」):自动归一到预设分类,不污染自定义词典 + const matchedPreset = await createRecurringPayable({ + created_by: 'u1', + name: '新公寓', + category: 'other', + custom_category: ' 房租 ', + amount: 5000, + currency: 'CNY', + due_day: 5, + }) + expect(matchedPreset.category).toBe('rent') + expect(matchedPreset.custom_category).toBeNull() + + expect(await getPayableCustomCategories('u1')).toEqual(['宽带网络', 'iCloud 订阅']) + // 用户隔离:u2 看不到 u1 的自定义分类 + expect(await getPayableCustomCategories('u2')).toEqual([]) + + // 删除使用该分类的固定支出后,持久化的自定义分类依然保留供下次选择 + await deleteRecurringPayable(created.id) + await deleteRecurringPayable(second.id) + expect(await getPayableCustomCategories('u1')).toEqual(['宽带网络', 'iCloud 订阅']) + + // 纯函数去重契约 + expect( + dedupeCustomCategories([' 宽带 ', '宽带', '房租', 'rent', 'iCloud', 'ICLOUD', '']) + ).toEqual(['宽带', 'iCloud']) + }) + + it('拒绝空串或超长自定义分类名称', async () => { + mountDb() + await expect(savePayableCustomCategory('u1', ' ')).rejects.toMatchObject({ + code: 'VALIDATION_FAILED', + status: 400, + }) + await expect(savePayableCustomCategory('u1', '分'.repeat(31))).rejects.toMatchObject({ + code: 'VALIDATION_FAILED', + status: 400, + }) + }) + }) + + describe('sync/pull 增量同步与旧客户端忽略新字段兼容', () => { + it('下发新增周期列与自定义分类表变更,且严格旧客户端解码器忽略未知字段/表不会崩溃', async () => { + mountDb() + + const payable = await createRecurringPayable( + { + created_by: 'u1', + name: '香港保单', + category: 'other', + custom_category: '跨境医疗险', + amount: 1500, + currency: 'HKD', + cycle_type: 'yearly', + due_month: 9, + due_day: 20, + }, + new Date(2026, 8, 1) + ) + + const token = await createSessionValue({ + id: 'u1', + email: 'u1@example.com', + name: 'u1', + role: 'admin', + created_at: '2026-10-01T00:00:00Z', + }) + + const res = await pullHandler( + new Request('https://app.all-bill.com/api/sync/pull', { + method: 'POST', + headers: { Authorization: `Bearer ${token}` }, + body: JSON.stringify({ cursor: 0 }), + }) + ) + expect(res.status).toBe(200) + const payload = (await res.json()) as { + cursor: number + has_more: boolean + changes: Array<{ tbl: string; row_id: string; op: string; row?: Record }> + } + + const payableChange = payload.changes.find( + c => c.tbl === 'recurring_payables' && c.row_id === payable.id + ) + expect(payableChange).toMatchObject({ + tbl: 'recurring_payables', + row_id: payable.id, + op: 'upsert', + row: { + id: payable.id, + category: 'other', + custom_category: '跨境医疗险', + cycle_type: 'yearly', + cycle_months: 12, + due_month: 9, + due_day: 20, + anchor_period: '2026-09', + }, + }) + + const customCatChange = payload.changes.find(c => c.tbl === 'payable_custom_categories') + expect(customCatChange).toMatchObject({ + tbl: 'payable_custom_categories', + op: 'upsert', + row: { + user_id: 'u1', + name: '跨境医疗险', + normalized_name: '跨境医疗险', + }, + }) + + // 模拟旧客户端(旧版 iOS SyncEngine + PayableItem 严格枚举解码器): + // 1) SyncEngine 跳过未知表 payable_custom_categories,不抛错且正常推进 cursor; + // 2) RPC / 已知表解码器只识别旧字段,要求 category 属于 5 枚举、due_day 属于 1..31、status 属于 3 枚举。 + const legacySupportedCategories = new Set(['rent', 'loan', 'utility', 'insurance', 'other']) + const legacySupportedStatuses = new Set(['unpaid', 'paid', 'overdue']) + + for (const change of payload.changes) { + if (change.tbl === 'recurring_payables' && change.op === 'upsert') { + const r = change.row! + expect(typeof r.id).toBe('string') + expect(legacySupportedCategories.has(String(r.category))).toBe(true) + expect(Number.isInteger(r.due_day) && Number(r.due_day) >= 1 && Number(r.due_day) <= 31).toBe( + true + ) + } + } + + const rpcItems = await getRecurringPayables('u1', new Date(2026, 8, 1)) + for (const item of rpcItems) { + expect(legacySupportedCategories.has(item.category)).toBe(true) + expect(legacySupportedStatuses.has(item.status)).toBe(true) + expect(item.due_day).toBeGreaterThanOrEqual(1) + expect(item.due_day).toBeLessThanOrEqual(31) + } + + // 另一用户 u2 reconcile u1 的自定义分类返回 delete,严防越权读取 + const tokenU2 = await createSessionValue({ + id: 'u2', + email: 'u2@example.com', + name: 'u2', + role: 'member', + created_at: '2026-10-01T00:00:00Z', + }) + const reconcileRes = await pullHandler( + new Request('https://app.all-bill.com/api/sync/pull', { + method: 'POST', + headers: { Authorization: `Bearer ${tokenU2}` }, + body: JSON.stringify({ + cursor: payload.cursor, + reconcile: [{ tbl: 'payable_custom_categories', row_id: customCatChange!.row_id }], + }), + }) + ) + expect(reconcileRes.status).toBe(200) + const reconcileData = (await reconcileRes.json()) as { + changes: Array<{ tbl: string; row_id: string; op: string; row?: unknown }> + } + expect(reconcileData.changes).toEqual([ + { + tbl: 'payable_custom_categories', + row_id: customCatChange!.row_id, + op: 'delete', + }, + ]) + }) + }) +}) diff --git a/lib/__tests__/payable-next-cycle.test.ts b/lib/__tests__/payable-next-cycle.test.ts index 46f7cc7..316ede1 100644 --- a/lib/__tests__/payable-next-cycle.test.ts +++ b/lib/__tests__/payable-next-cycle.test.ts @@ -46,4 +46,28 @@ describe('payableNextCycleStatus', () => { expect(r.days).toBe(30) expect(iso(r.date)).toBe('2026-10-21') }) + + it('每 X 月(如每 3 个月):按间隔月数推导下期出账日与还款日', () => { + const cycle = { cycle_type: 'every_n_months' as const, cycle_months: 3 } + // 本期 2026-10 已付清,下期为 2027-01-15 + const waiting = payableNextCycleStatus(15, '2026-10', day('2026-11-01'), 30, cycle) + expect(waiting.phase).toBe('awaiting_statement') + expect(iso(waiting.date)).toBe('2026-12-16') // 2027-01-15 - 30 天 + + const inWindow = payableNextCycleStatus(15, '2026-10', day('2026-12-20'), 30, cycle) + expect(inWindow.phase).toBe('awaiting_payment') + expect(iso(inWindow.date)).toBe('2027-01-15') + }) + + it('每年:按次年同月同日推导下期(含闰年 2 月 29 日平年收拢)', () => { + const yearly = { cycle_type: 'yearly' as const, due_month: 6 } + const waiting = payableNextCycleStatus(18, '2026-06', day('2026-07-01'), 30, yearly) + expect(waiting.phase).toBe('awaiting_statement') + expect(iso(waiting.date)).toBe('2027-05-19') // 2027-06-18 - 30 天 + + const leapYearly = { cycle_type: 'yearly' as const, due_month: 2 } + const inWindow = payableNextCycleStatus(29, '2028-02', day('2029-02-10'), 30, leapYearly) + expect(inWindow.phase).toBe('awaiting_payment') + expect(iso(inWindow.date)).toBe('2029-02-28') + }) }) diff --git a/lib/__tests__/rpc-registry.test.ts b/lib/__tests__/rpc-registry.test.ts index 752a1f0..be0f677 100644 --- a/lib/__tests__/rpc-registry.test.ts +++ b/lib/__tests__/rpc-registry.test.ts @@ -104,10 +104,10 @@ describe("RPC registry contract", () => { ["gmail-ledger", "updateLedgerAmount"], ["gmail-ledger", "getGmailLedgerBanks"], ["sync-gmail", "syncGmailLedgerToCardsAndBills"], + ["holders", "createHolder"], ]; const ADMIN_ONLY: Array<[string, string]> = [ - ["holders", "createHolder"], ["holders", "updateHolder"], ["holders", "mergeHolders"], ["promos", "createUserPromo"], @@ -153,6 +153,7 @@ describe("RPC registry contract", () => { "cards.getCardProducts", // 公开只读银行目录:无用户数据、无写操作,成员选归属银行时需要 "banks.getBankNames", + "banks.getBanks", ]); for (const [moduleName, mod] of Object.entries(RPC_REGISTRY)) { for (const [fn, entry] of Object.entries(mod)) { diff --git a/lib/__tests__/settings-redesign.test.ts b/lib/__tests__/settings-redesign.test.ts new file mode 100644 index 0000000..9faf917 --- /dev/null +++ b/lib/__tests__/settings-redesign.test.ts @@ -0,0 +1,129 @@ +import { describe, it, expect } from 'vitest' +import { readFileSync, existsSync } from 'node:fs' +import { join } from 'node:path' + +const ROOT = join(__dirname, '../..') +const read = (rel: string) => readFileSync(join(ROOT, rel), 'utf8') + +describe('F5 设置页重设计 · 双主题 Token 契约', () => { + it('app/globals.css 完整收录 17 个亮色令牌与动态覆盖', () => { + const css = read('app/globals.css') + expect(css).toContain('--color-d-light-bg:') + expect(css).toContain('--color-d-light-surface:') + expect(css).toContain('--color-d-light-border:') + expect(css).toContain('--color-d-light-text:') + expect(css).toContain('--color-d-light-accent:') + expect(css).toContain('--color-d-light-gold:') + expect(css).toContain('--color-d-light-danger:') + expect(css).toMatch(/\.theme-light,\s*\[data-theme="light"\]/) + expect(css).toMatch(/--color-d-bg:\s*var\(--color-d-light-bg\);/) + }) + + it('foundations.json 补齐暗色缺失令牌并收录亮色令牌', () => { + const foundations = JSON.parse(read('design/openpencil/vars/foundations.json')) + expect(foundations['color.obsidian.accentLight'].value).toBe('#7AADFF') + expect(foundations['color.obsidian.goldDeep'].value).toBe('#D9A93F') + expect(foundations['color.obsidian.danger'].value).toBe('#E5484D') + expect(foundations['color.obsidian.light.canvas'].value).toBe('#F5F7FA') + expect(foundations['color.obsidian.light.surface'].value).toBe('#FFFFFF') + }) + + it('baoyu-design 现行真源与历史存档保护', () => { + expect(existsSync(join(ROOT, 'design/baoyu/README.md'))).toBe(true) + expect(existsSync(join(ROOT, 'design/baoyu/canvas.json'))).toBe(true) + expect(existsSync(join(ROOT, 'design/baoyu/tokens.json'))).toBe(true) + expect(existsSync(join(ROOT, 'design/baoyu/Mobile_Settings_Dark.dc.html'))).toBe(true) + expect(existsSync(join(ROOT, 'design/baoyu/Admin_Settings_Dark.dc.html'))).toBe(true) + // 历史归档 .op 资产保留 + expect(existsSync(join(ROOT, 'design/openpencil/worldcredit-redesign.op'))).toBe(true) + }) +}) + +describe('F5 设置页重设计 · 移动端 /settings 与 BottomNav', () => { + const bottomNav = read('components/mobile/BottomNav.tsx') + const settingsPage = read('app/(mobile)/settings/page.tsx') + const displayCard = read('components/settings/DisplayPreferencesCard.tsx') + const gmailPanel = read('components/mobile/GmailConnectPanel.tsx') + + it('BottomNav 落地 4 Tab 结构(首页 / 账单 / 卡片 / 我的)', () => { + expect(bottomNav).toMatch(/\/dashboard/) + expect(bottomNav).toMatch(/\/bills/) + expect(bottomNav).toMatch(/\/cards/) + expect(bottomNav).toMatch(/\/settings/) + expect(bottomNav).toContain('首页') + expect(bottomNav).toContain('账单') + expect(bottomNav).toContain('卡片') + expect(bottomNav).toContain('我的') + }) + + it('移动端消除硬编码渐变与色值', () => { + expect(settingsPage).not.toContain('#4338ca') + expect(settingsPage).not.toContain('#4f46e5') + expect(settingsPage).not.toContain('#f59e0b') + expect(settingsPage).not.toContain('window.confirm') + expect(gmailPanel).not.toContain('window.confirm') + }) + + it('移动端头卡统一角色胶囊与后台跳转', () => { + expect(settingsPage).toContain('◆ 管理员') + expect(settingsPage).toContain('进入后台 →') + expect(settingsPage).toContain('/admin/settings') + }) + + it('移动端三组设置采用 BottomSheet 抽屉承载', () => { + expect(settingsPage).toContain(' { + expect(displayCard).toContain('default_currency') + expect(displayCard).toContain('show_annual_fee') + expect(displayCard).toContain('综合看板折算币种') + expect(displayCard).toContain('卡片年费信息') + }) + + it('退出登录具备 ConfirmDialog 二次确认', () => { + expect(settingsPage).toContain(' { + const adminPage = read('app/admin/settings/page.tsx') + + it('首屏加载失败时具备告警防护且锁死保存', () => { + expect(adminPage).toContain('loadError') + expect(adminPage).toContain('disabled={!canSave}') + expect(adminPage).toContain('重试加载') + expect(adminPage).toContain('配置拉取失败,已锁死保存操作') + }) + + it('全站维护模式开启操作具备 ConfirmDialog 二次确认拦截', () => { + expect(adminPage).toContain('confirmMaintenanceOpen') + expect(adminPage).toContain('开启全站维护模式') + expect(adminPage).toContain('开启全站维护模式后,所有普通用户的实时访问与会话将立即中断') + }) + + it('AI API Key 保持只写不回显,并提供独立安全更新通道', () => { + expect(adminPage).toContain('aiApiKeyInput') + expect(adminPage).toContain('只写不回显') + expect(adminPage).toContain('单独更新密钥') + expect(adminPage).toContain('ai_api_key_set') + }) + + it('统一草稿表单保存与 dirty 检测机制', () => { + expect(adminPage).toContain('dirtyKeys') + expect(adminPage).toContain('hasDraftChanges') + expect(adminPage).toContain('撤销更改') + expect(adminPage).toContain('保存更改') + }) + + it('默认记账币种改为 SelectField 标准选项', () => { + expect(adminPage).toContain(' { + db = createOpportunityDb(); + setDb(db as unknown as D1Database); + + await db.exec(` + INSERT INTO users (id, email, password_hash) VALUES ('u1', 'test@example.com', 'hash'); + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES ('h1', 'u1', 'u1', '张三'); + + -- 招行:默认共享额度 + INSERT INTO banks (id, name, quota_mode, statement_mode) VALUES ('b_cmb', '招商银行', 'shared', 'merged'); + INSERT INTO card_products (id, bank_id, bank_name, card_name, currency) + VALUES + ('cp_cmb_classic', 'b_cmb', '招商银行', '经典白', 'CNY'), + ('cp_cmb_bird', 'b_cmb', '招商银行', '百夫长', 'CNY'); + + -- 工行:独立额度 + INSERT INTO banks (id, name, quota_mode, statement_mode) VALUES ('b_icbc', '中国工商银行', 'independent', 'independent'); + INSERT INTO card_products (id, bank_id, bank_name, card_name, currency) + VALUES ('cp_icbc_car', 'b_icbc', '中国工商银行', '车主卡', 'CNY'); + `); +}); + +describe("共享额度池去重统计 (E5/PRD 7.3)", () => { + it("同一持卡人名下招行两张共享额度卡,总额度不重复累加", async () => { + // 招行建立合并/共享账户,两张卡各填 50,000 + await db.exec(` + INSERT INTO credit_accounts (id, holder_id, bank_id, bank_name, currency, quota_mode, statement_mode) + VALUES ('acc_cmb', 'h1', 'b_cmb', '招商银行', 'CNY', 'shared', 'merged'); + + INSERT INTO credit_cards (id, holder_id, account_id, card_product_id, card_number_last4, credit_limit, billing_day, status) + VALUES + ('cc_cmb_1', 'h1', 'acc_cmb', 'cp_cmb_classic', '1111', 50000, 10, 'active'), + ('cc_cmb_2', 'h1', 'acc_cmb', 'cp_cmb_bird', '2222', 50000, 10, 'active'); + `); + + const summary = await getAnalyticsSummary({ holder_id: "h1" }); + // 共享额度池只算 1 次 50,000 + expect(summary.total_credit_limit).toBe(50000); + + const holderData = await getHolderStatsPageData("h1"); + expect(holderData.summary.totalLimit).toBe(50000); + }); + + it("当账户显式配置 shared_credit_limit 时优先取 shared_credit_limit", async () => { + await db.exec(` + INSERT INTO credit_accounts (id, holder_id, bank_id, bank_name, currency, quota_mode, statement_mode, shared_credit_limit) + VALUES ('acc_cmb', 'h1', 'b_cmb', '招商银行', 'CNY', 'shared', 'merged', 80000); + + INSERT INTO credit_cards (id, holder_id, account_id, card_product_id, card_number_last4, credit_limit, billing_day, status) + VALUES + ('cc_cmb_1', 'h1', 'acc_cmb', 'cp_cmb_classic', '1111', 50000, 10, 'active'), + ('cc_cmb_2', 'h1', 'acc_cmb', 'cp_cmb_bird', '2222', 60000, 10, 'active'); + `); + + const summary = await getAnalyticsSummary({ holder_id: "h1" }); + expect(summary.total_credit_limit).toBe(80000); + + const holderData = await getHolderStatsPageData("h1"); + expect(holderData.summary.totalLimit).toBe(80000); + }); + + it("共享池额度与独立卡额度正确累加", async () => { + // 招行 2 张卡共享 50,000;工行 1 张卡独立 30,000;总计应为 80,000 + await db.exec(` + INSERT INTO credit_accounts (id, holder_id, bank_id, bank_name, currency, quota_mode, statement_mode) + VALUES + ('acc_cmb', 'h1', 'b_cmb', '招商银行', 'CNY', 'shared', 'merged'), + ('acc_icbc', 'h1', 'b_icbc', '中国工商银行', 'CNY', 'independent', 'independent'); + + INSERT INTO credit_cards (id, holder_id, account_id, card_product_id, card_number_last4, credit_limit, billing_day, status) + VALUES + ('cc_cmb_1', 'h1', 'acc_cmb', 'cp_cmb_classic', '1111', 50000, 10, 'active'), + ('cc_cmb_2', 'h1', 'acc_cmb', 'cp_cmb_bird', '2222', 50000, 10, 'active'), + ('cc_icbc_1', 'h1', 'acc_icbc', 'cp_icbc_car', '3333', 30000, 15, 'active'); + `); + + const summary = await getAnalyticsSummary({ holder_id: "h1" }); + expect(summary.total_credit_limit).toBe(80000); + + const holderData = await getHolderStatsPageData("h1"); + expect(holderData.summary.totalLimit).toBe(80000); + }); +}); diff --git a/lib/__tests__/unified-accounts-migration.test.ts b/lib/__tests__/unified-accounts-migration.test.ts new file mode 100644 index 0000000..5264436 --- /dev/null +++ b/lib/__tests__/unified-accounts-migration.test.ts @@ -0,0 +1,277 @@ +import { describe, it, expect } from "vitest"; +import { createOpportunityDb, createSqliteD1 } from "./helpers/sqlite-d1"; + +describe("0032_unified_credit_accounts: Schema, Backfill, Triggers & Bank Defaults", () => { + it("verifies the 4 banks defaults are statement_mode='merged' and quota_mode='shared'", async () => { + const db = createOpportunityDb(); + + // 插入测试的 4 家银行(若不存在)并运行更新 + await db.exec(` + INSERT OR IGNORE INTO banks (id, name) VALUES + ('b_cmb', '招商银行'), + ('b_cmbc', '中国民生银行'), + ('b_bos', '上海银行'), + ('b_bob', '北京银行'), + ('b_icbc', '中国工商银行'); + + UPDATE banks + SET statement_mode = 'merged', quota_mode = 'shared' + WHERE name IN ('招商银行', '中国民生银行', '民生银行', '上海银行', '北京银行') + OR name LIKE '%招商%' + OR name LIKE '%民生%' + OR name LIKE '%上海银行%' + OR name LIKE '%北京银行%'; + `); + + const banks = ( + await db.prepare("SELECT name, statement_mode, quota_mode FROM banks WHERE id IN ('b_cmb', 'b_cmbc', 'b_bos', 'b_bob', 'b_icbc')").all<{ + name: string; + statement_mode: string; + quota_mode: string; + }>() + ).results; + + const cmb = banks.find((b) => b.name === "招商银行"); + const cmbc = banks.find((b) => b.name === "中国民生银行"); + const bos = banks.find((b) => b.name === "上海银行"); + const bob = banks.find((b) => b.name === "北京银行"); + const icbc = banks.find((b) => b.name === "中国工商银行"); + + expect(cmb).toMatchObject({ statement_mode: "merged", quota_mode: "shared" }); + expect(cmbc).toMatchObject({ statement_mode: "merged", quota_mode: "shared" }); + expect(bos).toMatchObject({ statement_mode: "merged", quota_mode: "shared" }); + expect(bob).toMatchObject({ statement_mode: "merged", quota_mode: "shared" }); + expect(icbc).toMatchObject({ statement_mode: "independent", quota_mode: "independent" }); + + db.close(); + }); + + it("verifies backfill logic on various scenarios: no collision merged, collision kept independent, cross-holder isolated", async () => { + // 创建一个从 0001 执行到 0031 的干净库,插入存量数据,再应用 0032 + const db = createSqliteD1(); + const fs = await import("node:fs"); + const path = await import("node:path"); + const migrationsDir = path.join(__dirname, "../../migrations/d1"); + const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort(); + + // 运行 0001 - 0031 + for (const f of files) { + if (f.startsWith("0032")) break; + db.exec(fs.readFileSync(path.join(migrationsDir, f), "utf8")); + } + + // 灌入存量数据 + db.exec(` + INSERT INTO users (id, email, password_hash) VALUES + ('u1', 'u1@example.com', 'h1'), + ('u2', 'u2@example.com', 'h2'); + + INSERT INTO banks (id, name, statement_mode, quota_mode) VALUES + ('b_cmb', '招商银行', 'merged', 'shared'), + ('b_cmbc', '民生银行', 'merged', 'shared'), + ('b_icbc', '中国工商银行', 'independent', 'independent'); + + INSERT INTO card_products (id, bank_id, bank_name, card_name, currency, payment_due_type, payment_due_value) VALUES + ('cp_cmb', 'b_cmb', '招商银行', '经典白', 'CNY', 'after_billing', 20), + ('cp_cmbc', 'b_cmbc', '民生银行', '标准卡', 'CNY', 'after_billing', 20), + ('cp_icbc', 'b_icbc', '中国工商银行', '牡丹卡', 'CNY', 'after_billing', 25); + + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES + ('h1', 'u1', 'u1', '持卡人甲'), + ('h2', 'u2', 'u2', '持卡人乙'); + + -- 场景 1:h1 招商银行 2 张卡,card1 有 2026-09 和 2026-10 账单,card2 无账单 -> 无同月碰撞,应合并! + INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, credit_limit, status, created_at) VALUES + ('card_cmb_1', 'h1', 'cp_cmb', 5, 50000, 'active', '2026-01-01T00:00:00Z'), + ('card_cmb_2', 'h1', 'cp_cmb', 5, 60000, 'active', '2026-01-02T00:00:00Z'); + + INSERT INTO bills (id, card_id, bill_month, due_date, bill_amount) VALUES + ('bill_cmb_1', 'card_cmb_1', '2026-09', '2026-09-25', 1000), + ('bill_cmb_2', 'card_cmb_1', '2026-10', '2026-10-25', 2000); + + -- 场景 2:h1 民生银行 2 张卡(0872 与 另一张卡),两张卡均有 2026-10 账单 -> 同月碰撞!绝不强行合并,各自保留 independent! + INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day, credit_limit, status, created_at) VALUES + ('card_cmbc_coll_1', 'h1', 'cp_cmbc', '0872', 22, 30000, 'active', '2026-01-01T00:00:00Z'), + ('card_cmbc_coll_2', 'h1', 'cp_cmbc', '1234', 27, 30000, 'active', '2026-01-02T00:00:00Z'); + + INSERT INTO bills (id, card_id, bill_month, due_date, bill_amount) VALUES + ('bill_cmbc_1', 'card_cmbc_coll_1', '2026-10', '2026-11-16', 3000), + ('bill_cmbc_2', 'card_cmbc_coll_2', '2026-10', '2026-11-21', 4000); + + -- 场景 3:h2 民生银行尾号 9765 卡 -> 持卡人是 h2!与 h1 的 0872 属于不同持卡人,严禁跨人合并! + INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, billing_day, credit_limit, status, created_at) VALUES + ('card_cmbc_h2_9765', 'h2', 'cp_cmbc', '9765', 27, 40000, 'active', '2026-01-03T00:00:00Z'); + + INSERT INTO bills (id, card_id, bill_month, due_date, bill_amount) VALUES + ('bill_cmbc_h2', 'card_cmbc_h2_9765', '2026-10', '2026-11-21', 5000); + + -- 场景 4:h1 工商银行(independent 银行)单卡 -> independent 账户 + INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day, credit_limit, status, created_at) VALUES + ('card_icbc_1', 'h1', 'cp_icbc', 15, 20000, 'active', '2026-01-01T00:00:00Z'); + `); + + // 现在执行 0032 迁移! + db.exec(fs.readFileSync(path.join(migrationsDir, "0032_unified_credit_accounts.sql"), "utf8")); + + // 验证场景 1(招行多卡无碰撞合并) + const cmbCards = ( + await db.prepare("SELECT id, account_id FROM credit_cards WHERE id IN ('card_cmb_1', 'card_cmb_2')").all<{ + id: string; + account_id: string; + }>() + ).results; + expect(cmbCards[0].account_id).toBeTruthy(); + expect(cmbCards[0].account_id).toBe(cmbCards[1].account_id); + + const cmbAccount = await db + .prepare("SELECT * FROM credit_accounts WHERE id = ?") + .bind(cmbCards[0].account_id) + .first<{ + statement_mode: string; + quota_mode: string; + primary_card_id: string; + shared_credit_limit: number; + }>(); + expect(cmbAccount).toMatchObject({ + statement_mode: "merged", + quota_mode: "shared", + primary_card_id: "card_cmb_1", // card_cmb_1 账单多,成为锚点卡 + shared_credit_limit: 60000, // 取组内 MAX(50000, 60000) + }); + + // 验证招行历史账单的 account_id 和 card_id + const cmbBills = ( + await db.prepare("SELECT id, card_id, account_id FROM bills WHERE id IN ('bill_cmb_1', 'bill_cmb_2')").all<{ + id: string; + card_id: string; + account_id: string; + }>() + ).results; + expect(cmbBills[0].account_id).toBe(cmbCards[0].account_id); + expect(cmbBills[1].account_id).toBe(cmbCards[0].account_id); + expect(cmbBills[0].card_id).toBe("card_cmb_1"); + expect(cmbBills[1].card_id).toBe("card_cmb_1"); + + // 验证场景 2(h1 民生卡同月碰撞 -> 保守回填,绝不合并,账单零删除零篡改) + const cmbcCollCards = ( + await db + .prepare("SELECT id, account_id FROM credit_cards WHERE id IN ('card_cmbc_coll_1', 'card_cmbc_coll_2')") + .all<{ id: string; account_id: string }>() + ).results; + expect(cmbcCollCards[0].account_id).not.toBe(cmbcCollCards[1].account_id); // 保持独立! + + const cmbcAcc1 = await db + .prepare("SELECT statement_mode, primary_card_id FROM credit_accounts WHERE id = ?") + .bind(cmbcCollCards[0].account_id) + .first<{ statement_mode: string; primary_card_id: string }>(); + const cmbcAcc2 = await db + .prepare("SELECT statement_mode, primary_card_id FROM credit_accounts WHERE id = ?") + .bind(cmbcCollCards[1].account_id) + .first<{ statement_mode: string; primary_card_id: string }>(); + expect(cmbcAcc1?.statement_mode).toBe("independent"); + expect(cmbcAcc2?.statement_mode).toBe("independent"); + expect(cmbcAcc1?.primary_card_id).toBe("card_cmbc_coll_1"); + expect(cmbcAcc2?.primary_card_id).toBe("card_cmbc_coll_2"); + + // 账单金额分文不差保留 + const cmbcBills = ( + await db.prepare("SELECT id, bill_amount, card_id, account_id FROM bills WHERE id IN ('bill_cmbc_1', 'bill_cmbc_2')").all<{ + id: string; + bill_amount: number; + card_id: string; + account_id: string; + }>() + ).results; + expect(cmbcBills).toHaveLength(2); + expect(cmbcBills[0].bill_amount).toBe(3000); + expect(cmbcBills[1].bill_amount).toBe(4000); + expect(cmbcBills[0].account_id).toBe(cmbcCollCards[0].account_id); + expect(cmbcBills[1].account_id).toBe(cmbcCollCards[1].account_id); + + // 验证场景 3(民生 0872 与 9765 跨人隔离) + const h2Card = await db + .prepare("SELECT id, holder_id, account_id FROM credit_cards WHERE id = 'card_cmbc_h2_9765'") + .first<{ id: string; holder_id: string; account_id: string }>(); + expect(h2Card?.holder_id).toBe("h2"); + expect(h2Card?.account_id).not.toBe(cmbcCollCards[0].account_id); + expect(h2Card?.account_id).not.toBe(cmbcCollCards[1].account_id); + + const h2Account = await db + .prepare("SELECT * FROM credit_accounts WHERE id = ?") + .bind(h2Card?.account_id) + .first<{ holder_id: string }>(); + expect(h2Account?.holder_id).toBe("h2"); + + // 验证唯一约束 UNIQUE(account_id, bill_month) + // 试图向同一个 account 插入同月第二条账单,必须被 SQLite 拒绝! + expect(() => { + db.exec(` + INSERT INTO bills (id, account_id, card_id, bill_month, due_date, bill_amount) + VALUES ('bill_dup', '${cmbCards[0].account_id}', 'card_cmb_1', '2026-10', '2026-10-25', 999); + `); + }).toThrow(/UNIQUE constraint failed: bills.account_id, bills.bill_month/); + + db.close(); + }); + + it("verifies sync_changes triggers for credit_accounts and bill_card_subtotals", async () => { + const db = createOpportunityDb(); + + // 创建测试持卡人与账户 + await db.exec(` + INSERT INTO users (id, email, password_hash) VALUES ('u_sync', 'sync@example.com', 'h'); + INSERT INTO banks (id, name) VALUES ('b_sync', '测试银行'); + INSERT INTO card_products (id, bank_id, bank_name, card_name) VALUES ('cp_sync', 'b_sync', '测试银行', '标准卡'); + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES ('h_sync', 'u_sync', 'u_sync', '同步测试人'); + INSERT INTO credit_cards (id, holder_id, card_product_id, billing_day) VALUES ('c_sync', 'h_sync', 'cp_sync', 10); + DELETE FROM sync_changes; + `); + + // 1. 测试 credit_accounts 插入 + await db.exec(` + INSERT INTO credit_accounts (id, holder_id, bank_name, currency, primary_card_id) + VALUES ('acc_sync_test', 'h_sync', '测试银行', 'CNY', 'c_sync'); + `); + + const accInsertChange = await db + .prepare("SELECT owner_id, tbl, row_id, op FROM sync_changes WHERE tbl = 'credit_accounts' AND row_id = 'acc_sync_test'") + .first(); + expect(accInsertChange).toEqual({ + owner_id: "u_sync", + tbl: "credit_accounts", + row_id: "acc_sync_test", + op: "upsert", + }); + + // 2. 测试 credit_accounts 更新 + await db.exec(` + UPDATE credit_accounts SET shared_credit_limit = 50000 WHERE id = 'acc_sync_test'; + `); + const accUpdateChanges = ( + await db.prepare("SELECT owner_id, tbl, row_id, op FROM sync_changes WHERE tbl = 'credit_accounts' AND row_id = 'acc_sync_test'").all() + ).results; + expect(accUpdateChanges.length).toBeGreaterThanOrEqual(2); + + // 3. 测试 bill_card_subtotals 插入与更新 + await db.exec(` + INSERT INTO bills (id, account_id, card_id, bill_month, due_date, bill_amount) + VALUES ('bill_sub_test', 'acc_sync_test', 'c_sync', '2026-10', '2026-10-25', 1000); + DELETE FROM sync_changes; + + INSERT INTO bill_card_subtotals (id, bill_id, card_id, card_tail, subtotal_amount) + VALUES ('sub_1', 'bill_sub_test', 'c_sync', '0872', 600); + `); + + const subChange = await db + .prepare("SELECT owner_id, tbl, row_id, op FROM sync_changes WHERE tbl = 'bill_card_subtotals' AND row_id = 'sub_1'") + .first(); + expect(subChange).toEqual({ + owner_id: "u_sync", + tbl: "bill_card_subtotals", + row_id: "sub_1", + op: "upsert", + }); + + db.close(); + }); +}); diff --git a/lib/__tests__/unified-bills-summary.test.ts b/lib/__tests__/unified-bills-summary.test.ts new file mode 100644 index 0000000..a8f0e3b --- /dev/null +++ b/lib/__tests__/unified-bills-summary.test.ts @@ -0,0 +1,113 @@ +import { describe, it, expect, beforeEach } from "vitest"; +import { createOpportunityDb, type SqliteD1 } from "./helpers/sqlite-d1"; +import { setDb } from "../db/client"; +import { getCardsWithBillsSummary, getBillDetail, createBill } from "../api/bills.server"; + +let db: SqliteD1; + +beforeEach(async () => { + db = createOpportunityDb(); + setDb(db as unknown as D1Database); + + await db.exec(` + INSERT INTO users (id, email, password_hash) VALUES ('u1', 'test@example.com', 'hash'); + INSERT INTO card_holders (id, created_by, managed_by, name) VALUES ('h1', 'u1', 'u1', '本人'); + + INSERT INTO banks (id, name, statement_mode, quota_mode) + VALUES ('b_cmb', '招商银行', 'merged', 'shared'); + + INSERT INTO card_products (id, bank_id, bank_name, card_name, currency, payment_due_type, payment_due_value) + VALUES + ('cp_cmb_classic', 'b_cmb', '招商银行', '经典白', 'CNY', 'after_billing', 20), + ('cp_cmb_bird', 'b_cmb', '招商银行', '百夫长', 'CNY', 'after_billing', 20); + + -- 建立招行合并账户 + INSERT INTO credit_accounts (id, holder_id, bank_id, bank_name, currency, statement_mode, quota_mode, billing_day) + VALUES ('acc_cmb', 'h1', 'b_cmb', '招商银行', 'CNY', 'merged', 'shared', 10); + + INSERT INTO credit_cards (id, holder_id, account_id, card_product_id, card_number_last4, credit_limit, billing_day, status) + VALUES + ('cc_1', 'h1', 'acc_cmb', 'cp_cmb_classic', '0872', 50000, 10, 'active'), + ('cc_2', 'h1', 'acc_cmb', 'cp_cmb_bird', '9765', 50000, 10, 'active'); + + UPDATE credit_accounts SET primary_card_id = 'cc_1' WHERE id = 'acc_cmb'; + `); +}); + +describe("多卡统一账单摘要与读取路径 (E5/Phase 2)", () => { + it("getCardsWithBillsSummary: 合并账户副卡抑制缺账,待还不重复累加", async () => { + // 插入一笔 2026-10 期账单(总额 10000,挂在锚点卡 cc_1) + await db.exec(` + INSERT INTO bills (id, account_id, card_id, bill_month, bill_amount, due_date, status) + VALUES ('b_oct', 'acc_cmb', 'cc_1', '2026-10', 10000, '2026-11-05', 'unpaid'); + + -- 分卡小计:0872 消费 6000,9765 消费 3800,剩余 200 差额 + INSERT INTO bill_card_subtotals (id, bill_id, card_id, card_tail, subtotal_amount, currency) + VALUES + ('sub_1', 'b_oct', 'cc_1', '0872', 6000, 'CNY'), + ('sub_2', 'b_oct', 'cc_2', '9765', 3800, 'CNY'); + `); + + const summaries = await getCardsWithBillsSummary("u1"); + expect(summaries).toHaveLength(2); + + const anchorSummary = summaries.find((s) => s.card.id === "cc_1")!; + const secondarySummary = summaries.find((s) => s.card.id === "cc_2")!; + + // 主卡检查 + expect(anchorSummary.isAnchorCard).toBe(true); + expect(anchorSummary.suppressMissingStatement).toBe(false); + expect(anchorSummary.unpaidAmount).toBe(10000); + expect(anchorSummary.activeBill?.subtotals).toHaveLength(2); + expect(anchorSummary.activeBill?.unallocated_amount).toBe(200); + + // 副卡检查:必须抑制缺账,待还必须为 0 + expect(secondarySummary.isAnchorCard).toBe(false); + expect(secondarySummary.suppressMissingStatement).toBe(true); + expect(secondarySummary.unpaidAmount).toBe(0); + expect(secondarySummary.memberCards).toHaveLength(2); + }); + + it("getBillDetail: 返回账户信息、分卡小计与未归卡差额", async () => { + await db.exec(` + INSERT INTO bills (id, account_id, card_id, bill_month, bill_amount, due_date, status) + VALUES ('b_oct', 'acc_cmb', 'cc_1', '2026-10', 5000, '2026-11-05', 'unpaid'); + + INSERT INTO bill_card_subtotals (id, bill_id, card_id, card_tail, subtotal_amount, currency) + VALUES + ('sub_1', 'b_oct', 'cc_1', '0872', 3000, 'CNY'), + ('sub_2', 'b_oct', 'cc_2', '9765', 1500, 'CNY'); + `); + + const detail = await getBillDetail("b_oct"); + expect(detail.bill.account?.id).toBe("acc_cmb"); + expect(detail.bill.account?.statement_mode).toBe("merged"); + expect(detail.bill.subtotals).toHaveLength(2); + // 5000 - (3000 + 1500) = 500 + expect(detail.bill.unallocated_amount).toBe(500); + expect(detail.bill.member_cards).toHaveLength(2); + }); + + it("createBill: 自动补齐 account_id 并对齐 anchor card", async () => { + // 传入副卡 cc_2,但账户是 merged,应自动对齐 card_id 为 cc_1 + const created = await createBill({ + card_id: "cc_2", + bill_month: "2026-11", + bill_amount: 8800, + due_date: "2026-12-05", + status: "unpaid", + subtotals: [ + { card_tail: "0872", subtotal_amount: 5000 }, + { card_tail: "9765", subtotal_amount: 3800 }, + ], + }); + + expect(created.account_id).toBe("acc_cmb"); + expect(created.card_id).toBe("cc_1"); // 对齐锚点卡 + expect(created.bill_amount).toBe(8800); + + const detail = await getBillDetail(created.id); + expect(detail.bill.subtotals).toHaveLength(2); + expect(detail.bill.unallocated_amount).toBeUndefined(); // 5000+3800 = 8800,无差额 + }); +}); diff --git a/lib/api/accounts.server.ts b/lib/api/accounts.server.ts new file mode 100644 index 0000000..1c1d75b --- /dev/null +++ b/lib/api/accounts.server.ts @@ -0,0 +1,396 @@ +// lib/api/accounts.server.ts — 信用账户(Credit Accounts)服务端管理模块 + +import { query, queryOne, execute, batch, now } from "../db"; +import type { CreditAccount, CreditCard, Bill, BillCardSubtotal } from "../types"; +import { RpcDomainError } from "./errors"; + +export interface CreditAccountDetail extends CreditAccount { + cards: CreditCard[]; + latest_bill?: (Bill & { subtotals?: BillCardSubtotal[] }) | null; +} + +export type UpdateCreditAccountPatch = { + label?: string | null; + shared_credit_limit?: number | null; + billing_day?: number | null; + due_type?: "fixed" | "after_billing" | "fixed_before_billing" | null; + due_value?: number | null; + statement_mode?: "merged" | "independent"; + quota_mode?: "shared" | "independent"; +}; + +/** + * 获取当前用户可见的信用账户列表 + */ +export async function getCreditAccounts(userId?: string): Promise { + let condition = ""; + const params: unknown[] = []; + if (userId) { + condition = "WHERE (ch.created_by = ? OR ch.auth_user_id = ?)"; + params.push(userId, userId); + } + + const { data, error } = await query>( + `SELECT ca.* + FROM credit_accounts ca + JOIN card_holders ch ON ca.holder_id = ch.id + ${condition} + ORDER BY ca.created_at DESC`, + params, + ); + if (error) throw new Error(error.message); + + return (data || []).map((row) => ({ + id: String(row.id), + holder_id: String(row.holder_id), + bank_id: row.bank_id ? String(row.bank_id) : null, + bank_name: String(row.bank_name || ""), + currency: String(row.currency || "CNY"), + account_tail: row.account_tail ? String(row.account_tail) : null, + statement_mode: (row.statement_mode as CreditAccount["statement_mode"]) || "independent", + quota_mode: (row.quota_mode as CreditAccount["quota_mode"]) || "independent", + shared_credit_limit: + row.shared_credit_limit != null ? Number(row.shared_credit_limit) : null, + billing_day: row.billing_day != null ? Number(row.billing_day) : null, + due_type: row.due_type as CreditAccount["due_type"], + due_value: row.due_value != null ? Number(row.due_value) : null, + primary_card_id: row.primary_card_id ? String(row.primary_card_id) : null, + label: row.label ? String(row.label) : null, + status: (row.status as CreditAccount["status"]) || "active", + created_at: String(row.created_at), + updated_at: String(row.updated_at), + })); +} + +/** + * 获取单个信用账户详情,附带下挂卡片及最新账单信息 + */ +export async function getCreditAccountDetail( + accountId: string, +): Promise { + const { data: accRow, error: accError } = await queryOne>( + "SELECT * FROM credit_accounts WHERE id = ?", + [accountId], + ); + if (accError || !accRow) return null; + + const account: CreditAccount = { + id: String(accRow.id), + holder_id: String(accRow.holder_id), + bank_id: accRow.bank_id ? String(accRow.bank_id) : null, + bank_name: String(accRow.bank_name || ""), + currency: String(accRow.currency || "CNY"), + account_tail: accRow.account_tail ? String(accRow.account_tail) : null, + statement_mode: (accRow.statement_mode as CreditAccount["statement_mode"]) || "independent", + quota_mode: (accRow.quota_mode as CreditAccount["quota_mode"]) || "independent", + shared_credit_limit: + accRow.shared_credit_limit != null ? Number(accRow.shared_credit_limit) : null, + billing_day: accRow.billing_day != null ? Number(accRow.billing_day) : null, + due_type: accRow.due_type as CreditAccount["due_type"], + due_value: accRow.due_value != null ? Number(accRow.due_value) : null, + primary_card_id: accRow.primary_card_id ? String(accRow.primary_card_id) : null, + label: accRow.label ? String(accRow.label) : null, + status: (accRow.status as CreditAccount["status"]) || "active", + created_at: String(accRow.created_at), + updated_at: String(accRow.updated_at), + }; + + // 下挂信用卡 + const { data: cardsData } = await query>( + `SELECT cc.*, cp.card_name, cp.bank_name + FROM credit_cards cc + LEFT JOIN card_products cp ON cc.card_product_id = cp.id + WHERE cc.account_id = ? + ORDER BY cc.created_at ASC`, + [accountId], + ); + const cards = (cardsData || []) as unknown as CreditCard[]; + + // 最新账单 + const { data: latestBillRow } = await queryOne( + "SELECT * FROM bills WHERE account_id = ? ORDER BY bill_month DESC LIMIT 1", + [accountId], + ); + + let latest_bill: (Bill & { subtotals?: BillCardSubtotal[] }) | null = null; + if (latestBillRow) { + const { data: subtotals } = await query( + "SELECT * FROM bill_card_subtotals WHERE bill_id = ? ORDER BY card_tail ASC", + [latestBillRow.id], + ); + latest_bill = { + ...latestBillRow, + subtotals: subtotals || [], + }; + } + + return { + ...account, + cards, + latest_bill, + }; +} + +/** + * 将多张独立卡合并并入现有信用账户(支持合并向导) + * 硬约束守卫: + * 1. 目标账户与被合并卡片必须归属同一持卡人(严禁跨持卡人合并,如民生 0872 与 9765) + * 2. 检查历史同月账单碰撞:若存在相同 bill_month 账单,抛出可读冲突错误,杜绝强行合并 + */ +export async function mergeCardsIntoAccount( + targetAccountId: string, + cardIds: string[], +): Promise<{ mergedCount: number }> { + if (!cardIds || cardIds.length === 0) { + throw new RpcDomainError("VALIDATION_FAILED", "请选择需要合并的卡片"); + } + + const targetAccount = await getCreditAccountDetail(targetAccountId); + if (!targetAccount) { + throw new RpcDomainError("NOT_FOUND", "目标信用账户不存在"); + } + + const placeholders = cardIds.map(() => "?").join(","); + const { data: rawCards } = await query>( + `SELECT cc.*, cp.currency, cp.bank_name + FROM credit_cards cc + LEFT JOIN card_products cp ON cc.card_product_id = cp.id + WHERE cc.id IN (${placeholders})`, + cardIds, + ); + const cards = rawCards || []; + if (cards.length !== cardIds.length) { + throw new RpcDomainError("VALIDATION_FAILED", "部分待合并卡片不存在"); + } + + // 1. 同一持卡人、同银行与同币种校验 + const targetBank = targetAccount.bank_name?.trim(); + const firstCardBank = String(cards[0]?.bank_name || "").trim(); + for (const c of cards) { + if (String(c.holder_id) !== targetAccount.holder_id) { + throw new RpcDomainError("VALIDATION_FAILED", "不可跨持卡人合并信用账户与信用卡"); + } + const cardBank = String(c.bank_name || "").trim(); + if (targetBank && cardBank && cardBank !== targetBank) { + throw new RpcDomainError("VALIDATION_FAILED", "不可跨银行合并信用卡至同一账户"); + } + if (cardBank && firstCardBank && cardBank !== firstCardBank) { + throw new RpcDomainError("VALIDATION_FAILED", "待合并卡片归属不同银行,无法合并至同一账户"); + } + const cardCurrency = String(c.currency || "CNY"); + if (cardCurrency !== targetAccount.currency) { + throw new RpcDomainError("VALIDATION_FAILED", "不同记账币种的卡片不能合并至同一账户"); + } + if (String(c.card_type) === "loan") { + throw new RpcDomainError("VALIDATION_FAILED", "贷款类卡片不可合并至信用卡账单账户"); + } + } + + // 2. 同月账单碰撞检查 + // (a) 检查待合并各卡与目标账户已有账单是否存在相同月份 + const { data: targetBills } = await query<{ bill_month: string }>( + "SELECT bill_month FROM bills WHERE account_id = ?", + [targetAccountId], + ); + const targetMonths = new Set((targetBills || []).map((b) => b.bill_month)); + + const { data: candidateBills } = await query<{ card_id: string; bill_month: string }>( + `SELECT card_id, bill_month FROM bills WHERE card_id IN (${placeholders})`, + cardIds, + ); + const candidateList = candidateBills || []; + + for (const cb of candidateList) { + if (targetMonths.has(cb.bill_month)) { + throw new RpcDomainError( + "CONFLICT", + `检测到历史账单碰撞:卡片与目标账户在 ${cb.bill_month} 均有账单,无法自动合并,请先人工核对`, + ); + } + } + + // (b) 检查待合并卡片之间是否存在同月账单 + const seenCandidateMonths = new Set(); + for (const cb of candidateList) { + if (seenCandidateMonths.has(cb.bill_month)) { + throw new RpcDomainError( + "CONFLICT", + `待合并的卡片之间在 ${cb.bill_month} 存在重复账单,无法自动合并`, + ); + } + seenCandidateMonths.add(cb.bill_month); + } + + // 3. 执行合并事务 + const anchorCardId = targetAccount.primary_card_id || cardIds[0]; + const maxLimit = Math.max( + targetAccount.shared_credit_limit || 0, + ...cards.map((c) => Number(c.credit_limit_override ?? c.credit_limit) || 0), + ); + + const updates: { sql: string; params?: unknown[] }[] = []; + + // 更新目标账户模式与共享额度 + updates.push({ + sql: `UPDATE credit_accounts + SET statement_mode = 'merged', + quota_mode = 'shared', + shared_credit_limit = ?, + updated_at = ? + WHERE id = ?`, + params: [maxLimit > 0 ? maxLimit : null, now(), targetAccountId], + }); + + // 更新卡片所属 account_id + for (const cid of cardIds) { + updates.push({ + sql: "UPDATE credit_cards SET account_id = ? WHERE id = ?", + params: [targetAccountId, cid], + }); + } + + // 将待合并卡片历史 bills 迁移至目标账户,并对齐 anchor card_id + for (const cid of cardIds) { + updates.push({ + sql: "UPDATE bills SET account_id = ?, card_id = ? WHERE card_id = ?", + params: [targetAccountId, anchorCardId, cid], + }); + } + + await batch(updates); + return { mergedCount: cardIds.length }; +} + +/** + * 将卡片从合并账户中拆出为独立账单账户 + */ +export async function splitCardFromAccount(cardId: string): Promise { + const { data: cardRow } = await queryOne>( + `SELECT cc.*, cp.bank_id, cp.bank_name, cp.currency, cp.payment_due_type, cp.payment_due_value + FROM credit_cards cc + LEFT JOIN card_products cp ON cc.card_product_id = cp.id + WHERE cc.id = ?`, + [cardId], + ); + if (!cardRow) throw new RpcDomainError("NOT_FOUND", "卡片不存在"); + + const currentAccountId = cardRow.account_id ? String(cardRow.account_id) : null; + if (!currentAccountId) { + throw new RpcDomainError("VALIDATION_FAILED", "该卡片未归属于任何信用账户"); + } + + const { data: siblings } = await query<{ id: string }>( + "SELECT id FROM credit_cards WHERE account_id = ? AND id != ?", + [currentAccountId, cardId], + ); + if (!siblings || siblings.length === 0) { + throw new RpcDomainError("VALIDATION_FAILED", "该账户仅有此一张卡片,无需拆分"); + } + + const account = await getCreditAccountDetail(currentAccountId); + if (!account) throw new RpcDomainError("NOT_FOUND", "当前账户不存在"); + + const updates: { sql: string; params?: unknown[] }[] = []; + const newAccountId = `acc_i_${cardId}`; + + // 若拆出的卡片恰好是原账户的 primary_card_id,需将原账户锚点平滑平移给剩余卡 + if (account.primary_card_id === cardId) { + const nextAnchorCardId = siblings[0].id; + updates.push({ + sql: "UPDATE credit_accounts SET primary_card_id = ?, updated_at = ? WHERE id = ?", + params: [nextAnchorCardId, now(), currentAccountId], + }); + // 原账户账单更新锚点卡 + updates.push({ + sql: "UPDATE bills SET card_id = ? WHERE account_id = ?", + params: [nextAnchorCardId, currentAccountId], + }); + } + + // 为被拆出的卡片新建独立账户 + updates.push({ + sql: `INSERT INTO credit_accounts ( + id, holder_id, bank_id, bank_name, currency, statement_mode, quota_mode, + shared_credit_limit, billing_day, due_type, due_value, primary_card_id, status, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, 'independent', 'independent', NULL, ?, ?, ?, ?, 'active', ?, ?)`, + params: [ + newAccountId, + cardRow.holder_id, + cardRow.bank_id || null, + cardRow.bank_name || "未知银行", + cardRow.currency || "CNY", + cardRow.billing_day, + cardRow.override_due_type || cardRow.payment_due_type || "after_billing", + cardRow.override_due_value || cardRow.payment_due_value || 20, + cardId, + now(), + now(), + ], + }); + + // 更新卡片 account_id 指向新独立账户 + updates.push({ + sql: "UPDATE credit_cards SET account_id = ? WHERE id = ?", + params: [newAccountId, cardId], + }); + + await batch(updates); + + const created = await getCreditAccountDetail(newAccountId); + if (!created) throw new Error("拆分账户创建失败"); + return created; +} + +/** + * 更新信用账户信息 + */ +export async function updateCreditAccount( + accountId: string, + patch: UpdateCreditAccountPatch, +): Promise { + const account = await getCreditAccountDetail(accountId); + if (!account) throw new RpcDomainError("NOT_FOUND", "信用账户不存在"); + + const fields: string[] = ["updated_at = ?"]; + const params: unknown[] = [now()]; + + if (patch.label !== undefined) { + fields.push("label = ?"); + params.push(patch.label); + } + if (patch.shared_credit_limit !== undefined) { + fields.push("shared_credit_limit = ?"); + params.push(patch.shared_credit_limit != null && patch.shared_credit_limit > 0 ? patch.shared_credit_limit : null); + } + if (patch.billing_day !== undefined) { + fields.push("billing_day = ?"); + params.push(patch.billing_day); + } + if (patch.due_type !== undefined) { + fields.push("due_type = ?"); + params.push(patch.due_type); + } + if (patch.due_value !== undefined) { + fields.push("due_value = ?"); + params.push(patch.due_value); + } + if (patch.statement_mode !== undefined) { + fields.push("statement_mode = ?"); + params.push(patch.statement_mode); + } + if (patch.quota_mode !== undefined) { + fields.push("quota_mode = ?"); + params.push(patch.quota_mode); + } + + params.push(accountId); + const { error } = await execute( + `UPDATE credit_accounts SET ${fields.join(", ")} WHERE id = ?`, + params, + ); + if (error) throw new Error(error.message); + + const updated = await getCreditAccountDetail(accountId); + if (!updated) throw new Error("更新失败"); + return updated; +} diff --git a/lib/api/accounts.ts b/lib/api/accounts.ts new file mode 100644 index 0000000..0cc7926 --- /dev/null +++ b/lib/api/accounts.ts @@ -0,0 +1,41 @@ +// lib/api/accounts.ts — client-side RPC wrappers for credit accounts +import type * as Server from "./accounts.server"; +import { callRpc } from "./rpc-client"; + +export type { CreditAccountDetail, UpdateCreditAccountPatch } from "./accounts.server"; + +export function getCreditAccounts(...args: Parameters) { + return callRpc('accounts', 'getCreditAccounts', ...args); +} + +export function getCreditAccountDetail(...args: Parameters) { + return callRpc( + 'accounts', + 'getCreditAccountDetail', + ...args, + ); +} + +export function mergeCardsIntoAccount(...args: Parameters) { + return callRpc( + 'accounts', + 'mergeCardsIntoAccount', + ...args, + ); +} + +export function splitCardFromAccount(...args: Parameters) { + return callRpc( + 'accounts', + 'splitCardFromAccount', + ...args, + ); +} + +export function updateCreditAccount(...args: Parameters) { + return callRpc( + 'accounts', + 'updateCreditAccount', + ...args, + ); +} diff --git a/lib/api/admin.server.ts b/lib/api/admin.server.ts index 7dd4aab..a0268a5 100644 --- a/lib/api/admin.server.ts +++ b/lib/api/admin.server.ts @@ -1,6 +1,7 @@ import { query, queryOne, execute, uuid, now } from '../db' import { CardProduct, Promo, Benefit, Bank, EmailParseLog } from '../types' import { archiveLegacyDefinition } from '../opportunities/legacy.server' +import { extractValidCreditLimit, isExactDueDate } from '../email-core/due-date' /** * 管理后台通用 API 封装 @@ -44,7 +45,9 @@ interface RawEmailBillPayload { card_last4?: string | null bill_amount?: number | null min_payment?: number | null - due_date?: string + credit_limit?: number | null + due_date?: string | null + due_date_status?: 'exact' | 'ambiguous_or_grace_only' | 'missing' | null bill_month?: string statement_date?: string | null currency?: string @@ -182,6 +185,18 @@ export async function createCardFromEmailParseLog( if (parsed.bill_amount == null || !Number.isFinite(amount) || amount < 0) { throw new Error('AI 解析结果缺少合法账单金额') } + const zeroBill = amount === 0 + const rawDue = typeof parsed.due_date === 'string' ? parsed.due_date.trim() : '' + const exactDue = + isExactDueDate(rawDue) && parsed.due_date_status !== 'ambiguous_or_grace_only' + ? rawDue + : null + if (!zeroBill && !exactDue) { + if (parsed.due_date_status === 'ambiguous_or_grace_only' || rawDue.length > 0) { + throw new Error('邮件还款日模糊或仅有宽限期,禁止编造还款日入库') + } + throw new Error('邮件未提供确切还款日,禁止编造还款日入库') + } const holderSql = params.holderId ? `SELECT id, name FROM card_holders @@ -246,19 +261,19 @@ export async function createCardFromEmailParseLog( let createdCard = false if (!cardId) { cardId = uuid() + const initialLimit = extractValidCreditLimit(parsed.credit_limit) ?? 0 const { error: insertCardError } = await execute( `INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) - VALUES (?, ?, ?, ?, 0, ?, 'active', 'credit')`, - [cardId, holder.id, productId, tail, statementDay(parsed.statement_date)], + VALUES (?, ?, ?, ?, ?, ?, 'active', 'credit')`, + [cardId, holder.id, productId, tail, initialLimit, statementDay(parsed.statement_date)], ) if (insertCardError) throw new Error(insertCardError.message) createdCard = true } - const dueDate = parsed.due_date ?? parsed.statement_date ?? `${billMonth}-28` + const dueDate = exactDue ?? parsed.statement_date ?? `${billMonth}-28` const minPayment = parsed.min_payment == null ? null : Number(parsed.min_payment) - const zeroBill = amount === 0 const { data: existingBill, error: billError } = await queryOne<{ id: string status: string | null diff --git a/lib/api/analytics.server.ts b/lib/api/analytics.server.ts index d33fc77..6485d64 100644 --- a/lib/api/analytics.server.ts +++ b/lib/api/analytics.server.ts @@ -249,20 +249,86 @@ export async function getAnalyticsSummary(filters: AnalyticsFilters): Promise 0) { const placeholders = cardIds.map(() => '?').join(',') - const { data: cards, error } = await query<{ credit_limit: number; currency: string | null }>( - `SELECT cc.credit_limit, cp.currency + const { data: cards, error } = await query<{ + id: string + holder_id: string + credit_limit: number + account_id: string | null + currency: string | null + bank_id: string | null + bank_name: string | null + account_quota_mode: string | null + shared_credit_limit: number | null + bank_quota_mode: string | null + }>( + `SELECT cc.id, cc.holder_id, cc.credit_limit, cc.account_id, + cp.currency, cp.bank_id, cp.bank_name, + ca.quota_mode AS account_quota_mode, ca.shared_credit_limit, + b.quota_mode AS bank_quota_mode FROM credit_cards cc LEFT JOIN card_products cp ON cc.card_product_id = cp.id + LEFT JOIN banks b ON cp.bank_id = b.id + LEFT JOIN credit_accounts ca ON cc.account_id = ca.id WHERE cc.id IN (${placeholders}) AND cc.status = 'active'`, cardIds ) if (error) throw new Error(error.message) - // 额度为 0 的卡(例如额度未知的外币卡)不进分母:它们只会把分母撑大、 - // 让使用率假性变低,属于把未知当利好。 - const cardsWithLimit = (cards || []).filter(card => (Number(card.credit_limit) || 0) > 0) + + // 两级聚合:独立账户/卡逐卡累加,共享额度池同一 (holder_id, bank, currency) 每池仅计 1 次 + const limitItems: Array<{ amount: number; currency: string }> = [] + const sharedPools: Record = {} + + for (const card of cards || []) { + const cardLimit = Number(card.credit_limit) || 0 + const isShared = + card.account_quota_mode === 'shared' || + (!card.account_quota_mode && card.bank_quota_mode === 'shared') + + if (!isShared) { + if (cardLimit > 0) { + limitItems.push({ + amount: cardLimit, + currency: card.currency ?? displayCurrency, + }) + } + } else { + const bankKey = card.bank_id || card.bank_name || 'unknown' + const poolKey = `${card.holder_id}_${bankKey}_${card.currency ?? displayCurrency}` + if (!sharedPools[poolKey]) { + sharedPools[poolKey] = { + currency: card.currency ?? displayCurrency, + sharedLimit: + card.shared_credit_limit != null ? Number(card.shared_credit_limit) : undefined, + maxCardLimit: cardLimit, + } + } else { + if (card.shared_credit_limit != null) { + sharedPools[poolKey].sharedLimit = Math.max( + sharedPools[poolKey].sharedLimit ?? 0, + Number(card.shared_credit_limit) + ) + } + sharedPools[poolKey].maxCardLimit = Math.max( + sharedPools[poolKey].maxCardLimit, + cardLimit + ) + } + } + } + + for (const pool of Object.values(sharedPools)) { + const poolAmount = pool.sharedLimit ?? pool.maxCardLimit + if (poolAmount > 0) { + limitItems.push({ + amount: poolAmount, + currency: pool.currency, + }) + } + } + creditLimit = sumByCurrency( - cardsWithLimit, - card => ({ amount: Number(card.credit_limit) || 0, currency: card.currency ?? displayCurrency }), + limitItems, + item => item, displayCurrency, rates ) diff --git a/lib/api/banks.server.ts b/lib/api/banks.server.ts index b308576..ae2be32 100644 --- a/lib/api/banks.server.ts +++ b/lib/api/banks.server.ts @@ -6,6 +6,14 @@ export interface BankOption { name: string } +export interface BankItem { + id: string + name: string + short_name?: string | null + quota_mode?: string | null + statement_mode?: string | null +} + /** 启用中的银行,按名称排序;供固定支出等表单选择归属银行。 */ export async function getBankNames(): Promise { const { data, error } = await query( @@ -14,3 +22,12 @@ export async function getBankNames(): Promise { if (error) throw new Error(error.message) return data ?? [] } + +/** 启用中的完整银行列表,含简称与额度/账单模式;供卡片选择器精确绑定。 */ +export async function getBanks(): Promise { + const { data, error } = await query( + 'SELECT id, name, short_name, quota_mode, statement_mode FROM banks WHERE is_active = 1 ORDER BY name' + ) + if (error) throw new Error(error.message) + return data ?? [] +} diff --git a/lib/api/banks.ts b/lib/api/banks.ts index cf43ecb..193d330 100644 --- a/lib/api/banks.ts +++ b/lib/api/banks.ts @@ -2,8 +2,12 @@ import type * as Server from './banks.server' import { callRpc } from './rpc-client' -export type { BankOption } from './banks.server' +export type { BankOption, BankItem } from './banks.server' export function getBankNames(...args: Parameters) { return callRpc('banks', 'getBankNames', ...args) } + +export function getBanks(...args: Parameters) { + return callRpc('banks', 'getBanks', ...args) +} diff --git a/lib/api/bills.server.ts b/lib/api/bills.server.ts index ec720b5..406bbbe 100644 --- a/lib/api/bills.server.ts +++ b/lib/api/bills.server.ts @@ -1,8 +1,7 @@ import { query, queryOne, execute, batch, uuid, now, today } from "../db"; -import type { Bill, Payment, CreditCard, CardProduct } from "../types"; +import type { Bill, Payment, CreditCard, CardProduct, BillCardSubtotal, CreditAccount, CardHolder } from "../types"; import { getDueDate, - getLoanNextDueDate, effectiveBillAmount, billEffectiveMinPayment, billEffectiveDueDate, @@ -10,6 +9,9 @@ import { billStatusRecalcStatement, nextBillingDateOf, isValidCalendarDate, + isBillUnissued, + calculateCardGracePeriod, + diffInCalendarDays, } from "../utils"; import { format } from "date-fns"; import { RpcDomainError } from "./errors"; @@ -23,6 +25,8 @@ export type BillDashboardItem = Bill & { days_until_due: number; interest_free_days_left: number; computed_status: Bill["status"]; + subtotals?: BillCardSubtotal[]; + unallocated_amount?: number; }; export type BillWithCard = Bill & { @@ -32,6 +36,8 @@ export type BillWithCard = Bill & { card_number_last4?: string; card_product?: CardProduct; }; + account?: Partial; + account_card_tails?: string; }; export type PaymentWithBill = Payment & { @@ -63,9 +69,12 @@ function computeStatus(bill: Bill, paidAmount: number): Bill["status"] { // 一律用生效金额:用户手填值优先,否则已还金额会跟展示的金额对不上 // (屏幕上写着 800、状态却按导入的 1200 判定部分还款)。 const amount = effectiveBillAmount(bill); - if (amount <= 0 || paidAmount >= amount) return "paid"; + if (amount <= 0 || paidAmount >= amount - 0.01) return "paid"; if (paidAmount > 0) return "partial"; - if (daysUntil(bill.due_date) < 0) return "overdue"; + // 待出账保护:未出账前绝无逾期概念,状态为 unpaid(统一复用 isBillUnissued 日历日口径) + if (isBillUnissued(bill)) return "unpaid"; + const dueDate = billEffectiveDueDate(bill) || bill.due_date; + if (dueDate && diffInCalendarDays(dueDate) < 0) return "overdue"; return "unpaid"; } @@ -74,6 +83,7 @@ function computeStatus(bill: Bill, paidAmount: number): Bill["status"] { interface BillJoinRow extends Record { // bills fields id: string; + account_id: string | null; card_id: string; bill_month: string; statement_start: string | null; @@ -120,6 +130,7 @@ function mapJoinRowToDashboard( ): BillDashboardItem { const bill: Bill = { id: row.id, + account_id: row.account_id ? String(row.account_id) : undefined, card_id: row.card_id, bill_month: row.bill_month, statement_start: row.statement_start || undefined, @@ -270,8 +281,8 @@ export async function getBillDashboardItems( const billIds = rawBills.map((b) => b.id); - // Batch fetch payments and attachments - const [paymentsRes, attachmentsRes] = await Promise.all([ + // Batch fetch payments, attachments, and card subtotals + const [paymentsRes, attachmentsRes, subtotalsRes] = await Promise.all([ query( `SELECT id, bill_id, amount, paid_at, channel, note FROM payments WHERE bill_id IN (${billIds.map(() => "?").join(",")})`, billIds, @@ -280,6 +291,10 @@ export async function getBillDashboardItems( `SELECT id, record_id, file_name FROM record_attachments WHERE record_type = 'bill' AND record_id IN (${billIds.map(() => "?").join(",")})`, billIds, ), + query( + `SELECT * FROM bill_card_subtotals WHERE bill_id IN (${billIds.map(() => "?").join(",")})`, + billIds, + ), ]); const paymentsByBill: Record> = {}; @@ -299,9 +314,14 @@ export async function getBillDashboardItems( public_url: `/api/attachments/${a.id}`, }); } + const subtotalsByBill: Record = {}; + for (const s of subtotalsRes.data || []) { + if (!subtotalsByBill[s.bill_id]) subtotalsByBill[s.bill_id] = []; + subtotalsByBill[s.bill_id].push(s); + } - return rawBills.map((row) => - mapJoinRowToDashboard( + return rawBills.map((row) => { + const item = mapJoinRowToDashboard( row, (paymentsByBill[row.id] || []).map((p) => ({ id: p.id, @@ -311,8 +331,22 @@ export async function getBillDashboardItems( note: p.note, })), attachmentsByBill[row.id], - ), - ); + ); + const subs = subtotalsByBill[row.id] || []; + let unallocated_amount: number | undefined; + if (subs.length > 0) { + const subSum = subs.reduce((sum, s) => sum + s.subtotal_amount, 0); + const diff = item.bill_amount - subSum; + if (Math.abs(diff) >= 0.01) { + unallocated_amount = Math.round(diff * 100) / 100; + } + } + return { + ...item, + subtotals: subs, + unallocated_amount, + }; + }); } export async function getBillById(id: string): Promise { @@ -344,49 +378,7 @@ export async function getBillById(id: string): Promise { return withCreditCardProductFields(billWithCard); } -export function calculateCardGracePeriod( - card: CreditCard & { card_product: CardProduct }, - today: Date = new Date(), -) { - const d = new Date(today); - d.setHours(0, 0, 0, 0); - const billingDay = Number(card.override_billing_day ?? card.billing_day ?? 10); - if (card.card_type === "loan" && card.loan_due_day) { - const nextDueDate = getLoanNextDueDate(card.loan_due_day, d); - const diffMs = nextDueDate.getTime() - d.getTime(); - return { - billingDay, - nextBillingDate: nextDueDate, - nextDueDate, - graceDays: Math.max(1, Math.ceil(diffMs / (24 * 60 * 60 * 1000))), - }; - } - let purchaseMonth = new Date(d.getFullYear(), d.getMonth(), 1); - const effectiveBillingDay = Math.min( - billingDay, - new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate(), - ); - // 账单日次日起的交易归下一期:账单日当天刷卡当天出账(多数国内行 - // 口径),当天交易进当期账单、免息最短;账单日后一天刷卡才是最长 - // 免息的第一天(今天 == 账单日 → purchaseMonth 留在本月,当期出账 - // 最早、免息天数最小;今天 == 账单日+1 → 归下一期,免息期最长)。 - if (d.getDate() > effectiveBillingDay) { - purchaseMonth = new Date(d.getFullYear(), d.getMonth() + 1, 1); - } - const nextBillingDate = new Date( - purchaseMonth.getFullYear(), - purchaseMonth.getMonth(), - effectiveBillingDay, - ); - const nextDueDate = getDueDate(card, card.card_product, purchaseMonth); - const diffMs = nextDueDate.getTime() - d.getTime(); - return { - billingDay, - nextBillingDate, - nextDueDate, - graceDays: Math.max(1, Math.ceil(diffMs / (24 * 60 * 60 * 1000))), - }; -} +export { calculateCardGracePeriod }; export interface CardWithBillsSummary { card: CreditCard & { card_product: CardProduct }; @@ -400,6 +392,10 @@ export interface CardWithBillsSummary { nextBillingDate: Date; nextDueDate: Date; historyBills: BillDashboardItem[]; + account?: CreditAccount; + isAnchorCard?: boolean; + suppressMissingStatement?: boolean; + memberCards?: CreditCard[]; } export async function getCardsWithBillsSummary(userId?: string): Promise { @@ -419,6 +415,28 @@ export async function getCardsWithBillsSummary(userId?: string): Promise c.account_id).filter(Boolean))) as string[]; + let accountMap: Record = {}; + if (accountIds.length > 0) { + const { data: accounts } = await query( + `SELECT * FROM credit_accounts WHERE id IN (${accountIds.map(() => "?").join(",")})`, + accountIds, + ); + if (accounts) { + accountMap = accounts.reduce((acc, a) => ({ ...acc, [a.id]: a }), {}); + } + } + + // 按 account_id 聚合同账户成员卡 + const memberCardsByAccountId: Record = {}; + for (const c of cards) { + if (c.account_id) { + if (!memberCardsByAccountId[c.account_id]) memberCardsByAccountId[c.account_id] = []; + memberCardsByAccountId[c.account_id].push(c); + } + } + const productIds = Array.from(new Set(cards.map((c) => c.card_product_id).filter(Boolean))); let productMap: Record = {}; if (productIds.length > 0) { @@ -437,10 +455,16 @@ export async function getCardsWithBillsSummary(userId?: string): Promise(); + const billsByAccountId = new Map(); for (const b of allBills) { const cid = b.card_id; if (!billsByCardId.has(cid)) billsByCardId.set(cid, []); billsByCardId.get(cid)!.push(b); + + if (b.account_id) { + if (!billsByAccountId.has(b.account_id)) billsByAccountId.set(b.account_id, []); + billsByAccountId.get(b.account_id)!.push(b); + } } return cards.map((card) => { @@ -457,23 +481,70 @@ export async function getCardsWithBillsSummary(userId?: string): Promise(); + cardBills = []; + for (const b of [...accBills, ...directBills]) { + if (!seen.has(b.id)) { + seen.add(b.id); + cardBills.push(b); + } + } + } else { + cardBills = billsByCardId.get(card.id) || []; + } + + const normalizeMonth = (m?: string | null) => { + if (!m) return ""; + const cleaned = m.replace(/[^0-9]/g, ""); + return cleaned.length === 6 ? `${cleaned.slice(0, 4)}-${cleaned.slice(4, 6)}` : m; + }; const historyBills = [...cardBills].sort((a, b) => { - const timeA = new Date(a.due_date || a.statement_end || "2000-01-01").getTime(); - const timeB = new Date(b.due_date || b.statement_end || "2000-01-01").getTime(); + const mA = normalizeMonth(a.bill_month); + const mB = normalizeMonth(b.bill_month); + if (mA && mB && mA !== mB) { + return mB.localeCompare(mA); + } + if (mA && !mB) return -1; + if (!mA && mB) return 1; + const dueA = + billEffectiveDueDate(a) || a.due_date || a.statement_end || a.statement_date || "2000-01-01"; + const dueB = + billEffectiveDueDate(b) || b.due_date || b.statement_end || b.statement_date || "2000-01-01"; + const timeA = new Date(dueA).getTime(); + const timeB = new Date(dueB).getTime(); return timeB - timeA; }); + const unpaidBills = historyBills.filter((b) => b.computed_status !== "paid"); const activeBill = unpaidBills.length > 0 ? unpaidBills[0] : historyBills[0] || null; - const unpaidAmount = unpaidBills.reduce( - (sum, b) => sum + (b.remaining_amount > 0 ? b.remaining_amount : effectiveBillAmount(b)), - 0, - ); + + // 非锚点副卡不重复计算待还金额(避免列表按卡累加时额度翻倍) + const unpaidAmount = isAnchorCard + ? unpaidBills.reduce( + (sum, b) => sum + (b.remaining_amount > 0 ? b.remaining_amount : effectiveBillAmount(b)), + 0, + ) + : 0; + + const isUnissuedBill = (b: BillDashboardItem) => isBillUnissued(b); + let status: CardWithBillsSummary["status"] = "unissued"; if ( unpaidBills.some( (b) => - b.computed_status === "overdue" || (b.days_until_due < 0 && b.computed_status !== "paid"), + b.computed_status === "overdue" || + (b.days_until_due < 0 && b.computed_status !== "paid" && !isUnissuedBill(b)), ) ) { status = "overdue"; @@ -482,6 +553,10 @@ export async function getCardsWithBillsSummary(userId?: string): Promise 0) { status = "unpaid"; } + + // 合并账户的非锚点卡抑制缺账告警 + const suppressMissingStatement = isMergedAccount && !isAnchorCard; + return { card: cardWithProduct, holder_id: card.holder_id, @@ -493,6 +568,10 @@ export async function getCardsWithBillsSummary(userId?: string): Promise & { items?: BillItemInput[] }, + bill: Omit & { + items?: BillItemInput[]; + subtotals?: Array<{ + card_id?: string | null; + card_tail: string; + subtotal_amount: number; + currency?: string; + }>; + }, ): Promise { const id = uuid(); - const { items: _items, ...billRow } = bill; + const { items: _items, subtotals, ...billRow } = bill; void _items; + + let accountId = billRow.account_id || null; + let anchorCardId = billRow.card_id; + + // 若未传 account_id,从所属卡片查出其 account_id + const { data: cardRow } = await queryOne<{ account_id: string | null }>( + "SELECT account_id FROM credit_cards WHERE id = ?", + [billRow.card_id], + ); + if (!accountId && cardRow?.account_id) { + accountId = cardRow.account_id; + } + + // 若所属账户是 merged,确保 card_id 对齐账户的 primary_card_id + if (accountId) { + const { data: acc } = await queryOne<{ statement_mode: string; primary_card_id: string | null }>( + "SELECT statement_mode, primary_card_id FROM credit_accounts WHERE id = ?", + [accountId], + ); + if (acc?.statement_mode === "merged" && acc.primary_card_id) { + anchorCardId = acc.primary_card_id; + } + } + const { error } = await execute( - `INSERT INTO bills (id, card_id, bill_month, statement_start, statement_end, statement_date, bill_amount, min_payment, due_date, status) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + `INSERT INTO bills (id, account_id, card_id, bill_month, statement_start, statement_end, statement_date, bill_amount, min_payment, due_date, status) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ id, - billRow.card_id, + accountId, + anchorCardId, billRow.bill_month, billRow.statement_start || null, billRow.statement_end || null, @@ -536,6 +648,30 @@ export async function createBill( ], ); if (error) throw new Error(error.message); + + // 批量保存分卡小计(如果有) + if (subtotals && subtotals.length > 0) { + for (const sub of subtotals) { + const subId = uuid(); + await execute( + `INSERT INTO bill_card_subtotals (id, bill_id, card_id, card_tail, subtotal_amount, currency, source) + VALUES (?, ?, ?, ?, ?, ?, 'manual') + ON CONFLICT(bill_id, card_tail) DO UPDATE SET + card_id = excluded.card_id, + subtotal_amount = excluded.subtotal_amount, + currency = excluded.currency`, + [ + subId, + id, + sub.card_id || null, + sub.card_tail, + sub.subtotal_amount, + sub.currency || "CNY", + ], + ); + } + } + const created = await getBillById(id); if (!created) throw new Error("账单创建失败"); return created as unknown as Bill; @@ -545,17 +681,27 @@ export interface BillDetail { bill: Bill & { card?: CreditCard & { card_product?: CardProduct; - card_holder?: { id: string; name: string }; + card_holder?: CardHolder; }; + account?: CreditAccount; + subtotals?: BillCardSubtotal[]; + unallocated_amount?: number; + member_cards?: Array<{ + id: string; + card_number_last4?: string; + name_override?: string; + status: CreditCard["status"]; + }>; }; payments: Payment[]; } -/** Bill detail page: bill + card + product + holder + payments in one call. */ +/** Bill detail page: bill + card + product + holder + payments + account + subtotals in one call. */ export async function getBillDetail(billId: string): Promise { const { data: billRow, error } = await queryOne>( `SELECT b.*, cc.id AS c_id, cc.holder_id AS c_holder_id, cc.card_product_id AS c_card_product_id, cc.card_number_last4 AS c_card_number_last4, cc.credit_limit AS c_credit_limit, + cc.credit_limit_override AS c_credit_limit_override, cc.billing_day AS c_billing_day, cc.status AS c_status, cc.card_type AS c_card_type, cc.loan_due_day AS c_loan_due_day, cc.override_billing_day AS c_override_billing_day, cc.override_due_type AS c_override_due_type, cc.override_due_value AS c_override_due_value, @@ -565,11 +711,22 @@ export async function getBillDetail(billId: string): Promise { cp.card_name AS p_card_name, cp.currency AS p_currency, cp.payment_due_type AS p_payment_due_type, cp.payment_due_value AS p_payment_due_value, cp.annual_fee AS p_annual_fee, cp.annual_fee_waiver AS p_annual_fee_waiver, cp.is_active AS p_is_active, cp.created_at AS p_created_at, - ch.id AS h_id, ch.name AS h_name + ch.id AS h_id, ch.name AS h_name, ch.created_by AS h_created_by, + ch.avatar_color AS h_avatar_color, ch.created_at AS h_created_at, + ch.phone AS h_phone, ch.email AS h_email, ch.managed_by AS h_managed_by, + ch.auth_user_id AS h_auth_user_id, + ca.id AS ca_id, ca.holder_id AS ca_holder_id, ca.bank_id AS ca_bank_id, + ca.bank_name AS ca_bank_name, ca.currency AS ca_currency, ca.account_tail AS ca_account_tail, + ca.statement_mode AS ca_statement_mode, ca.quota_mode AS ca_quota_mode, + ca.shared_credit_limit AS ca_shared_credit_limit, ca.billing_day AS ca_billing_day, + ca.due_type AS ca_due_type, ca.due_value AS ca_due_value, + ca.primary_card_id AS ca_primary_card_id, ca.label AS ca_label, ca.status AS ca_status, + ca.created_at AS ca_created_at, ca.updated_at AS ca_updated_at FROM bills b LEFT JOIN credit_cards cc ON b.card_id = cc.id LEFT JOIN card_products cp ON cc.card_product_id = cp.id LEFT JOIN card_holders ch ON cc.holder_id = ch.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 b.id = ?`, [billId], ); @@ -587,13 +744,15 @@ export async function getBillDetail(billId: string): Promise { if (row.c_id) { const card: CreditCard & { card_product?: CardProduct; - card_holder?: { id: string; name: string }; + card_holder?: CardHolder; } = { id: row.c_id as string, holder_id: row.c_holder_id as string, card_product_id: row.c_card_product_id as string, card_number_last4: (row.c_card_number_last4 as string) || undefined, credit_limit: row.c_credit_limit as number, + credit_limit_override: + row.c_credit_limit_override != null ? (row.c_credit_limit_override as number) : undefined, billing_day: row.c_billing_day as number, status: row.c_status as CreditCard["status"], card_type: row.c_card_type as CreditCard["card_type"], @@ -623,11 +782,82 @@ export async function getBillDetail(billId: string): Promise { }; } if (row.h_id) { - card.card_holder = { id: row.h_id as string, name: (row.h_name as string) || "" }; + card.card_holder = { + id: row.h_id as string, + name: (row.h_name as string) || "", + created_by: (row.h_created_by as string) || "", + avatar_color: (row.h_avatar_color as string) || "#1976d2", + created_at: (row.h_created_at as string) || "", + phone: (row.h_phone as string) || undefined, + email: (row.h_email as string) || undefined, + managed_by: (row.h_managed_by as string) || undefined, + auth_user_id: (row.h_auth_user_id as string) || undefined, + }; } bill.card = card; } + // 组装 account + if (row.ca_id) { + bill.account = { + id: row.ca_id as string, + holder_id: row.ca_holder_id as string, + bank_id: (row.ca_bank_id as string) || undefined, + bank_name: (row.ca_bank_name as string) || "", + currency: (row.ca_currency as string) || "CNY", + account_tail: (row.ca_account_tail as string) || undefined, + statement_mode: row.ca_statement_mode as CreditAccount["statement_mode"], + quota_mode: row.ca_quota_mode as CreditAccount["quota_mode"], + shared_credit_limit: + row.ca_shared_credit_limit != null ? (row.ca_shared_credit_limit as number) : undefined, + billing_day: row.ca_billing_day as number, + due_type: row.ca_due_type as CreditAccount["due_type"], + due_value: row.ca_due_value as number, + primary_card_id: (row.ca_primary_card_id as string) || undefined, + label: (row.ca_label as string) || undefined, + status: row.ca_status as CreditAccount["status"], + created_at: row.ca_created_at as string, + updated_at: row.ca_updated_at as string, + }; + } + + // 查询分卡小计 + const { data: subtotals } = await query( + "SELECT * FROM bill_card_subtotals WHERE bill_id = ? ORDER BY card_tail ASC", + [billId], + ); + const subs = subtotals || []; + bill.subtotals = subs; + + // 计算未归卡差额 + if (subs.length > 0) { + const sum = subs.reduce((acc, s) => acc + s.subtotal_amount, 0); + const diff = bill.bill_amount - sum; + if (Math.abs(diff) >= 0.01) { + bill.unallocated_amount = Math.round(diff * 100) / 100; + } + } + + // 查询同账户成员卡 + const targetAccountId = bill.account_id || (row.ca_id as string | undefined); + if (targetAccountId) { + const { data: memberCards } = await query<{ + id: string; + card_number_last4: string | null; + name_override: string | null; + status: string; + }>( + "SELECT id, card_number_last4, name_override, status FROM credit_cards WHERE account_id = ?", + [targetAccountId], + ); + bill.member_cards = (memberCards || []).map((m) => ({ + id: m.id, + card_number_last4: m.card_number_last4 || undefined, + name_override: m.name_override || undefined, + status: m.status as CreditCard["status"], + })); + } + const { data: paymentRows, error: payError } = await query( "SELECT * FROM payments WHERE bill_id = ? ORDER BY paid_at DESC", [billId], @@ -850,7 +1080,13 @@ export async function setCardManualBillAmount(cardId: string, amount: number): P } export async function getBillsByHolder(holderId: string): Promise { - const { data, error } = await query( + const { data, error } = await query< + BillJoinRow & { + ca_id?: string | null; + ca_statement_mode?: string | null; + ca_quota_mode?: string | null; + } + >( `SELECT b.*, cc.id AS cc_id, cc.holder_id AS cc_holder_id, cc.card_product_id AS cc_card_product_id, cc.card_number_last4 AS cc_card_number_last4, cc.credit_limit AS cc_credit_limit, cc.billing_day AS cc_billing_day, cc.status AS cc_status, cc.card_type AS cc_card_type, @@ -861,21 +1097,58 @@ export async function getBillsByHolder(holderId: string): Promise { + + const rawRows = data || []; + // 查找涉及的合并账户,收集同账户卡尾号 + const mergedAccountIds = Array.from( + new Set( + rawRows + .filter((r) => r.ca_statement_mode === "merged" && r.ca_id) + .map((r) => r.ca_id as string), + ), + ); + const tailsByAccountId: Record = {}; + if (mergedAccountIds.length > 0) { + const { data: memberCards } = await query<{ account_id: string; card_number_last4: string | null }>( + `SELECT account_id, card_number_last4 FROM credit_cards WHERE account_id IN (${mergedAccountIds.map(() => "?").join(",")})`, + mergedAccountIds, + ); + for (const mc of memberCards || []) { + if (mc.card_number_last4) { + if (!tailsByAccountId[mc.account_id]) tailsByAccountId[mc.account_id] = []; + tailsByAccountId[mc.account_id].push(mc.card_number_last4); + } + } + } + + return rawRows.map((row) => { const dashboard = mapJoinRowToDashboard(row, []); + const accountTails = row.ca_id && tailsByAccountId[row.ca_id] + ? tailsByAccountId[row.ca_id].join(" / ") + : undefined; return withCreditCardProductFields({ ...dashboard, credit_cards: dashboard.card, - } as BillWithCard); + account: row.ca_id + ? { + id: row.ca_id, + statement_mode: row.ca_statement_mode, + quota_mode: row.ca_quota_mode, + } + : undefined, + account_card_tails: accountTails, + } as unknown as BillWithCard); }); } diff --git a/lib/api/cards.server.ts b/lib/api/cards.server.ts index 178e21f..20dfec9 100644 --- a/lib/api/cards.server.ts +++ b/lib/api/cards.server.ts @@ -1,11 +1,21 @@ -import { query, queryOne, execute, uuid } from '../db' -import type { CardProduct, CreditCard, CardHolder, Bill, Benefit, BenefitUsage } from '@/lib/types' +import { query, queryOne, execute, batch, uuid, now } from '../db' +import type { CardProduct, CreditCard, CardHolder, Bill, Benefit, BenefitUsage, CardDueDateResolution } from '@/lib/types' import { normalizeAliases } from '../utils' import { legacyBenefitPeriodStart } from './benefits.server' import { localDateInZone } from '../opportunities/dates' import type { OpportunityActor } from '../opportunities/types' import type { OpportunityDto } from '../opportunities/queries.server' import { getCardOpportunities } from '../opportunities/queries.server' +import { + loadCardDueDateResolution, + buildDueDateReasonReport, + type DueDateReasonReport, + type CardForDueDateSummary, + type BillForDueDateSummary, + type GmailSyncMessageLite, + type BillImportDraftLite, +} from '../due-date-summary' +import type { EmailParseLog } from '../types' export type CreditCardWithProduct = CreditCard & { card_product?: CardProduct @@ -16,9 +26,11 @@ export type CreditCardWithProduct = CreditCard & { interface CardJoinRow { id: string holder_id: string + account_id: string | null card_product_id: string card_number_last4: string | null credit_limit: number + credit_limit_override: number | null billing_day: number status: string card_type: string @@ -50,9 +62,11 @@ function joinRowToCard(row: CardJoinRow): CreditCardWithProduct { const card: CreditCardWithProduct = { id: row.id, holder_id: row.holder_id, + account_id: row.account_id || undefined, card_product_id: row.card_product_id, card_number_last4: row.card_number_last4 || undefined, credit_limit: row.credit_limit, + credit_limit_override: row.credit_limit_override != null ? Number(row.credit_limit_override) : undefined, billing_day: row.billing_day, status: row.status as CreditCard['status'], card_type: row.card_type as CreditCard['card_type'], @@ -87,7 +101,7 @@ function joinRowToCard(row: CardJoinRow): CreditCardWithProduct { return card } -const CARD_SELECT = `cc.id, cc.holder_id, cc.card_product_id, cc.card_number_last4, cc.credit_limit, +const CARD_SELECT = `cc.id, cc.holder_id, cc.account_id, cc.card_product_id, cc.card_number_last4, cc.credit_limit, cc.credit_limit_override, cc.billing_day, cc.status, cc.card_type, cc.loan_due_day, cc.override_billing_day, cc.override_due_type, cc.override_due_value, cc.name_override, cc.annual_fee_override, cc.created_at, cc.issued_on, cc.activated_on, @@ -154,6 +168,8 @@ export interface CardDetail { benefits: CardDetailBenefit[] /** 统一机会 DTO(Task 11):默认最多 3 条,完整列表走机会页。 */ opportunities: OpportunityDto[] + /** 还款日确切性与四类缺失原因解析(严格区分,绝不编造日期) */ + dueDateResolution?: CardDueDateResolution } function computeBillStatus(billAmount: number, paid: number, dueDate: string): Bill['status'] { @@ -266,7 +282,14 @@ export async function getCardDetail( opportunities = [] } - return { card, bills: billList, benefits, opportunities } + let dueDateResolution: CardDueDateResolution | undefined + try { + dueDateResolution = await loadCardDueDateResolution(card) + } catch (err) { + console.error('加载卡片还款日解析失败:', err) + } + + return { card, bills: billList, benefits, opportunities, dueDateResolution } } export async function getCardsByHolder(holderId: string): Promise { @@ -278,17 +301,204 @@ export async function getCardsByHolder(holderId: string): Promise): Promise { +export type CreateCardInput = { + holder_id: string + billing_day: number + account_id?: string | null + card_product_id?: string + bank_id?: string + card_number_last4?: string | null + credit_limit?: number + credit_limit_override?: number | null + status?: CreditCard['status'] + card_type?: CreditCard['card_type'] + loan_due_day?: number | null + override_billing_day?: number | null + override_due_type?: CreditCard['override_due_type'] + override_due_value?: number | null + name_override?: string | null + annual_fee_override?: number | null + account_mode_override?: CreditCard['account_mode_override'] + issued_on?: string | null + activated_on?: string | null +} + +export async function ensureDefaultCardProductForBank(bankId: string): Promise { + const { data: defaultProduct } = await queryOne( + 'SELECT * FROM card_products WHERE bank_id = ? AND is_active = 1 ORDER BY (CASE WHEN id = ? THEN 0 ELSE 1 END), created_at ASC LIMIT 1', + [bankId, `cp_default_${bankId}`] + ) + if (defaultProduct) return defaultProduct + + const { data: bank } = await queryOne<{ id: string; name: string; country?: string }>( + 'SELECT id, name, country FROM banks WHERE id = ?', + [bankId] + ) + if (!bank) return null + + const defId = `cp_default_${bank.id}` + await execute( + `INSERT OR IGNORE INTO card_products (id, country, bank_id, bank_name, card_name, currency, payment_due_type, payment_due_value, annual_fee, is_active) + VALUES (?, ?, ?, ?, ?, 'CNY', 'after_billing', 20, 0, 1)`, + [defId, bank.country || 'CN', bank.id, bank.name, '标准信用卡'] + ) + const { data: createdProd } = await queryOne('SELECT * FROM card_products WHERE id = ?', [defId]) + return createdProd || null +} + +export async function createCard(card: CreateCardInput): Promise { const id = uuid() + let productId = card.card_product_id + let product: CardProduct | null = null + + if (productId) { + const { data } = await queryOne('SELECT * FROM card_products WHERE id = ?', [productId]) + product = data + } + + if (!product && card.bank_id) { + product = await ensureDefaultCardProductForBank(card.bank_id) + if (product) { + productId = product.id + } + } + + if (!productId) { + throw new Error('缺少卡产品或所属银行') + } + + // 自定义还款规则范围校验 + if (card.override_due_type) { + if (card.override_due_value === undefined || card.override_due_value === null) { + throw new Error('启用自定义还款规则时必须提供有效的还款日数值') + } + const val = Number(card.override_due_value) + if (!Number.isInteger(val)) { + throw new Error('还款日数值必须为整数') + } + if (card.override_due_type === 'after_billing') { + if (val < 0) { + throw new Error('账单日后还款天数必须大于或等于 0') + } + } else if (card.override_due_type === 'fixed') { + if (val < 1 || val > 31) { + throw new Error('固定还款日必须在 1 到 31 之间') + } + } else { + throw new Error('不支持的还款规则类型') + } + } + + // 名称覆盖清洗:若与产品名称相同则置空,否则去除首尾空格 + let nameOverride: string | null = null + if (card.name_override && card.name_override.trim()) { + const trimmed = card.name_override.trim() + if (!product || trimmed !== product.card_name) { + nameOverride = trimmed + } + } + + const limitOverride = card.credit_limit_override != null + ? (Number(card.credit_limit_override) > 0 ? Number(card.credit_limit_override) : null) + : (card.credit_limit && Number(card.credit_limit) > 0 ? Number(card.credit_limit) : null) + const limitValue = limitOverride ?? (Number(card.credit_limit) || 0) + + // 关联或创建 credit_account + let accountId = card.account_id || null + if (!accountId) { + const currency = product?.currency || 'CNY' + const bankKey = product?.bank_id || product?.bank_name || 'UNKNOWN' + // 若不是贷款卡,检查是否已有同持卡人同银行同币种的 active merged 账户 + if ((card.card_type || 'credit') !== 'loan') { + const { data: existingAccount } = await queryOne<{ id: string }>( + `SELECT id FROM credit_accounts + WHERE holder_id = ? + AND COALESCE(bank_id, bank_name) = ? + AND currency = ? + AND statement_mode = 'merged' + AND status = 'active' + ORDER BY created_at ASC LIMIT 1`, + [card.holder_id, bankKey, currency] + ) + if (existingAccount) { + accountId = existingAccount.id + } + } + + if (!accountId) { + // 检查发卡行模式 + let defaultStatementMode: 'merged' | 'independent' = 'independent' + let defaultQuotaMode: 'shared' | 'independent' = 'independent' + if (product?.bank_id) { + const { data: bankRow } = await queryOne<{ statement_mode: string; quota_mode: string }>( + 'SELECT statement_mode, quota_mode FROM banks WHERE id = ?', + [product.bank_id] + ) + if (bankRow?.statement_mode === 'merged') defaultStatementMode = 'merged' + if (bankRow?.quota_mode === 'shared') defaultQuotaMode = 'shared' + } else if (product?.bank_name) { + if (/招商|民生|上海银行|北京银行/.test(product.bank_name)) { + defaultStatementMode = 'merged' + defaultQuotaMode = 'shared' + } + } + + if (card.card_type === 'loan') { + defaultStatementMode = 'independent' + defaultQuotaMode = 'independent' + } + + accountId = uuid() + await execute( + `INSERT INTO credit_accounts ( + id, holder_id, bank_id, bank_name, currency, statement_mode, quota_mode, + shared_credit_limit, billing_day, due_type, due_value, primary_card_id, status, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 'active', ?, ?)`, + [ + accountId, + card.holder_id, + product?.bank_id || null, + product?.bank_name || '未知银行', + currency, + defaultStatementMode, + defaultQuotaMode, + limitValue > 0 ? limitValue : null, + card.billing_day, + card.override_due_type || product?.payment_due_type || 'after_billing', + card.override_due_value || product?.payment_due_value || 20, + now(), + now() + ] + ) + } + } + const { error } = await execute( - `INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type, loan_due_day, override_billing_day, override_due_type, override_due_value, issued_on, activated_on) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - [id, card.holder_id, card.card_product_id, card.card_number_last4 || null, card.credit_limit, - card.billing_day, card.status || 'active', card.card_type || 'credit', card.loan_due_day || null, - card.override_billing_day || null, card.override_due_type || null, card.override_due_value || null, - card.issued_on ?? null, card.activated_on ?? null] + `INSERT INTO credit_cards ( + id, holder_id, account_id, card_product_id, card_number_last4, credit_limit, credit_limit_override, + billing_day, status, card_type, loan_due_day, override_billing_day, + override_due_type, override_due_value, name_override, annual_fee_override, + account_mode_override, issued_on, activated_on + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + id, card.holder_id, accountId, productId, card.card_number_last4 || null, limitValue, limitOverride, + card.billing_day, card.status || 'active', card.card_type || 'credit', card.loan_due_day || null, + null, // override_billing_day 归一合并后新建卡统一为 null + card.override_due_type || null, card.override_due_value || null, nameOverride, + card.annual_fee_override ?? null, card.account_mode_override ?? null, + card.issued_on ?? null, card.activated_on ?? null + ] ) if (error) throw new Error(error.message) + + // 确保账户有 primary_card_id 锚点卡 + if (accountId) { + await execute( + 'UPDATE credit_accounts SET primary_card_id = ? WHERE id = ? AND primary_card_id IS NULL', + [id, accountId] + ) + } + const created = await getCardById(id) if (!created) throw new Error('卡片创建失败') return created @@ -302,24 +512,174 @@ async function getCardById(id: string): Promise { return joinRowToCard(data) } +export type UpdateCardPatch = Partial> & { + bank_id?: string + card_product_id?: string +} + export async function updateCard( id: string, - patch: Partial> + patch: UpdateCardPatch ): Promise { + const currentCard = await getCardById(id) + if (!currentCard) throw new Error('卡片不存在') + + let targetProductId = patch.card_product_id + let targetProduct: CardProduct | null = null + + // 1. 若传了 card_product_id 且试图换绑产品/银行,或仅传 bank_id 且试图更换所属银行 + if (targetProductId && targetProductId !== currentCard.card_product_id) { + const { data: tp } = await queryOne( + 'SELECT * FROM card_products WHERE id = ?', + [targetProductId] + ) + targetProduct = tp + if (!targetProduct && (targetProductId.startsWith('cp_default_') || patch.bank_id)) { + const bId = patch.bank_id || targetProductId.replace('cp_default_', '') + targetProduct = await ensureDefaultCardProductForBank(bId) + if (targetProduct) { + targetProductId = targetProduct.id + } + } + if (!targetProduct) { + throw new Error('目标卡产品不存在') + } + } else if (!targetProductId && patch.bank_id && currentCard.card_product?.bank_id !== patch.bank_id) { + targetProduct = await ensureDefaultCardProductForBank(patch.bank_id) + if (!targetProduct) { + throw new Error('所选银行暂无可用卡产品') + } + targetProductId = targetProduct.id + } + + if (targetProduct) { + // Q3 同币种限制:若已有历史账单,只允许同币种切换 + const { data: billRows } = await queryOne<{ cnt: number }>( + 'SELECT COUNT(*) as cnt FROM bills WHERE card_id = ?', + [id] + ) + const hasBills = (billRows?.cnt ?? 0) > 0 + const curCurrency = currentCard.card_product?.currency || 'CNY' + const targetCurrency = targetProduct.currency || 'CNY' + if (hasBills && curCurrency !== targetCurrency) { + throw new Error('该卡已有历史账单,仅允许切换到同币种卡产品;如需更换币种,请新建卡片') + } + + // 机会台账冲突检查 + const { data: oppAccounts } = await query<{ account_id: string }>( + 'SELECT account_id FROM opportunity_account_cards WHERE card_id = ? AND retired_at IS NULL', + [id] + ) + if (oppAccounts && oppAccounts.length > 0) { + if (currentCard.card_product?.bank_id && targetProduct.bank_id && currentCard.card_product.bank_id !== targetProduct.bank_id) { + throw new Error('这张卡关联了原银行的权益台账,请先去「我的权益」解绑后再换银行') + } + } + } + + // 自定义还款规则范围校验 + if (patch.override_due_type) { + if (patch.override_due_value === undefined || patch.override_due_value === null) { + throw new Error('启用自定义还款规则时必须提供有效的还款日数值') + } + const val = Number(patch.override_due_value) + if (!Number.isInteger(val)) { + throw new Error('还款日数值必须为整数') + } + if (patch.override_due_type === 'after_billing') { + if (val < 0) { + throw new Error('账单日后还款天数必须大于或等于 0') + } + } else if (patch.override_due_type === 'fixed') { + if (val < 1 || val > 31) { + throw new Error('固定还款日必须在 1 到 31 之间') + } + } else { + throw new Error('不支持的还款规则类型') + } + } + + // 2. 持卡人变更校验(防止越权) + if (patch.holder_id && patch.holder_id !== currentCard.holder_id) { + const { data: holders } = await query<{ id: string; created_by: string; auth_user_id: string }>( + 'SELECT id, created_by, auth_user_id FROM card_holders WHERE id IN (?, ?)', + [currentCard.holder_id, patch.holder_id] + ) + const curH = holders?.find(h => h.id === currentCard.holder_id) + const newH = holders?.find(h => h.id === patch.holder_id) + if (!curH || !newH || (curH.created_by && newH.created_by && curH.created_by !== newH.created_by)) { + throw new Error('卡片或目标持卡人不存在,或不属于同一账户') + } + } + + // 3. 额度计算(复用 Task B 逻辑) + let limitOverrideVal = patch.credit_limit_override + let limitVal = patch.credit_limit + + if (patch.credit_limit !== undefined && patch.credit_limit_override === undefined) { + const num = Number(patch.credit_limit) + if (Number.isFinite(num) && num > 0) { + limitOverrideVal = num + limitVal = num + } else { + limitOverrideVal = null + limitVal = 0 + } + } else if (patch.credit_limit_override !== undefined && patch.credit_limit === undefined) { + const num = Number(patch.credit_limit_override) + if (Number.isFinite(num) && num > 0) { + limitVal = num + limitOverrideVal = num + } else { + limitVal = 0 + limitOverrideVal = null + } + } + + // 4. Q2 账单日合并收口:若更新 billing_day,强制清空 override_billing_day + let effectiveOverrideBillingDay = patch.override_billing_day + if (patch.billing_day !== undefined) { + effectiveOverrideBillingDay = null + } + + // 5. 卡片名称覆盖更新处理 + let finalNameOverride = patch.name_override + if (finalNameOverride !== undefined) { + if (finalNameOverride && finalNameOverride.trim()) { + const trimmed = finalNameOverride.trim() + const effectiveProduct = targetProductId + ? (await queryOne('SELECT * FROM card_products WHERE id = ?', [targetProductId]))?.data + : currentCard.card_product + if (effectiveProduct && trimmed === effectiveProduct.card_name) { + finalNameOverride = null + } else { + finalNameOverride = trimmed + } + } else { + finalNameOverride = null + } + } + + const cleanedLast4 = patch.card_number_last4 !== undefined + ? (patch.card_number_last4 && patch.card_number_last4.trim() ? patch.card_number_last4.trim() : null) + : undefined + const fields: string[] = [] const params: unknown[] = [] const fieldMap: Record = { + card_product_id: targetProductId, holder_id: patch.holder_id, - card_number_last4: patch.card_number_last4, - credit_limit: patch.credit_limit, + card_number_last4: cleanedLast4, + credit_limit: limitVal, + credit_limit_override: limitOverrideVal, billing_day: patch.billing_day, status: patch.status, card_type: patch.card_type, loan_due_day: patch.loan_due_day, - override_billing_day: patch.override_billing_day, + override_billing_day: effectiveOverrideBillingDay, override_due_type: patch.override_due_type, override_due_value: patch.override_due_value, - name_override: patch.name_override, + name_override: finalNameOverride, annual_fee_override: patch.annual_fee_override, account_mode_override: patch.account_mode_override, issued_on: patch.issued_on, @@ -334,13 +694,73 @@ export async function updateCard( if (fields.length === 0) throw new Error('没有需要更新的字段') params.push(id) const { error } = await execute(`UPDATE credit_cards SET ${fields.join(', ')} WHERE id = ?`, params) - if (error) throw new Error(error.message) + if (error) { + if (/OPPORTUNITY_CARD_OWNERSHIP_CONFLICT/.test(error.message)) { + throw new Error('该卡已关联权益台账账户,请先在「我的权益」解绑后再更换持卡人') + } + throw new Error(error.message) + } const updated = await getCardById(id) if (!updated) throw new Error('卡片更新失败') return updated } export async function deleteCard(id: string): Promise { + const card = await getCardById(id) + if (!card) return + + const accountId = card.account_id + if (accountId) { + // 检查同账户内是否有其他卡片 + const { data: siblings } = await query<{ id: string }>( + `SELECT id FROM credit_cards + WHERE account_id = ? AND id != ? + ORDER BY (CASE WHEN status = 'active' THEN 0 ELSE 1 END), created_at ASC`, + [accountId, id] + ) + + if (siblings && siblings.length > 0) { + // 仍有其他卡片!检查当前被删卡片是否为 primary_card_id 锚点卡 + const { data: accountRow } = await queryOne<{ primary_card_id: string }>( + 'SELECT primary_card_id FROM credit_accounts WHERE id = ?', + [accountId] + ) + + if (accountRow?.primary_card_id === id) { + const nextPrimaryCardId = siblings[0].id + // 在单一 batch 事务中:将账户锚点及所有 bills.card_id 平滑平移至剩余卡片,再删除目标卡,防止账单误灭失! + await batch([ + { + sql: 'UPDATE credit_accounts SET primary_card_id = ?, updated_at = ? WHERE id = ?', + params: [nextPrimaryCardId, now(), accountId], + }, + { + sql: 'UPDATE bills SET card_id = ? WHERE account_id = ?', + params: [nextPrimaryCardId, accountId], + }, + { + sql: 'DELETE FROM credit_cards WHERE id = ?', + params: [id], + }, + ]) + return + } + } else { + // 账户内最后一张卡片:删除卡片前,先清理关联账户及账单 + await batch([ + { + sql: 'DELETE FROM credit_accounts WHERE id = ?', + params: [accountId], + }, + { + sql: 'DELETE FROM credit_cards WHERE id = ?', + params: [id], + }, + ]) + return + } + } + const { error } = await execute('DELETE FROM credit_cards WHERE id = ?', [id]) if (error) throw new Error(error.message) } @@ -351,6 +771,8 @@ export async function deleteCard(id: string): Promise { * (与 getCardsWithBillsSummary 同谓词),防止把卡移给别人家或从别人家移入。 * 卡上挂着权益台账关联时数据库触发器会拒绝(OPPORTUNITY_CARD_OWNERSHIP_CONFLICT), * 这里转成可读提示,让用户先去权益页解绑。 + * + * 锚点卡守卫:若卡片在原持卡人的多卡合并账户中,先将其平滑拆出,原账户锚点平移给剩余卡。 */ export async function updateCardHolder( userId: string, @@ -373,9 +795,67 @@ export async function updateCardHolder( throw new Error('卡片或目标持卡人不存在,或不属于当前账户') } + // 账户移交守卫:若卡片在原持卡人的多卡合并账户中,先将其从原账户拆出 + let newAccountId = card.account_id || null + if (card.account_id) { + const { data: oldAccount } = await queryOne<{ statement_mode: string; primary_card_id: string }>( + 'SELECT statement_mode, primary_card_id FROM credit_accounts WHERE id = ?', + [card.account_id] + ) + const { data: remainingCards } = await query<{ id: string }>( + 'SELECT id FROM credit_cards WHERE account_id = ? AND id != ? ORDER BY (CASE WHEN status = "active" THEN 0 ELSE 1 END), created_at ASC', + [card.account_id, cardId] + ) + + if (remainingCards && remainingCards.length > 0) { + // 原账户还有其他卡,原账户平滑切换锚点 + if (oldAccount?.primary_card_id === cardId) { + const nextAnchorId = remainingCards[0].id + await batch([ + { + sql: 'UPDATE credit_accounts SET primary_card_id = ?, updated_at = ? WHERE id = ?', + params: [nextAnchorId, now(), card.account_id], + }, + { + sql: 'UPDATE bills SET card_id = ? WHERE account_id = ?', + params: [nextAnchorId, card.account_id], + }, + ]) + } + // 在新持卡人名下新建独立账户 + newAccountId = uuid() + await execute( + `INSERT INTO credit_accounts ( + id, holder_id, bank_id, bank_name, currency, statement_mode, quota_mode, + shared_credit_limit, billing_day, due_type, due_value, primary_card_id, status, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, 'independent', 'independent', NULL, ?, ?, ?, ?, 'active', ?, ?)`, + [ + newAccountId, + newHolderId, + card.card_product?.bank_id || null, + card.card_product?.bank_name || '未知银行', + card.card_product?.currency || 'CNY', + card.billing_day, + card.override_due_type || card.card_product?.payment_due_type || 'after_billing', + card.override_due_value || card.card_product?.payment_due_value || 20, + cardId, + now(), + now(), + ] + ) + } else { + // 只有这一张卡,直接把该 credit_account 的 holder_id 改为 newHolderId + await execute('UPDATE credit_accounts SET holder_id = ?, updated_at = ? WHERE id = ?', [ + newHolderId, + now(), + card.account_id, + ]) + } + } + const { error } = await execute( - 'UPDATE credit_cards SET holder_id = ? WHERE id = ? AND holder_id = ?', - [newHolderId, cardId, card.holder_id] + 'UPDATE credit_cards SET holder_id = ?, account_id = ? WHERE id = ? AND holder_id = ?', + [newHolderId, newAccountId ?? null, cardId, card.holder_id] ) if (error) { if (/OPPORTUNITY_CARD_OWNERSHIP_CONFLICT/.test(error.message)) { @@ -389,3 +869,107 @@ export async function updateCardHolder( } return moved } + +/** + * 汇总当前用户全部卡片及邮件日志/Gmail同步记录的还款日状态与四类缺失原因。 + * 绝不编造日期,按卡/邮件分类汇总给前端与审计入口。 + */ +export async function getDueDateReasonReport(userId?: string): Promise { + let cardCondition = '' + const cardParams: unknown[] = [] + if (userId) { + cardCondition = 'WHERE (ch.created_by = ? OR ch.auth_user_id = ?)' + cardParams.push(userId, userId) + } + const { data: rawCards } = await query>( + `SELECT cc.*, cp.bank_name, cp.card_name, cp.payment_due_type, cp.payment_due_value + 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 + ${cardCondition} + ORDER BY cc.created_at DESC`, + cardParams + ) + const cards: CardForDueDateSummary[] = (rawCards ?? []).map((row) => ({ + id: String(row.id), + holder_id: String(row.holder_id), + card_number_last4: row.card_number_last4 ? String(row.card_number_last4) : null, + billing_day: Number(row.billing_day) || 1, + card_type: (row.card_type === 'loan' ? 'loan' : 'credit') as 'credit' | 'loan', + loan_due_day: row.loan_due_day ? Number(row.loan_due_day) : null, + override_due_type: row.override_due_type as CardForDueDateSummary['override_due_type'], + override_due_value: row.override_due_value ? Number(row.override_due_value) : null, + bank_name: row.bank_name ? String(row.bank_name) : null, + card_name: row.name_override ? String(row.name_override) : (row.card_name ? String(row.card_name) : null), + card_product: row.bank_name ? { + bank_name: String(row.bank_name), + card_name: String(row.card_name ?? ''), + payment_due_type: (row.payment_due_type ?? 'after_billing') as CardProduct['payment_due_type'], + payment_due_value: Number(row.payment_due_value) || 20, + } : null, + })) + + const cardIds = cards.map((c) => c.id) + let bills: BillForDueDateSummary[] = [] + if (cardIds.length > 0) { + const placeholders = cardIds.map(() => '?').join(',') + const { data: billRows } = await query( + `SELECT id, card_id, bill_month, COALESCE(bill_amount_override, bill_amount) AS bill_amount, + statement_date, due_date, due_date_override, created_at + FROM bills WHERE card_id IN (${placeholders}) ORDER BY bill_month DESC LIMIT 500`, + cardIds + ) + bills = billRows ?? [] + } + + let emailLogs: EmailParseLog[] + let gmailMessages: GmailSyncMessageLite[] + let billDrafts: BillImportDraftLite[] + + const ownerIds = userId ? [userId] : [] + if (ownerIds.length > 0) { + const placeholders = ownerIds.map(() => '?').join(',') + const [logsRes, gmailRes, draftsRes] = await Promise.all([ + query( + `SELECT * FROM email_parse_logs WHERE user_id IN (${placeholders}) ORDER BY created_at DESC LIMIT 300`, + ownerIds, + ), + query( + `SELECT gmail_message_id, user_id, from_email, subject, status, bill_id, draft_id, error_msg, created_at + FROM gmail_sync_messages WHERE user_id IN (${placeholders}) ORDER BY created_at DESC LIMIT 300`, + ownerIds, + ), + query( + `SELECT id, created_by, card_id, source_type, parsed_payload, status, created_at + FROM bill_import_drafts WHERE created_by IN (${placeholders}) ORDER BY created_at DESC LIMIT 300`, + ownerIds, + ), + ]) + emailLogs = logsRes.data ?? [] + gmailMessages = gmailRes.data ?? [] + billDrafts = draftsRes.data ?? [] + } else { + const [logsRes, gmailRes, draftsRes] = await Promise.all([ + query(`SELECT * FROM email_parse_logs ORDER BY created_at DESC LIMIT 300`), + query( + `SELECT gmail_message_id, user_id, from_email, subject, status, bill_id, draft_id, error_msg, created_at + FROM gmail_sync_messages ORDER BY created_at DESC LIMIT 300` + ), + query( + `SELECT id, created_by, card_id, source_type, parsed_payload, status, created_at + FROM bill_import_drafts ORDER BY created_at DESC LIMIT 300` + ), + ]) + emailLogs = logsRes.data ?? [] + gmailMessages = gmailRes.data ?? [] + billDrafts = draftsRes.data ?? [] + } + + return buildDueDateReasonReport({ + cards, + bills, + emailLogs, + gmailMessages, + billDrafts, + }) +} diff --git a/lib/api/cards.ts b/lib/api/cards.ts index 506d8b8..35da25b 100644 --- a/lib/api/cards.ts +++ b/lib/api/cards.ts @@ -42,3 +42,6 @@ export function updateCard(...args: Parameters) { export function updateCardHolder(cardId: string, newHolderId: string) { return callRpc('cards', 'updateCardHolder', '', cardId, newHolderId) } +export function getDueDateReasonReport() { + return callRpc('cards', 'getDueDateReasonReport', '') +} diff --git a/lib/api/holders.server.ts b/lib/api/holders.server.ts index 455ffe4..5b88657 100644 --- a/lib/api/holders.server.ts +++ b/lib/api/holders.server.ts @@ -187,12 +187,21 @@ async function syncHolderAuthUser(holderId: string, email?: string | null): Prom await execute('UPDATE card_holders SET auth_user_id = ? WHERE id = ?', [data?.id ?? null, holderId]) } -export async function createHolder(holder: Omit): Promise { +export type CreateHolderInput = Omit & { + created_by?: string +} + +export async function createHolder(holder: CreateHolderInput): Promise { + const trimmedName = holder.name ? holder.name.trim() : '' + if (!trimmedName) { + throw new Error('持卡人姓名不能为空') + } const id = uuid() const ts = now() + const createdBy = holder.created_by || '' const { error } = await execute( 'INSERT INTO card_holders (id, created_by, managed_by, name, phone, email, avatar_color, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', - [id, holder.created_by, holder.created_by, holder.name, holder.phone || null, holder.email || null, holder.avatar_color || '#1976d2', ts] + [id, createdBy, createdBy, trimmedName, holder.phone || null, holder.email || null, holder.avatar_color || '#7aadff', ts] ) if (error) throw new Error(error.message) await syncHolderAuthUser(id, holder.email) @@ -310,11 +319,28 @@ export async function getHolderStatsPageData(holderId: string): Promise( - 'SELECT * FROM credit_cards WHERE holder_id = ?', [holderId] + const { data: cards, error: cardError } = await query< + CreditCard & { + bank_id?: string | null + bank_name?: string | null + currency?: string | null + account_quota_mode?: string | null + shared_credit_limit?: number | null + bank_quota_mode?: string | null + } + >( + `SELECT cc.*, cp.bank_id, cp.bank_name, cp.currency, + ca.quota_mode AS account_quota_mode, ca.shared_credit_limit, + b.quota_mode AS bank_quota_mode + FROM credit_cards cc + LEFT JOIN card_products cp ON cc.card_product_id = cp.id + LEFT JOIN banks b ON cp.bank_id = b.id + LEFT JOIN credit_accounts ca ON cc.account_id = ca.id + WHERE cc.holder_id = ?`, + [holderId] ) if (cardError) throw new Error(cardError.message) - const allCards = (cards || []) as CreditCard[] + const allCards = cards || [] const activeCards = allCards.filter(c => c.status === 'active') const cardIds = allCards.map(c => c.id) @@ -333,8 +359,43 @@ export async function getHolderStatsPageData(holderId: string): Promise s + (Number(c.credit_limit) || 0), 0) + // Summary: 两级去重聚合总授信额度(共享额度池同银行每池仅计 1 次,不重复叠加) + const sharedPools: Record = {} + let independentLimit = 0 + for (const c of activeCards) { + const limit = Number(c.credit_limit) || 0 + const isShared = + c.account_quota_mode === 'shared' || + (!c.account_quota_mode && c.bank_quota_mode === 'shared') + + if (!isShared) { + if (limit > 0) independentLimit += limit + } else { + const bankKey = c.bank_id || c.bank_name || 'unknown' + const poolKey = `${bankKey}_${c.currency || 'CNY'}` + if (!sharedPools[poolKey]) { + sharedPools[poolKey] = { + sharedLimit: + c.shared_credit_limit != null ? Number(c.shared_credit_limit) : undefined, + maxLimit: limit, + } + } else { + if (c.shared_credit_limit != null) { + sharedPools[poolKey].sharedLimit = Math.max( + sharedPools[poolKey].sharedLimit ?? 0, + Number(c.shared_credit_limit) + ) + } + sharedPools[poolKey].maxLimit = Math.max(sharedPools[poolKey].maxLimit, limit) + } + } + } + + let totalLimit = independentLimit + for (const pool of Object.values(sharedPools)) { + const poolAmount = pool.sharedLimit ?? pool.maxLimit + if (poolAmount > 0) totalLimit += poolAmount + } const unpaidStatuses: Bill['status'][] = ['unpaid', 'partial', 'overdue'] const unpaidBills = allBills.filter(b => unpaidStatuses.includes(b.status)) const totalUsed = unpaidBills.reduce((s, b) => s + (Number(b.bill_amount) || 0), 0) diff --git a/lib/api/member-scope.ts b/lib/api/member-scope.ts index 4d8eaaa..e4ba26d 100644 --- a/lib/api/member-scope.ts +++ b/lib/api/member-scope.ts @@ -43,6 +43,15 @@ export function assertHolderIdsAccess(holderIds: unknown, ctx: MemberContext): v memberAssert(ids.every(id => typeof id === 'string' && ctx.holderIds.includes(id)), '无权访问其他成员的数据') } +export async function assertAccountAccess(accountId: unknown, ctx: MemberContext): Promise { + memberAssert(typeof accountId === 'string', '参数必须是信用账户 ID') + const { data } = await queryOne<{ holder_id: string }>( + 'SELECT holder_id FROM credit_accounts WHERE id = ?', + [accountId] + ) + memberAssert(!!data && ctx.holderIds.includes(data.holder_id), '无权访问其他成员的信用账户') +} + export async function assertCardAccess(cardId: unknown, ctx: MemberContext): Promise { memberAssert(typeof cardId === 'string', '参数必须是卡片 ID') const { data } = await queryOne<{ holder_id: string }>('SELECT holder_id FROM credit_cards WHERE id = ?', [cardId]) diff --git a/lib/api/payables.server.ts b/lib/api/payables.server.ts index fef215c..fb4c0b6 100644 --- a/lib/api/payables.server.ts +++ b/lib/api/payables.server.ts @@ -1,4 +1,4 @@ -// lib/api/payables.server.ts — 周期性固定支出(房租 / 贷款 / 其他按月应付)。 +// lib/api/payables.server.ts — 周期性固定支出(房租 / 贷款 / 其他周期应付)。 // // 与信用卡账单分开建模:房租不是卡账,混进 credit_cards 会污染卡数、额度、 // 免息期等所有口径(见 migrations/d1/0009 的说明)。 @@ -6,22 +6,42 @@ import { query, queryOne, execute, uuid, now } from '../db' import { payablePeriodOf, payableDueDate, nextPayablePeriodOf, diffInCalendarDays } from '../utils' import { + CUSTOM_CATEGORY_SENTINEL, + MAX_CUSTOM_CATEGORY_LENGTH, PAYABLE_HISTORY_LIMIT, + dedupeCustomCategories, + isPayableCategory, + isPayableCycleType, + isValidEveryNMonths, + isValidPayablePeriod, + normalizeCustomCategoryName, normalizePayableCurrency, + resolvePresetPayableCategory, type PayableCategory, + type PayableCycleType, } from './payables.shared' import { RpcDomainError } from './errors' -export type { PayableCategory } from './payables.shared' +export type { PayableCategory, PayableCycleType } from './payables.shared' export interface RecurringPayable { id: string created_by: string name: string category: PayableCategory + /** 自定义分类展示名;预设分类时为 null(保留 category='other' 以兼容旧版与 iOS 枚举) */ + custom_category?: string | null amount: number currency: string + /** 支出周期:monthly(默认) / every_n_months / yearly */ + cycle_type?: PayableCycleType + /** 周期步长(月):monthly=1,every_n_months=2..60,yearly=12 */ + cycle_months?: number + /** 每年应付月份(1–12);仅 cycle_type='yearly' 时有值 */ + due_month?: number | null due_day: number + /** 起算/锚点账期 'YYYY-MM';monthly 为 null */ + anchor_period?: string | null holder_id: string | null note: string | null /** 归属银行名称(选填;null = 非银行,筛选时单列一个桶) */ @@ -35,9 +55,14 @@ export interface RecurringPayable { export interface RecurringPayableInput { name: string category: PayableCategory + custom_category?: string | null amount: number currency: string + cycle_type?: PayableCycleType + cycle_months?: number | null + due_month?: number | null due_day: number + anchor_period?: string | null holder_id?: string | null note?: string | null bank_name?: string | null @@ -90,6 +115,11 @@ function withStatus( else if (daysUntilDue < 0) status = 'overdue' return { ...row, + cycle_type: row.cycle_type ?? 'monthly', + cycle_months: row.cycle_months ?? 1, + due_month: row.due_month ?? null, + anchor_period: row.anchor_period ?? null, + custom_category: row.custom_category ?? null, amount, period, due_date: dueDateStr, @@ -113,14 +143,15 @@ export async function resolveDisplayPeriod( row: RecurringPayable, today: Date ): Promise<{ period: string; paidAmount: number }> { - const current = payablePeriodOf(today) + const current = payablePeriodOf(today, row) const amount = Number(row.amount) || 0 const paidCurrent = await paidAmountFor(row.id, current) const settled = amount > 0 && paidCurrent >= amount - 0.01 - const nextDue = payableDueDate(row.due_day, nextPayablePeriodOf(current)) + const nextPeriod = nextPayablePeriodOf(current, row) + const nextDue = payableDueDate(row.due_day, nextPeriod) if (settled && diffInCalendarDays(nextDue, today) < 30) { // 滚动到下期:该期此前不可能有付款记录,已付金额为 0 - return { period: nextPayablePeriodOf(current), paidAmount: 0 } + return { period: nextPeriod, paidAmount: 0 } } return { period: current, paidAmount: paidCurrent } } @@ -157,6 +188,7 @@ export async function getRecurringPayables( userId: string, today: Date = new Date() ): Promise { + const effectiveToday = today instanceof Date ? today : new Date() const { data, error } = await query( 'SELECT * FROM recurring_payables WHERE created_by = ? AND is_active = 1 ORDER BY due_day ASC', [userId] @@ -167,8 +199,8 @@ export async function getRecurringPayables( return Promise.all( rows.map(async row => { - const { period, paidAmount } = await resolveDisplayPeriod(row, today) - return withStatus(row, period, paidAmount, today) + const { period, paidAmount } = await resolveDisplayPeriod(row, effectiveToday) + return withStatus(row, period, paidAmount, effectiveToday) }) ) } @@ -187,37 +219,303 @@ function normalizePayableBankName(value: unknown): string | null { return trimmed } +interface NormalizedCategoryResult { + category: PayableCategory + custom_category: string | null + shouldPersistCustom: boolean +} + +function normalizePayableCategorySelection( + rawCategory: unknown, + rawCustomCategory: unknown +): NormalizedCategoryResult { + if (rawCustomCategory !== undefined && rawCustomCategory !== null) { + if (typeof rawCustomCategory !== 'string') { + throw new RpcDomainError('VALIDATION_FAILED', '自定义分类名称不合法') + } + const normalizedCustom = normalizeCustomCategoryName(rawCustomCategory) + if (normalizedCustom !== null) { + if (normalizedCustom.length > MAX_CUSTOM_CATEGORY_LENGTH) { + throw new RpcDomainError( + 'VALIDATION_FAILED', + `自定义分类名称不能超过 ${MAX_CUSTOM_CATEGORY_LENGTH} 个字符` + ) + } + const matchedPreset = resolvePresetPayableCategory(normalizedCustom) + if (matchedPreset) { + return { category: matchedPreset, custom_category: null, shouldPersistCustom: false } + } + return { category: 'other', custom_category: normalizedCustom, shouldPersistCustom: true } + } + if (rawCategory === CUSTOM_CATEGORY_SENTINEL) { + throw new RpcDomainError('VALIDATION_FAILED', '请填写自定义分类名称') + } + } else if (rawCategory === CUSTOM_CATEGORY_SENTINEL) { + throw new RpcDomainError('VALIDATION_FAILED', '请填写自定义分类名称') + } + + if (!isPayableCategory(rawCategory)) { + throw new RpcDomainError('VALIDATION_FAILED', '请选择合法的支出分类') + } + return { category: rawCategory, custom_category: null, shouldPersistCustom: false } +} + +interface NormalizedCycleResult { + cycle_type: PayableCycleType + cycle_months: number + due_month: number | null + due_day: number + anchor_period: string | null +} + +function normalizePayableCycleSelection( + raw: { + cycle_type?: unknown + cycle_months?: unknown + due_month?: unknown + due_day: unknown + anchor_period?: unknown + }, + today: Date +): NormalizedCycleResult { + if ( + typeof raw.due_day !== 'number' || + !Number.isInteger(raw.due_day) || + raw.due_day < 1 || + raw.due_day > 31 + ) { + throw new RpcDomainError('VALIDATION_FAILED', '应付日必须在 1–31 之间') + } + const dueDay = raw.due_day + + const rawType = raw.cycle_type ?? 'monthly' + if (!isPayableCycleType(rawType)) { + throw new RpcDomainError('VALIDATION_FAILED', '支出周期必须是每月、每 X 月或每年之一') + } + + if (rawType === 'monthly') { + return { + cycle_type: 'monthly', + cycle_months: 1, + due_month: null, + due_day: dueDay, + anchor_period: null, + } + } + + if (rawType === 'every_n_months') { + if (!isValidEveryNMonths(raw.cycle_months)) { + throw new RpcDomainError('VALIDATION_FAILED', '间隔月数必须是 2–60 之间的整数') + } + let anchorPeriod: string + if ( + raw.anchor_period === undefined || + raw.anchor_period === null || + (typeof raw.anchor_period === 'string' && raw.anchor_period.trim() === '') + ) { + anchorPeriod = payablePeriodOf(today) + } else if (!isValidPayablePeriod(raw.anchor_period)) { + throw new RpcDomainError('VALIDATION_FAILED', '起算月份格式必须为 YYYY-MM') + } else { + anchorPeriod = raw.anchor_period.trim() + } + return { + cycle_type: 'every_n_months', + cycle_months: raw.cycle_months, + due_month: null, + due_day: dueDay, + anchor_period: anchorPeriod, + } + } + + // yearly:每年按同月同日推导 + if ( + typeof raw.due_month !== 'number' || + !Number.isInteger(raw.due_month) || + raw.due_month < 1 || + raw.due_month > 12 + ) { + throw new RpcDomainError('VALIDATION_FAILED', '每年应付月份必须是 1–12 之间的整数') + } + const dueMonth = raw.due_month + let anchorPeriod: string + if ( + raw.anchor_period !== undefined && + raw.anchor_period !== null && + !(typeof raw.anchor_period === 'string' && raw.anchor_period.trim() === '') + ) { + if (!isValidPayablePeriod(raw.anchor_period)) { + throw new RpcDomainError('VALIDATION_FAILED', '起算月份格式必须为 YYYY-MM') + } + const trimmedAnchor = raw.anchor_period.trim() + if (Number(trimmedAnchor.slice(5, 7)) !== dueMonth) { + throw new RpcDomainError('VALIDATION_FAILED', '起算月份必须与每年应付月份一致') + } + anchorPeriod = trimmedAnchor + } else { + const candidatePeriod = `${today.getFullYear()}-${String(dueMonth).padStart(2, '0')}` + const candidateDue = payableDueDate(dueDay, candidatePeriod) + const anchorYear = + diffInCalendarDays(candidateDue, today) >= 0 + ? today.getFullYear() + : today.getFullYear() + 1 + anchorPeriod = `${anchorYear}-${String(dueMonth).padStart(2, '0')}` + } + + return { + cycle_type: 'yearly', + cycle_months: 12, + due_month: dueMonth, + due_day: dueDay, + anchor_period: anchorPeriod, + } +} + +/** + * 将自定义分类幂等去重持久化到用户词典表,并返回标准展示名称 + * (若已有大小写不同但同名的词条,沿用首次保存的展示名)。 + */ +async function persistCustomCategoryForUser(userId: string, name: string): Promise { + const normalized = normalizeCustomCategoryName(name) + if (!normalized) return name + const normKey = normalized.toLowerCase() + const existing = await queryOne<{ name: string }>( + 'SELECT name FROM payable_custom_categories WHERE user_id = ? AND normalized_name = ?', + [userId, normKey] + ) + if (existing.data?.name) { + return existing.data.name + } + const { error } = await execute( + `INSERT INTO payable_custom_categories (id, user_id, name, normalized_name, created_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(user_id, normalized_name) DO NOTHING`, + [uuid(), userId, normalized, normKey, now()] + ) + if (error) throw new Error(error.message) + const after = await queryOne<{ name: string }>( + 'SELECT name FROM payable_custom_categories WHERE user_id = ? AND normalized_name = ?', + [userId, normKey] + ) + return after.data?.name ?? normalized +} + +/** 读取当前用户已持久化的自定义分类列表(去重、排除预设同名项)。 */ +export async function getPayableCustomCategories(userId?: string): Promise { + if (typeof userId !== 'string' || !userId.trim()) { + throw new RpcDomainError('VALIDATION_FAILED', '缺少合法的用户身份') + } + const [dictRes, usedRes] = await Promise.all([ + query<{ name: string }>( + 'SELECT name FROM payable_custom_categories WHERE user_id = ? ORDER BY created_at ASC, rowid ASC', + [userId] + ), + query<{ name: string }>( + `SELECT custom_category AS name + FROM recurring_payables + WHERE created_by = ? AND custom_category IS NOT NULL + ORDER BY created_at ASC, rowid ASC`, + [userId] + ), + ]) + if (dictRes.error) throw new Error(dictRes.error.message) + if (usedRes.error) throw new Error(usedRes.error.message) + return dedupeCustomCategories([ + ...(dictRes.data ?? []).map(r => r.name), + ...(usedRes.data ?? []).map(r => r.name), + ]) +} + +/** 单独保存一个自定义分类(幂等去重)并返回最新可选列表。 */ +export async function savePayableCustomCategory( + userId: string, + rawName: string +): Promise { + if (typeof userId !== 'string' || !userId.trim()) { + throw new RpcDomainError('VALIDATION_FAILED', '缺少合法的用户身份') + } + const resolved = normalizePayableCategorySelection(CUSTOM_CATEGORY_SENTINEL, rawName) + if (resolved.shouldPersistCustom && resolved.custom_category) { + await persistCustomCategoryForUser(userId, resolved.custom_category) + } + return getPayableCustomCategories(userId) +} + export async function createRecurringPayable( - input: CreateRecurringPayableInput + input: CreateRecurringPayableInput, + today: Date = new Date() ): Promise { + const effectiveToday = today instanceof Date ? today : new Date() if (!input.name?.trim()) throw new RpcDomainError('VALIDATION_FAILED', '请填写名称') if (!Number.isFinite(input.amount) || input.amount < 0) { throw new RpcDomainError('VALIDATION_FAILED', '金额必须是不小于 0 的数字') } - if (!Number.isInteger(input.due_day) || input.due_day < 1 || input.due_day > 31) { - throw new RpcDomainError('VALIDATION_FAILED', '每月应付日必须在 1–31 之间') - } + const cycle = normalizePayableCycleSelection( + { + cycle_type: input.cycle_type, + cycle_months: input.cycle_months, + due_month: input.due_month, + due_day: input.due_day, + anchor_period: input.anchor_period, + }, + effectiveToday + ) const currency = normalizePayableCurrency(input.currency) if (!currency) throw new RpcDomainError('VALIDATION_FAILED', '币种必须是 CNY / USD / HKD 之一') const bankName = normalizePayableBankName(input.bank_name) + const categorySelection = normalizePayableCategorySelection(input.category, input.custom_category) + + let customCategory = categorySelection.custom_category + if (categorySelection.shouldPersistCustom && customCategory && input.created_by) { + customCategory = await persistCustomCategoryForUser(input.created_by, customCategory) + } + const id = uuid() const { error } = await execute( - `INSERT INTO recurring_payables (id, created_by, name, category, amount, currency, due_day, holder_id, note, bank_name, bank_account, is_active, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`, - [id, input.created_by, input.name.trim(), input.category, input.amount, - currency, input.due_day, input.holder_id || null, input.note || null, - bankName, input.bank_account?.trim() || null, now()] + `INSERT INTO recurring_payables ( + id, created_by, name, category, custom_category, amount, currency, + cycle_type, cycle_months, due_month, due_day, anchor_period, + holder_id, note, bank_name, bank_account, is_active, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`, + [ + id, + input.created_by, + input.name.trim(), + categorySelection.category, + customCategory, + input.amount, + currency, + cycle.cycle_type, + cycle.cycle_months, + cycle.due_month, + cycle.due_day, + cycle.anchor_period, + input.holder_id || null, + input.note || null, + bankName, + input.bank_account?.trim() || null, + now(), + ] ) if (error) throw new Error(error.message) const created = await queryOne('SELECT * FROM recurring_payables WHERE id = ?', [id]) if (!created.data) throw new Error('创建失败') - return withStatus(created.data, payablePeriodOf(), 0, new Date()) + const { period, paidAmount } = await resolveDisplayPeriod(created.data, effectiveToday) + return withStatus(created.data, period, paidAmount, effectiveToday) } export async function updateRecurringPayable( id: string, - patch: Partial & { is_active?: number } + patch: Partial & { is_active?: number }, + today: Date = new Date() ): Promise { + const effectiveToday = today instanceof Date ? today : new Date() + if (patch.name !== undefined && !patch.name?.trim()) { + throw new RpcDomainError('VALIDATION_FAILED', '请填写名称') + } + if (patch.amount !== undefined && (!Number.isFinite(patch.amount) || patch.amount < 0)) { + throw new RpcDomainError('VALIDATION_FAILED', '金额必须是不小于 0 的数字') + } if (patch.currency !== undefined) { const currency = normalizePayableCurrency(patch.currency) if (!currency) throw new RpcDomainError('VALIDATION_FAILED', '币种必须是 CNY / USD / HKD 之一') @@ -226,22 +524,92 @@ export async function updateRecurringPayable( if (patch.bank_name !== undefined) { patch = { ...patch, bank_name: normalizePayableBankName(patch.bank_name) } } - const fields: string[] = [] - const params: unknown[] = [] - for (const key of ['name', 'category', 'amount', 'currency', 'due_day', 'holder_id', 'note', 'bank_name', 'bank_account', 'is_active'] as const) { - const value = (patch as Record)[key] - if (value !== undefined) { - fields.push(`${key} = ?`) - params.push(value) + + const existing = await queryOne('SELECT * FROM recurring_payables WHERE id = ?', [id]) + if (!existing.data) throw new RpcDomainError('NOT_FOUND', '应付事项不存在') + + const updates: Record = {} + if (patch.name !== undefined) updates.name = patch.name.trim() + if (patch.amount !== undefined) updates.amount = patch.amount + if (patch.currency !== undefined) updates.currency = patch.currency + if (patch.holder_id !== undefined) updates.holder_id = patch.holder_id || null + if (patch.note !== undefined) updates.note = patch.note + if (patch.bank_name !== undefined) updates.bank_name = patch.bank_name + if (patch.bank_account !== undefined) updates.bank_account = patch.bank_account?.trim() || null + if (patch.is_active !== undefined) updates.is_active = patch.is_active + + // 触及分类或自定义分类时联合归一,避免切换回预设分类后残留旧 custom_category + if (patch.category !== undefined || patch.custom_category !== undefined) { + const rawCat = patch.category ?? existing.data.category + const rawCustom = + patch.custom_category !== undefined + ? patch.custom_category + : patch.category !== undefined + ? null + : existing.data.custom_category + const categorySelection = normalizePayableCategorySelection(rawCat, rawCustom) + let customCategory = categorySelection.custom_category + if (categorySelection.shouldPersistCustom && customCategory) { + customCategory = await persistCustomCategoryForUser(existing.data.created_by, customCategory) + } + updates.category = categorySelection.category + updates.custom_category = customCategory + } + + // 触及周期或应付日时联合校验与归一,保证切换周期后无脏字段残留 + const touchesCycle = + patch.cycle_type !== undefined || + patch.cycle_months !== undefined || + patch.due_month !== undefined || + patch.due_day !== undefined || + patch.anchor_period !== undefined + + if (touchesCycle) { + const nextCycleType = patch.cycle_type ?? existing.data.cycle_type ?? 'monthly' + const nextDueMonth = + patch.due_month !== undefined ? patch.due_month : existing.data.due_month + // 若显式传入 anchor_period 则用传入值;否则在同周期且(年付同月或每 X 月)时保留原锚点 + let candidateAnchor: unknown = patch.anchor_period + if (candidateAnchor === undefined) { + if (nextCycleType === 'every_n_months' && existing.data.cycle_type === 'every_n_months') { + candidateAnchor = existing.data.anchor_period + } else if ( + nextCycleType === 'yearly' && + existing.data.cycle_type === 'yearly' && + existing.data.due_month === nextDueMonth + ) { + candidateAnchor = existing.data.anchor_period + } } + const normalizedCycle = normalizePayableCycleSelection( + { + cycle_type: nextCycleType, + cycle_months: + patch.cycle_months !== undefined ? patch.cycle_months : existing.data.cycle_months, + due_month: nextDueMonth, + due_day: patch.due_day !== undefined ? patch.due_day : existing.data.due_day, + anchor_period: candidateAnchor, + }, + effectiveToday + ) + updates.cycle_type = normalizedCycle.cycle_type + updates.cycle_months = normalizedCycle.cycle_months + updates.due_month = normalizedCycle.due_month + updates.due_day = normalizedCycle.due_day + updates.anchor_period = normalizedCycle.anchor_period } + + const fields = Object.keys(updates).map(key => `${key} = ?`) + const params = Object.values(updates) if (fields.length === 0) throw new Error('没有需要更新的字段') params.push(id) + const { error } = await execute(`UPDATE recurring_payables SET ${fields.join(', ')} WHERE id = ?`, params) if (error) throw new Error(error.message) const updated = await queryOne('SELECT * FROM recurring_payables WHERE id = ?', [id]) if (!updated.data) throw new Error('应付事项不存在') - return withStatus(updated.data, payablePeriodOf(), await paidAmountFor(id, payablePeriodOf()), new Date()) + const { period, paidAmount } = await resolveDisplayPeriod(updated.data, effectiveToday) + return withStatus(updated.data, period, paidAmount, effectiveToday) } export async function deleteRecurringPayable(id: string): Promise { @@ -260,8 +628,9 @@ export async function payRecurringPayable( payableId: string, amount: number, note?: string, - today: Date = new Date() + rawToday: Date = new Date() ): Promise { + const today = rawToday instanceof Date ? rawToday : new Date() if (!Number.isFinite(amount) || amount <= 0) throw new Error('还款金额必须大于 0') const payable = await queryOne('SELECT * FROM recurring_payables WHERE id = ?', [payableId]) diff --git a/lib/api/payables.shared.ts b/lib/api/payables.shared.ts index 40de021..b364fd2 100644 --- a/lib/api/payables.shared.ts +++ b/lib/api/payables.shared.ts @@ -14,14 +14,148 @@ const CATEGORY_LABELS: Record = { other: '其他', } -export function categoryLabel(category: PayableCategory): string { - return CATEGORY_LABELS[category] ?? CATEGORY_LABELS.other -} - export const PAYABLE_CATEGORIES: { value: PayableCategory; label: string }[] = ( Object.keys(CATEGORY_LABELS) as PayableCategory[] ).map(value => ({ value, label: CATEGORY_LABELS[value] })) +export function isPayableCategory(value: unknown): value is PayableCategory { + return typeof value === 'string' && Object.hasOwn(CATEGORY_LABELS, value) +} + +/** Select 下拉中代表「输入新自定义分类」的哨兵值。 */ +export const CUSTOM_CATEGORY_SENTINEL = '__custom__' + +/** 自定义分类名称最大长度。 */ +export const MAX_CUSTOM_CATEGORY_LENGTH = 30 + +/** + * 若输入与已有预设分类(英文枚举值或中文展示名)同义,返回对应预设枚举, + * 避免把「房租」再存一份重复的自定义分类。 + */ +export function resolvePresetPayableCategory(raw: unknown): PayableCategory | null { + if (typeof raw !== 'string') return null + const trimmed = raw.trim() + if (!trimmed) return null + const lower = trimmed.toLowerCase() + if (isPayableCategory(lower)) return lower + for (const item of PAYABLE_CATEGORIES) { + if (item.label === trimmed) return item.value + } + return null +} + +/** 归一化自定义分类名称:去首尾空白并折叠内部连续空白;空串返回 null。 */ +export function normalizeCustomCategoryName(raw: unknown): string | null { + if (typeof raw !== 'string') return null + const collapsed = raw.trim().replace(/\s+/g, ' ') + return collapsed.length > 0 ? collapsed : null +} + +/** + * 自定义分类列表去重: + * 1. 去首尾与多余空白、剔除空值; + * 2. 排除与预设分类重名的项(防止出现两个「房租」); + * 3. 按大小写不敏感(toLowerCase)去重,保留首次出现的展示写法。 + */ +export function dedupeCustomCategories( + names: Iterable +): string[] { + const result: string[] = [] + const seen = new Set() + for (const raw of names) { + const normalized = normalizeCustomCategoryName(raw) + if (!normalized) continue + if (resolvePresetPayableCategory(normalized) !== null) continue + const key = normalized.toLowerCase() + if (seen.has(key)) continue + seen.add(key) + result.push(normalized) + } + return result +} + +export function categoryLabel( + category: PayableCategory, + customCategory?: string | null +): string { + const normalizedCustom = normalizeCustomCategoryName(customCategory) + if (normalizedCustom) { + const preset = resolvePresetPayableCategory(normalizedCustom) + return preset ? CATEGORY_LABELS[preset] : normalizedCustom + } + return CATEGORY_LABELS[category] ?? CATEGORY_LABELS.other +} + +// ── 固定支出周期(每月 / 每 X 月 / 每年)──────────────────────────────────── + +export const PAYABLE_CYCLE_TYPES = ['monthly', 'every_n_months', 'yearly'] as const + +export type PayableCycleType = (typeof PAYABLE_CYCLE_TYPES)[number] + +export const MIN_PAYABLE_CYCLE_MONTHS = 2 +export const MAX_PAYABLE_CYCLE_MONTHS = 60 + +export const PAYABLE_CYCLE_LABELS: Record = { + monthly: '每月', + every_n_months: '每 X 月', + yearly: '每年', +} + +export const PAYABLE_CYCLE_OPTIONS: { value: PayableCycleType; label: string }[] = + PAYABLE_CYCLE_TYPES.map(value => ({ value, label: PAYABLE_CYCLE_LABELS[value] })) + +export function isPayableCycleType(value: unknown): value is PayableCycleType { + return ( + typeof value === 'string' && + (PAYABLE_CYCLE_TYPES as readonly string[]).includes(value) + ) +} + +/** 校验每 X 月的间隔月数是否为合理整数(2–60)。 */ +export function isValidEveryNMonths(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isInteger(value) && + value >= MIN_PAYABLE_CYCLE_MONTHS && + value <= MAX_PAYABLE_CYCLE_MONTHS + ) +} + +/** 校验账期字符串格式 'YYYY-MM'(1970–2100 年,01–12 月)。 */ +export function isValidPayablePeriod(value: unknown): value is string { + if (typeof value !== 'string') return false + const m = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(value.trim()) + if (!m) return false + const year = Number(m[1]) + return year >= 1970 && year <= 2100 +} + +export interface PayableCycleSpec { + cycle_type?: PayableCycleType | null + cycle_months?: number | null + due_month?: number | null + due_day: number + anchor_period?: string | null +} + +/** 卡片副标题上的周期与应付日摘要文案。 */ +export function payableCycleLabel(spec: PayableCycleSpec): string { + const cycleType = spec.cycle_type ?? 'monthly' + if (cycleType === 'every_n_months') { + const months = spec.cycle_months ?? MIN_PAYABLE_CYCLE_MONTHS + return `每 ${months} 个月 · ${spec.due_day} 日` + } + if (cycleType === 'yearly') { + const fallbackMonth = + spec.anchor_period && isValidPayablePeriod(spec.anchor_period) + ? Number(spec.anchor_period.slice(5, 7)) + : 1 + const month = spec.due_month ?? fallbackMonth + return `每年 ${month} 月 ${spec.due_day} 日` + } + return `每月 ${spec.due_day} 日` +} + /** * 固定支出的封闭币种集(2026-11-02 规则):与生产库实际持有的卡币种一致 * (CNY / USD / HKD),界面用下拉枚举、服务端白名单校验,不再接受自由文本。 @@ -65,5 +199,8 @@ export function isPayableCurrency(value: unknown): value is PayableCurrency { return typeof value === 'string' && (PAYABLE_CURRENCIES as readonly string[]).includes(value) } -/** 历史还款返回上限:服务端查询与前端「最近 N 笔」文案共用同一常量。 */ +/** 历史还款返回上限:服务端列表与前端「最近 N 笔」文案共用同一常量。 */ export const PAYABLE_HISTORY_LIMIT = 60 + +/** 固定支出下期出账提醒提前天数(默认在还款日前 30 天出账/提醒)。 */ +export const NEXT_BILL_LEAD_DAYS = 30 diff --git a/lib/api/payables.ts b/lib/api/payables.ts index d5862d5..eb93d34 100644 --- a/lib/api/payables.ts +++ b/lib/api/payables.ts @@ -11,10 +11,30 @@ export type { } from './payables.server' // 纯类型与纯函数走 .shared,避免把服务端依赖带进浏览器包。 -export type { PayableCategory, PayableCurrency } from './payables.shared' +export type { + PayableCategory, + PayableCurrency, + PayableCycleType, + PayableCycleSpec, +} from './payables.shared' export { categoryLabel, + CUSTOM_CATEGORY_SENTINEL, + MAX_CUSTOM_CATEGORY_LENGTH, PAYABLE_CATEGORIES, + isPayableCategory, + resolvePresetPayableCategory, + normalizeCustomCategoryName, + dedupeCustomCategories, + PAYABLE_CYCLE_TYPES, + PAYABLE_CYCLE_LABELS, + PAYABLE_CYCLE_OPTIONS, + MIN_PAYABLE_CYCLE_MONTHS, + MAX_PAYABLE_CYCLE_MONTHS, + isPayableCycleType, + isValidEveryNMonths, + isValidPayablePeriod, + payableCycleLabel, PAYABLE_CURRENCIES, PAYABLE_CURRENCY_LABELS, isPayableCurrency, @@ -40,3 +60,9 @@ export function payRecurringPayable(...args: Parameters) { return callRpc('payables', 'getPayablePayments', ...args) } +export function getPayableCustomCategories(...args: Parameters) { + return callRpc('payables', 'getPayableCustomCategories', ...args) +} +export function savePayableCustomCategory(...args: Parameters) { + return callRpc('payables', 'savePayableCustomCategory', ...args) +} diff --git a/lib/api/push.ts b/lib/api/push.ts index 075eff0..1cace82 100644 --- a/lib/api/push.ts +++ b/lib/api/push.ts @@ -6,3 +6,70 @@ export function subscribePush(input: Server.PushSubscribeInput) { // userId 位置由服务端 registry 以会话身份覆盖(bindUser: 1) return callRpc('push', 'subscribePush', input, '') } + +export interface TestPushResult { + ok: boolean + error?: string + data?: { + subscriptions: number + sent: number + removed: number + errors: string[] + } +} + +/** + * 校验用户的提醒配置是否允许下发 Web Push。 + * 存量口径:若 enabled_channels 未显式设置,而旧 opportunities.web_push_enabled === false,则不开启。 + */ +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 +} + +/** 触发向当前用户订阅发送测试通知(收敛到统一 API 模块) */ +export async function sendTestPush(): Promise { + try { + const res = await fetch('/api/push/test', { + method: 'POST', + credentials: 'same-origin', + }) + const json = (await res.json().catch(() => null)) as { + data?: { + subscriptions: number + sent: number + removed: number + errors: string[] + } + error?: string + } | null + + if (!res.ok) { + return { + ok: false, + error: json?.error || `推送接口请求失败 (${res.status})`, + } + } + + return { + ok: true, + data: json?.data, + } + } catch (err) { + return { + ok: false, + error: err instanceof Error ? err.message : '网络请求失败', + } + } +} diff --git a/lib/api/registry.ts b/lib/api/registry.ts index 8bc2a13..fbb8d2d 100644 --- a/lib/api/registry.ts +++ b/lib/api/registry.ts @@ -10,6 +10,7 @@ // - memberFilter: response filter applied to member results import * as adminServer from './admin.server' +import * as accountsServer from './accounts.server' import * as aiServer from './ai.server' import * as analyticsServer from './analytics.server' import * as attachmentsServer from './attachments.server' @@ -37,6 +38,7 @@ import * as remindersServer from './reminders.server' import * as syncGmailServer from './sync-gmail.server' import { applyAnalyticsScope, + assertAccountAccess, assertBenefitAccess, assertBillAccess, assertBillListAccess, @@ -131,6 +133,33 @@ export const RPC_REGISTRY: Record> = { enrichBankFromWeb: { impl: aiServer.enrichBankFromWeb, admin: true }, suggestPromosFromWeb: { impl: aiServer.suggestPromosFromWeb, admin: true }, }, + accounts: { + getCreditAccounts: { impl: accountsServer.getCreditAccounts, bindUser: 0 }, + getCreditAccountDetail: { + impl: accountsServer.getCreditAccountDetail, + memberGuard: async (args, ctx) => assertAccountAccess(args[0], ctx), + }, + mergeCardsIntoAccount: { + impl: accountsServer.mergeCardsIntoAccount, + memberGuard: async (args, ctx) => { + await assertAccountAccess(args[0], ctx); + const cardIds = args[1] as string[]; + if (Array.isArray(cardIds)) { + for (const cid of cardIds) { + await assertCardAccess(cid, ctx); + } + } + }, + }, + splitCardFromAccount: { + impl: accountsServer.splitCardFromAccount, + memberGuard: async (args, ctx) => assertCardAccess(args[0], ctx), + }, + updateCreditAccount: { + impl: accountsServer.updateCreditAccount, + memberGuard: async (args, ctx) => assertAccountAccess(args[0], ctx), + }, + }, analytics: { getAnalyticsSummary: { impl: analyticsServer.getAnalyticsSummary, memberGuard: (args, ctx) => applyAnalyticsScope(args[0], ctx) }, getMonthlyDebtTrend: { impl: analyticsServer.getMonthlyDebtTrend, memberGuard: (args, ctx) => applyAnalyticsScope(args[0], ctx) }, @@ -220,6 +249,7 @@ export const RPC_REGISTRY: Record> = { createCard: { impl: cardsServer.createCard, memberGuard: guardObjField(0, "holder_id", async (holderId, ctx) => assertHolderAccess(holderId, ctx)) }, updateCard: { impl: cardsServer.updateCard, memberGuard: guardCard(0) }, updateCardHolder: { impl: cardsServer.updateCardHolder, bindUser: 0 }, + getDueDateReasonReport: { impl: cardsServer.getDueDateReasonReport, bindUser: 0 }, }, dashboard: { getOpportunityTodayCount: { impl: getTodayAvailableCount, prependActor: true }, @@ -241,13 +271,14 @@ export const RPC_REGISTRY: Record> = { }, banks: { getBankNames: { impl: banksServer.getBankNames }, + getBanks: { impl: banksServer.getBanks }, }, holders: { getHolders: { impl: holdersServer.getHolders, bindUser: 0 }, getHolder: { impl: holdersServer.getHolder, memberGuard: guardHolder(0) }, getHolderStatsPageData: { impl: holdersServer.getHolderStatsPageData, memberGuard: guardHolder(0) }, getHolderCardCounts: { impl: holdersServer.getHolderCardCounts, memberGuard: async (args, ctx) => assertHolderIdsAccess(args[0], ctx) }, - createHolder: { impl: holdersServer.createHolder, bindField: { arg: 0, field: "created_by" }, admin: true }, + createHolder: { impl: holdersServer.createHolder, bindField: { arg: 0, field: "created_by" } }, updateHolder: { impl: holdersServer.updateHolder, admin: true }, mergeHolders: { impl: holdersServer.mergeHolders, admin: true }, }, @@ -262,6 +293,8 @@ export const RPC_REGISTRY: Record> = { payables: { // 周期应付(房租/贷款):一律绑定会话用户,成员只能碰自己创建的记录。 getRecurringPayables: { impl: payablesServer.getRecurringPayables, bindUser: 0 }, + getPayableCustomCategories: { impl: payablesServer.getPayableCustomCategories, bindUser: 0 }, + savePayableCustomCategory: { impl: payablesServer.savePayableCustomCategory, bindUser: 0 }, createRecurringPayable: { impl: payablesServer.createRecurringPayable, bindField: { arg: 0, field: 'created_by' }, diff --git a/lib/api/sync-gmail.server.ts b/lib/api/sync-gmail.server.ts index aa73537..221fd63 100644 --- a/lib/api/sync-gmail.server.ts +++ b/lib/api/sync-gmail.server.ts @@ -1,5 +1,6 @@ import { query, queryOne, execute, uuid, now } from '../db' import type { Bill, CardHolder, CardProduct, CreditCard } from '../types' +import { isExactDueDate } from '../email-core/due-date' type GmailLedgerSyncEntry = { id: string @@ -167,7 +168,7 @@ export async function syncGmailLedgerToCardsAndBills(targetUserId?: string): Pro const bankShort = normalizeBank(entry.bank) const amount = Number(entry.statement_amount || 0) const billMonth = getEntryMonth(entry) - if (!tail || !entry.due_date || !billMonth || amount <= 0) continue + if (!tail || !isExactDueDate(entry.due_date) || !billMonth || amount <= 0) continue const cardKey = `${bankShort}:${tail}` let card = cardByBankAndTail.get(cardKey) || cardByBankAndTail.get(`:${tail}`) || null @@ -188,7 +189,7 @@ export async function syncGmailLedgerToCardsAndBills(targetUserId?: string): Pro const newCardId = uuid() const { error: createCardErr } = await execute( `INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) - VALUES (?, ?, ?, ?, 50000, ?, ?, ?)`, + VALUES (?, ?, ?, ?, 0, ?, ?, ?)`, [newCardId, holderId, product.id, tail, pickStatementDay(entry.statement_date), 'active', entry.kind?.includes('贷款') ? 'loan' : 'credit'] ) @@ -196,7 +197,7 @@ export async function syncGmailLedgerToCardsAndBills(targetUserId?: string): Pro card = { id: newCardId, holder_id: holderId, card_product_id: product.id, - card_number_last4: tail, credit_limit: 50000, billing_day: pickStatementDay(entry.statement_date), + card_number_last4: tail, credit_limit: 0, billing_day: pickStatementDay(entry.statement_date), status: 'active', card_type: entry.kind?.includes('贷款') ? 'loan' : 'credit', created_at: now(), card_product: { bank_name: product.bank_name, card_name: product.card_name }, diff --git a/lib/bills-view-model.ts b/lib/bills-view-model.ts index 51ac139..5f51163 100644 --- a/lib/bills-view-model.ts +++ b/lib/bills-view-model.ts @@ -8,18 +8,26 @@ export type AccountMode = 'multi' | 'single' /** * 多卡一账户 / 单卡单账户 的展示口径: - * 同一持卡人在同一家银行持有 >1 张卡 → multi;否则 single。 + * 判定优先级: + * 1. 实体信用账户 statement_mode 优先:所属账户存在 statement_mode 时,merged 判定为 multi,否则 single + * 2. 用户手动钉住的 account_mode_override 次之 + * 3. 同持卡人同银行卡数统计兜底:持有 >1 张卡 → multi;否则 single + * * 这是展示层推导,不改 schema;同一银行跨持卡人仍算各自独立的账户。 */ export function deriveAccountMode( holderId: string, bankName: string, - cards: Pick[] + cards: Pick[] ): AccountMode { - // 用户手动钉住的账户模式优先(email 导入歧义 / 独立记账的同银行卡) + // 实体信用账户模式优先(若所属账户为 merged 则直接判定为 multi) const self = cards.find( c => c.holder_id === holderId && (c.card.card_product?.bank_name || '') === bankName ) + if (self?.account?.statement_mode) { + return self.account.statement_mode === 'merged' ? 'multi' : 'single' + } + // 用户手动钉住的账户模式优先(email 导入歧义 / 独立记账的同银行卡) if (self?.card.account_mode_override) return self.card.account_mode_override const sameBankSameHolder = cards.filter( c => c.holder_id === holderId && (c.card.card_product?.bank_name || '') === bankName diff --git a/lib/db/types.ts b/lib/db/types.ts index d02904a..2388a52 100644 --- a/lib/db/types.ts +++ b/lib/db/types.ts @@ -79,12 +79,45 @@ export interface CardHolderRow { created_at: string } +export interface CreditAccountRow { + id: string + holder_id: string + bank_id: string | null + bank_name: string + currency: string + account_tail: string | null + statement_mode: 'merged' | 'independent' + quota_mode: 'shared' | 'independent' + shared_credit_limit: number | null + billing_day: number | null + due_type: 'fixed' | 'after_billing' | 'fixed_before_billing' | null + due_value: number | null + primary_card_id: string | null + label: string | null + status: 'active' | 'archived' + created_at: string + updated_at: string +} + +export interface BillCardSubtotalRow { + id: string + bill_id: string + card_id: string | null + card_tail: string + subtotal_amount: number + currency: string | null + source: 'email' | 'manual' + created_at: string +} + export interface CreditCardRow { id: string holder_id: string + account_id: string | null card_product_id: string card_number_last4: string | null credit_limit: number + credit_limit_override: number | null billing_day: number status: 'active' | 'frozen' | 'cancelled' card_type: 'credit' | 'loan' @@ -103,6 +136,7 @@ export interface CreditCardRow { export interface BillRow { id: string + account_id: string | null card_id: string bill_month: string statement_start: string | null diff --git a/lib/due-date-summary.ts b/lib/due-date-summary.ts new file mode 100644 index 0000000..0435f62 --- /dev/null +++ b/lib/due-date-summary.ts @@ -0,0 +1,804 @@ +/** + * 卡片与邮件维度的还款日确切性判定及缺失原因汇总。 + * + * 严格区分四类缺失原因,绝不编造日期: + * - missing_in_email:邮件未提供确切还款日 + * - parse_failed:邮件解析失败(AI 异常 / JSON 损坏 / 入库失败) + * - ambiguous_or_grace_only:日期模糊或仅有宽限期(如仅「账单日后 20 天」相对规则、非 YYYY-MM-DD) + * - unsynced:未同步(尚无该卡的邮件同步/解析记录) + */ + +import { query, queryOne } from './db' +import type { + Bill, + CardDueDateEmailEvidence, + CardDueDateResolution, + CardProduct, + CreditCard, + DueDateMissingReasonCode, + EmailParseLog, +} from './types' +import { + DUE_DATE_ISSUE_LABELS, + isExactDueDate, +} from './email-core/due-date' + +export { DUE_DATE_ISSUE_LABELS } + +export interface GmailSyncMessageLite { + gmail_message_id: string + user_id: string + from_email?: string | null + subject?: string | null + status: 'bill_written' | 'draft_parked' | 'skipped' | 'failed' + bill_id?: string | null + draft_id?: string | null + error_msg?: string | null + created_at: string +} + +export interface BillImportDraftLite { + id: string + created_by: string + card_id?: string | null + source_type?: string | null + parsed_payload: string | Record + status?: string | null + created_at: string +} + +export interface CardForDueDateSummary { + id: string + holder_id: string + card_number_last4?: string | null + billing_day: number + card_type: 'credit' | 'loan' + loan_due_day?: number | null + override_due_type?: 'fixed' | 'after_billing' | 'fixed_before_billing' | null + override_due_value?: number | null + bank_name?: string | null + card_name?: string | null + card_product?: Pick< + CardProduct, + 'bank_name' | 'card_name' | 'payment_due_type' | 'payment_due_value' + > | null +} + +export interface BillForDueDateSummary { + id: string + card_id: string + bill_month: string + bill_amount: number + statement_date?: string | null + due_date: string + due_date_override?: string | null + created_at?: string +} + +export interface EmailIssueSummaryItem { + source: 'email_parse_log' | 'gmail_sync' | 'bill_draft' + id: string + created_at: string + from_email: string | null + subject: string | null + bank_name: string | null + card_last4: string | null + reason_code: DueDateMissingReasonCode + reason_label: string + detail: string +} + +export interface DueDateReasonReport { + cards_total: number + cards_with_exact_due_date: number + cards_missing_exact_due_date: number + by_reason: Record + cards: Array<{ + card_id: string + bank_name: string + card_name: string + card_last4: string + resolution: CardDueDateResolution + }> + unmatched_email_issues: EmailIssueSummaryItem[] +} + +function emptyReasonCounts(): Record { + return { + missing_in_email: 0, + parse_failed: 0, + ambiguous_or_grace_only: 0, + unsynced: 0, + } +} + +function normalizeTail(value: string | null | undefined): string { + return String(value ?? '').replace(/\D/g, '') +} + +function normalizeBank(value: string | null | undefined): string { + return String(value ?? '') + .trim() + .toLowerCase() + .replace(/[\s\u3000]+/g, '') +} + +function bankMatches(a: string | null | undefined, b: string | null | undefined): boolean { + const na = normalizeBank(a) + const nb = normalizeBank(b) + if (!na || !nb) return false + return na === nb || na.includes(nb) || nb.includes(na) +} + +function parseJsonSafe(raw: unknown): Record | null { + if (!raw) return null + if (typeof raw === 'object' && !Array.isArray(raw)) return raw as Record + if (typeof raw !== 'string') return null + const trimmed = raw.trim() + if (!trimmed) return null + try { + const parsed = JSON.parse(trimmed) + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record) + : null + } catch { + return null + } +} + +/** + * 分类单封邮件解析日志(若属于非账单营销邮件或已成功给出确切还款日且已关联账单,则返回 null 表示无缺失问题)。 + */ +export function classifyEmailLogDueDateIssue(log: EmailParseLog): EmailIssueSummaryItem[] { + const createdAt = log.created_at || '' + const fromEmail = log.from_email ?? null + const subject = log.subject ?? null + const errMsg = (log.error_msg ?? '').trim() + const parsed = parseJsonSafe(log.raw_ai_response) + + // 1. 转发包日志:拆解内部 skipped 条目 + if (parsed && parsed.source === 'forwarded_bundle') { + const skipped = Array.isArray(parsed.skipped) + ? (parsed.skipped as Array<{ label?: string; reason?: string }>) + : [] + const items: EmailIssueSummaryItem[] = [] + for (let i = 0; i < skipped.length; i++) { + const entry = skipped[i] + const r = String(entry?.reason ?? '').trim() + if (!r) continue + if (r.includes('AI 解析失败')) { + items.push({ + source: 'email_parse_log', + id: `${log.id}#${i + 1}`, + created_at: createdAt, + from_email: fromEmail, + subject: entry?.label ? `${subject ?? '转发包'} (${entry.label})` : subject, + bank_name: null, + card_last4: null, + reason_code: 'parse_failed', + reason_label: DUE_DATE_ISSUE_LABELS.parse_failed, + detail: r, + }) + } else if (r.includes('宽限期') || r.includes('模糊')) { + items.push({ + source: 'email_parse_log', + id: `${log.id}#${i + 1}`, + created_at: createdAt, + from_email: fromEmail, + subject: entry?.label ? `${subject ?? '转发包'} (${entry.label})` : subject, + bank_name: null, + card_last4: null, + reason_code: 'ambiguous_or_grace_only', + reason_label: DUE_DATE_ISSUE_LABELS.ambiguous_or_grace_only, + detail: r, + }) + } else if (r.includes('邮件未提供确切还款日')) { + items.push({ + source: 'email_parse_log', + id: `${log.id}#${i + 1}`, + created_at: createdAt, + from_email: fromEmail, + subject: entry?.label ? `${subject ?? '转发包'} (${entry.label})` : subject, + bank_name: null, + card_last4: null, + reason_code: 'missing_in_email', + reason_label: DUE_DATE_ISSUE_LABELS.missing_in_email, + detail: r, + }) + } + } + return items + } + + // 2. 明确的非账单(营销/自动扣款通知/验证邮件)不计入账单还款日缺失 + if ( + errMsg.startsWith('Gmail 转发验证') || + errMsg.includes('email_kind=') || + (parsed && parsed.is_bill === false) + ) { + return [] + } + + const bankName = typeof parsed?.bank_name === 'string' ? parsed.bank_name : null + const cardLast4 = + typeof parsed?.card_last4 === 'string' ? normalizeTail(parsed.card_last4) || null : null + const rawDue = typeof parsed?.due_date === 'string' ? parsed.due_date.trim() : '' + const dueStatus = typeof parsed?.due_date_status === 'string' ? parsed.due_date_status : null + + // 3. 解析失败(status='failed' 且无有效 AI JSON,或 AI 接口报错,或建卡/入库失败导致未产出账单) + if (log.status === 'failed') { + if (!parsed) { + return [ + { + source: 'email_parse_log', + id: log.id, + created_at: createdAt, + from_email: fromEmail, + subject, + bank_name: null, + card_last4: null, + reason_code: 'parse_failed', + reason_label: DUE_DATE_ISSUE_LABELS.parse_failed, + detail: errMsg || '邮件 AI 解析失败,未生成结构化结果', + }, + ] + } + if (dueStatus === 'ambiguous_or_grace_only' || (rawDue && !isExactDueDate(rawDue))) { + return [ + { + source: 'email_parse_log', + id: log.id, + created_at: createdAt, + from_email: fromEmail, + subject, + bank_name: bankName, + card_last4: cardLast4, + reason_code: 'ambiguous_or_grace_only', + reason_label: DUE_DATE_ISSUE_LABELS.ambiguous_or_grace_only, + detail: errMsg || `邮件还款日「${rawDue || '宽限期规则'}」非确切日期`, + }, + ] + } + if (!rawDue) { + return [ + { + source: 'email_parse_log', + id: log.id, + created_at: createdAt, + from_email: fromEmail, + subject, + bank_name: bankName, + card_last4: cardLast4, + reason_code: 'missing_in_email', + reason_label: DUE_DATE_ISSUE_LABELS.missing_in_email, + detail: errMsg ? `邮件未提供还款日(且处理报错:${errMsg})` : '邮件未提供确切还款日', + }, + ] + } + return [ + { + source: 'email_parse_log', + id: log.id, + created_at: createdAt, + from_email: fromEmail, + subject, + bank_name: bankName, + card_last4: cardLast4, + reason_code: 'parse_failed', + reason_label: DUE_DATE_ISSUE_LABELS.parse_failed, + detail: errMsg || '账单入库失败', + }, + ] + } + + // 4. status === 'skipped'(含模糊日期跳过、缺少还款日跳过、或历史日志里 is_bill=true 但缺 due_date) + if (log.status === 'skipped') { + if ( + errMsg.includes('宽限期') || + errMsg.includes('模糊') || + dueStatus === 'ambiguous_or_grace_only' || + (rawDue && !isExactDueDate(rawDue)) + ) { + return [ + { + source: 'email_parse_log', + id: log.id, + created_at: createdAt, + from_email: fromEmail, + subject, + bank_name: bankName, + card_last4: cardLast4, + reason_code: 'ambiguous_or_grace_only', + reason_label: DUE_DATE_ISSUE_LABELS.ambiguous_or_grace_only, + detail: errMsg || '邮件仅含宽限期或还款日期模糊,未写入账单', + }, + ] + } + if ( + errMsg.includes('邮件未提供确切还款日') || + (parsed && parsed.is_bill === true && !rawDue && Number(parsed.bill_amount) !== 0) + ) { + return [ + { + source: 'email_parse_log', + id: log.id, + created_at: createdAt, + from_email: fromEmail, + subject, + bank_name: bankName, + card_last4: cardLast4, + reason_code: 'missing_in_email', + reason_label: DUE_DATE_ISSUE_LABELS.missing_in_email, + detail: errMsg || '邮件未提供确切还款日', + }, + ] + } + } + + return [] +} + +/** + * 分类 Gmail 同步审计记录与待确认草稿的还款日缺失原因。 + */ +export function classifyGmailMessageDueDateIssue( + msg: GmailSyncMessageLite, + draftById: Map, +): EmailIssueSummaryItem | null { + const errMsg = (msg.error_msg ?? '').trim() + if (msg.status === 'bill_written') return null + if (errMsg.includes('email_kind=')) return null + + const draft = msg.draft_id ? draftById.get(msg.draft_id) : undefined + const payload = draft ? parseJsonSafe(draft.parsed_payload) : null + if (payload && payload.is_bill === false) return null + + const bankName = typeof payload?.bank_name === 'string' ? payload.bank_name : null + const cardLast4 = + typeof payload?.card_last4 === 'string' ? normalizeTail(payload.card_last4) || null : null + const rawDue = typeof payload?.due_date === 'string' ? payload.due_date.trim() : '' + const dueStatus = typeof payload?.due_date_status === 'string' ? payload.due_date_status : null + + if (msg.status === 'failed') { + return { + source: 'gmail_sync', + id: msg.gmail_message_id, + created_at: msg.created_at, + from_email: msg.from_email ?? null, + subject: msg.subject ?? null, + bank_name: bankName, + card_last4: cardLast4, + reason_code: 'parse_failed', + reason_label: DUE_DATE_ISSUE_LABELS.parse_failed, + detail: errMsg || 'Gmail 账单邮件解析失败', + } + } + + if ( + errMsg.includes('宽限期') || + errMsg.includes('模糊') || + dueStatus === 'ambiguous_or_grace_only' || + (rawDue && !isExactDueDate(rawDue)) + ) { + return { + source: 'gmail_sync', + id: msg.gmail_message_id, + created_at: msg.created_at, + from_email: msg.from_email ?? null, + subject: msg.subject ?? null, + bank_name: bankName, + card_last4: cardLast4, + reason_code: 'ambiguous_or_grace_only', + reason_label: DUE_DATE_ISSUE_LABELS.ambiguous_or_grace_only, + detail: errMsg || '邮件仅含宽限期或还款日期模糊', + } + } + + if ( + errMsg.includes('邮件未提供确切还款日') || + (payload && payload.is_bill !== false && !rawDue && Number(payload.bill_amount) !== 0) + ) { + return { + source: 'gmail_sync', + id: msg.gmail_message_id, + created_at: msg.created_at, + from_email: msg.from_email ?? null, + subject: msg.subject ?? null, + bank_name: bankName, + card_last4: cardLast4, + reason_code: 'missing_in_email', + reason_label: DUE_DATE_ISSUE_LABELS.missing_in_email, + detail: errMsg || '邮件未提供确切还款日', + } + } + + return null +} + +function classifyStandaloneDraftIssue(draft: BillImportDraftLite): { + cardId: string | null + item: EmailIssueSummaryItem +} | null { + if (draft.status && draft.status !== 'draft' && draft.status !== 'pending') return null + const payload = parseJsonSafe(draft.parsed_payload) + if (!payload || payload.is_bill === false) return null + const rawDue = typeof payload.due_date === 'string' ? payload.due_date.trim() : '' + const dueStatus = typeof payload.due_date_status === 'string' ? payload.due_date_status : null + if (isExactDueDate(rawDue) && dueStatus !== 'ambiguous_or_grace_only') return null + if (Number(payload.bill_amount) === 0) return null + + const bankName = typeof payload.bank_name === 'string' ? payload.bank_name : null + const cardLast4 = + typeof payload.card_last4 === 'string' ? normalizeTail(payload.card_last4) || null : null + const reasonCode: DueDateMissingReasonCode = + dueStatus === 'ambiguous_or_grace_only' || rawDue.length > 0 + ? 'ambiguous_or_grace_only' + : 'missing_in_email' + + return { + cardId: draft.card_id ?? null, + item: { + source: 'bill_draft', + id: draft.id, + created_at: draft.created_at, + from_email: null, + subject: bankName ? `${bankName} 待确认账单草稿` : '待确认账单草稿', + bank_name: bankName, + card_last4: cardLast4, + reason_code: reasonCode, + reason_label: DUE_DATE_ISSUE_LABELS[reasonCode], + detail: + reasonCode === 'ambiguous_or_grace_only' + ? '草稿中还款日模糊或仅有宽限期' + : '草稿中邮件未提供确切还款日', + }, + } +} + +function matchesCard(card: CardForDueDateSummary, issue: EmailIssueSummaryItem): boolean { + const cardTail = normalizeTail(card.card_number_last4) + const cardBank = card.bank_name ?? card.card_product?.bank_name ?? '' + + if (issue.card_last4 && cardTail) { + if (issue.card_last4 !== cardTail) return false + if (issue.bank_name && cardBank) { + return bankMatches(issue.bank_name, cardBank) + } + return true + } + + // 解析失败(无结构化尾号)时,若邮件主题含银行名且(无尾号或主题含该卡尾号),允许关联提示 + if (issue.reason_code === 'parse_failed' && !issue.card_last4) { + const subj = `${issue.subject ?? ''} ${issue.detail ?? ''}` + if (cardTail && subj.includes(cardTail)) return true + if (cardBank && subj.toLowerCase().includes(cardBank.toLowerCase()) && !cardTail) return true + } + + return false +} + +/** + * 判断账单行是否携带真实确切的还款日(排除 0 元账单的月末 -28 / 出账日存储兜底)。 + */ +function pickExactBillDueDate( + bills: BillForDueDateSummary[], +): { dueDate: string; source: 'bill_email' | 'bill_override'; billMonth: string } | null { + const sorted = [...bills].sort((a, b) => { + const byMonth = (b.bill_month || '').localeCompare(a.bill_month || '') + if (byMonth !== 0) return byMonth + return (b.created_at || '').localeCompare(a.created_at || '') + }) + + for (const bill of sorted) { + if (bill.due_date_override && isExactDueDate(bill.due_date_override)) { + return { + dueDate: bill.due_date_override.trim(), + source: 'bill_override', + billMonth: bill.bill_month, + } + } + const rawDue = typeof bill.due_date === 'string' ? bill.due_date.trim() : '' + if (!isExactDueDate(rawDue)) continue + // 0 元账单在入库时允许在无 due_date 情况下回落 statement_date 或 `${bill_month}-28` 以满足 NOT NULL; + // 若金额为 0 且恰好等于回落占位值,不能当作邮件确切还款日展示。 + if (Number(bill.bill_amount) === 0) { + const fallback28 = `${bill.bill_month}-28` + if (rawDue === fallback28 || (bill.statement_date && rawDue === bill.statement_date)) { + continue + } + } + return { + dueDate: rawDue, + source: 'bill_email', + billMonth: bill.bill_month, + } + } + return null +} + +function getManualFixedDueDay(card: CardForDueDateSummary): number | null { + if (card.card_type === 'loan' && card.loan_due_day && card.loan_due_day >= 1 && card.loan_due_day <= 31) { + return card.loan_due_day + } + if ( + (card.override_due_type === 'fixed' || card.override_due_type === 'fixed_before_billing') && + card.override_due_value && + card.override_due_value >= 1 && + card.override_due_value <= 31 + ) { + return card.override_due_value + } + return null +} + +/** + * 纯函数:为单张卡计算还款日确切性与缺失原因汇总。 + */ +export function resolveCardDueDate(params: { + card: CardForDueDateSummary + bills: BillForDueDateSummary[] + matchedIssues: EmailIssueSummaryItem[] + hasAnyUserSyncActivity: boolean +}): CardDueDateResolution { + const { card, bills, matchedIssues, hasAnyUserSyncActivity } = params + const sortedIssues = [...matchedIssues].sort((a, b) => + (b.created_at || '').localeCompare(a.created_at || ''), + ) + + const counts = emptyReasonCounts() + for (const item of sortedIssues) { + counts[item.reason_code]++ + } + + const evidences: CardDueDateEmailEvidence[] = sortedIssues.slice(0, 10).map((item) => ({ + source: item.source, + id: item.id, + subject: item.subject, + from_email: item.from_email, + created_at: item.created_at, + reason_code: item.reason_code, + reason_label: item.reason_label, + detail: item.detail, + })) + + const exact = pickExactBillDueDate(bills) + const manualFixedDay = getManualFixedDueDay(card) + + if (exact) { + return { + has_exact_due_date: true, + exact_due_date: exact.dueDate, + exact_source: exact.source, + exact_bill_month: exact.billMonth, + manual_fixed_day: manualFixedDay, + reason_code: null, + reason_label: null, + summary: + exact.source === 'bill_override' + ? `${exact.dueDate}(${exact.billMonth} 账单人工确认)` + : `${exact.dueDate}(${exact.billMonth} 账单邮件)`, + email_evidences: evidences, + reason_counts: counts, + } + } + + // 无邮件/账单确切日期:严格按证据归入四类原因,绝不推算编造某月某日 + if (sortedIssues.length > 0) { + const primary = sortedIssues[0] + const parts: string[] = [] + if (counts.missing_in_email > 0) parts.push(`邮件未提供 ${counts.missing_in_email} 封`) + if (counts.ambiguous_or_grace_only > 0) + parts.push(`日期模糊/只有宽限期 ${counts.ambiguous_or_grace_only} 封`) + if (counts.parse_failed > 0) parts.push(`解析失败 ${counts.parse_failed} 封`) + return { + has_exact_due_date: false, + exact_due_date: null, + exact_source: null, + exact_bill_month: null, + manual_fixed_day: manualFixedDay, + reason_code: primary.reason_code, + reason_label: primary.reason_label, + summary: `未获取确切还款日(${parts.join(',')})`, + email_evidences: evidences, + reason_counts: counts, + } + } + + // 无任何命中邮件时:若用户仅设置了相对宽限期覆盖(after_billing),归入「日期模糊/只有宽限期」; + // 否则归入「未同步」(尚未同步到该卡的账单邮件)。 + if (card.override_due_type === 'after_billing' && card.override_due_value != null) { + counts.ambiguous_or_grace_only = 1 + return { + has_exact_due_date: false, + exact_due_date: null, + exact_source: null, + exact_bill_month: null, + manual_fixed_day: manualFixedDay, + reason_code: 'ambiguous_or_grace_only', + reason_label: DUE_DATE_ISSUE_LABELS.ambiguous_or_grace_only, + summary: `仅设置宽限期(账单日后 ${card.override_due_value} 天),尚无账单邮件确切日期`, + email_evidences: [], + reason_counts: counts, + } + } + + counts.unsynced = 1 + const graceHint = + card.card_product?.payment_due_type === 'after_billing' && card.card_product?.payment_due_value + ? `;卡产品默认仅含宽限期(账单日后 ${card.card_product.payment_due_value} 天),不编造具体日期` + : '' + return { + has_exact_due_date: false, + exact_due_date: null, + exact_source: null, + exact_bill_month: null, + manual_fixed_day: manualFixedDay, + reason_code: 'unsynced', + reason_label: DUE_DATE_ISSUE_LABELS.unsynced, + summary: hasAnyUserSyncActivity + ? `未同步到该卡的账单邮件${graceHint}` + : `尚未同步账单邮件${graceHint}`, + email_evidences: [], + reason_counts: counts, + } +} + +/** + * 纯函数:汇总一组卡片及全部邮件日志/Gmail 同步消息/草稿的还款日状态与缺失原因。 + */ +export function buildDueDateReasonReport(input: { + cards: CardForDueDateSummary[] + bills: BillForDueDateSummary[] + emailLogs: EmailParseLog[] + gmailMessages?: GmailSyncMessageLite[] + billDrafts?: BillImportDraftLite[] +}): DueDateReasonReport { + const { cards, bills, emailLogs, gmailMessages = [], billDrafts = [] } = input + const draftById = new Map(billDrafts.map((d) => [d.id, d])) + const referencedDraftIds = new Set( + gmailMessages.map((m) => m.draft_id).filter((id): id is string => !!id), + ) + + const allIssues: Array<{ explicitCardId?: string | null; item: EmailIssueSummaryItem }> = [] + for (const log of emailLogs) { + for (const item of classifyEmailLogDueDateIssue(log)) { + allIssues.push({ item }) + } + } + for (const msg of gmailMessages) { + const item = classifyGmailMessageDueDateIssue(msg, draftById) + if (item) { + const draft = msg.draft_id ? draftById.get(msg.draft_id) : undefined + allIssues.push({ explicitCardId: draft?.card_id ?? null, item }) + } + } + for (const draft of billDrafts) { + if (referencedDraftIds.has(draft.id)) continue + const res = classifyStandaloneDraftIssue(draft) + if (res) { + allIssues.push({ explicitCardId: res.cardId, item: res.item }) + } + } + + const hasAnyUserSyncActivity = + emailLogs.length > 0 || gmailMessages.length > 0 || billDrafts.length > 0 + + const billsByCard = new Map() + for (const b of bills) { + const arr = billsByCard.get(b.card_id) ?? [] + arr.push(b) + billsByCard.set(b.card_id, arr) + } + + const matchedIssueIds = new Set() + const byReason = emptyReasonCounts() + let withExact = 0 + let missingExact = 0 + + const cardReports = cards.map((card) => { + const cardIssues: EmailIssueSummaryItem[] = [] + for (const entry of allIssues) { + if ( + (entry.explicitCardId && entry.explicitCardId === card.id) || + matchesCard(card, entry.item) + ) { + cardIssues.push(entry.item) + matchedIssueIds.add(`${entry.item.source}:${entry.item.id}`) + } + } + const resolution = resolveCardDueDate({ + card, + bills: billsByCard.get(card.id) ?? [], + matchedIssues: cardIssues, + hasAnyUserSyncActivity, + }) + if (resolution.has_exact_due_date) { + withExact++ + } else { + missingExact++ + if (resolution.reason_code) byReason[resolution.reason_code]++ + } + return { + card_id: card.id, + bank_name: card.bank_name ?? card.card_product?.bank_name ?? '', + card_name: card.card_name ?? card.card_product?.card_name ?? '', + card_last4: card.card_number_last4 ?? '', + resolution, + } + }) + + const unmatched = allIssues + .filter((entry) => !matchedIssueIds.has(`${entry.item.source}:${entry.item.id}`)) + .map((entry) => entry.item) + + return { + cards_total: cards.length, + cards_with_exact_due_date: withExact, + cards_missing_exact_due_date: missingExact, + by_reason: byReason, + cards: cardReports, + unmatched_email_issues: unmatched, + } +} + +/** + * 服务端查询:为单张卡片从 D1 加载账单与所属用户的邮件/Gmail/草稿记录并生成 CardDueDateResolution。 + */ +export async function loadCardDueDateResolution( + card: CreditCard & { card_product?: CardProduct; bank_name?: string; card_name?: string }, +): Promise { + const holderRow = await queryOne<{ created_by: string; auth_user_id?: string | null }>( + 'SELECT created_by, auth_user_id FROM card_holders WHERE id = ?', + [card.holder_id], + ) + const ownerIds = Array.from( + new Set( + [holderRow.data?.created_by, holderRow.data?.auth_user_id].filter( + (v): v is string => typeof v === 'string' && v.length > 0, + ), + ), + ) + + const { data: billRows } = await query( + `SELECT id, card_id, bill_month, COALESCE(bill_amount_override, bill_amount) AS bill_amount, + statement_date, due_date, due_date_override, created_at + FROM bills WHERE card_id = ? ORDER BY bill_month DESC LIMIT 12`, + [card.id], + ) + + let emailLogs: EmailParseLog[] = [] + let gmailMessages: GmailSyncMessageLite[] = [] + let billDrafts: BillImportDraftLite[] = [] + + if (ownerIds.length > 0) { + const placeholders = ownerIds.map(() => '?').join(',') + const [logsRes, gmailRes, draftsRes] = await Promise.all([ + query( + `SELECT * FROM email_parse_logs WHERE user_id IN (${placeholders}) ORDER BY created_at DESC LIMIT 200`, + ownerIds, + ), + query( + `SELECT gmail_message_id, user_id, from_email, subject, status, bill_id, draft_id, error_msg, created_at + FROM gmail_sync_messages WHERE user_id IN (${placeholders}) ORDER BY created_at DESC LIMIT 200`, + ownerIds, + ), + query( + `SELECT id, created_by, card_id, source_type, parsed_payload, status, created_at + FROM bill_import_drafts WHERE created_by IN (${placeholders}) ORDER BY created_at DESC LIMIT 200`, + ownerIds, + ), + ]) + emailLogs = logsRes.data ?? [] + gmailMessages = gmailRes.data ?? [] + billDrafts = draftsRes.data ?? [] + } + + const report = buildDueDateReasonReport({ + cards: [card], + bills: (billRows ?? []) as Bill[], + emailLogs, + gmailMessages, + billDrafts, + }) + return report.cards[0].resolution +} diff --git a/lib/email-core/ai.ts b/lib/email-core/ai.ts index 4c78830..568f515 100644 --- a/lib/email-core/ai.ts +++ b/lib/email-core/ai.ts @@ -44,7 +44,7 @@ export async function loadAiConfig(db: D1Database): Promise { // ─── OpenAI bill parser ─────────────────────────────────────────────────────── const SYSTEM_PROMPT = `你是银行账单解析助手。从邮件内容中提取信用卡账单信息,以 JSON 格式返回: -{"is_bill":true,"email_kind":"statement","bank_name":"","card_last4":"","bill_amount":0,"min_payment":null,"due_date":"YYYY-MM-DD","bill_month":"YYYY-MM","statement_date":null,"statement_day":null,"currency":"CNY","confidence":0.9} +{"is_bill":true,"email_kind":"statement","bank_name":"","card_last4":"","bill_amount":0,"min_payment":null,"credit_limit":null,"due_date":"YYYY-MM-DD","due_date_status":"exact","bill_month":"YYYY-MM","statement_date":null,"statement_day":null,"currency":"CNY","confidence":0.9} 字段 card_last4 请填邮件中出现的"卡号/账户结尾"完整数字,不要截断: - 大陆/香港卡通常是末 4 位,如 "1234" - American Express 的账户结尾是 5 位,如 "93001",请原样填 5 位 @@ -56,6 +56,11 @@ email_kind 是邮件类型,按实际内容选: - "payment_reminder":还款提醒/催缴通知 - "other":营销或其他 只有 email_kind 是 "statement" 时 is_bill 才为 true;自动扣款通知、还款提醒即使提到金额和还款日,也不是新一期账单,is_bill 必须为 false(它们对应的那期账单已由真正的账单邮件建过,再解析会造出重复账单)。 +due_date 与 due_date_status 规则(严禁编造或推算还款日): +- 仅当邮件正文白纸黑字给出本期确切完整的还款截止日期(具体年月日,格式 YYYY-MM-DD)时,due_date 填该日期,due_date_status 填 "exact"。 +- 若邮件仅提到宽限期或相对规则(如「账单日后20天」「免息还款期最短20天」「每月15日还款」但未写明当期具体年月日)或日期表述模糊,禁止从账单日推算 due_date,due_date 必须填 null,due_date_status 填 "ambiguous_or_grace_only"。 +- 若邮件完全未提供还款日,due_date 填 null,due_date_status 填 "missing"。 +credit_limit 只在邮件正文明确写出卡片信用额度具体正数时填数值(纯数字);未提供填 null,禁止填写 0 或从账单金额/可用额度推算。 statement_date 只在邮件明确给出本期出账日/Statement Date(完整日期)时填写。注意:自动扣款通知里的 "Statement balance as of Oct 16" 不是出账日,不要填进 statement_date。 statement_day 只在邮件正文明确写出「账单日」及其数值(如「账单日 09」「账单日:每月21日」「Statement day: 22」)时填 1-31 的整数。不要从账期起止日期、还款日或 statement_date 推算;没有就填 null。 如果不是账单邮件,返回 {"is_bill": false} diff --git a/lib/email-core/bills.ts b/lib/email-core/bills.ts index 05693f0..cc803cf 100644 --- a/lib/email-core/bills.ts +++ b/lib/email-core/bills.ts @@ -9,6 +9,8 @@ */ import type { BillParseResult, HolderScopedBill, NestedBillMessage, RawAttachment } from './types' +import { evaluateParsedBillDueDate, extractValidCreditLimit, isExactDueDate } from './due-date' +import { isCmbStatement, parseCmbStatement } from './cmb' import { extractNameFromBody, isEmlAttachment, @@ -122,6 +124,7 @@ export function deriveBillingDayFromEmail(params: { */ export interface CardProductCandidate { id: string + bank_id?: string | null bank_name: string currency: string } @@ -176,6 +179,8 @@ export interface FindOrCreateCardParams { bankName: string | null /** AI 解出的币种,用于在同银行多产品里排除币种不符的候选。 */ currency: string | null + /** 邮件明确写出的信用额度(正数);缺失或 <= 0 时按未获取存兼容值 0。 */ + creditLimit?: number | null /** * false 时只查找不创建:归属不可信(回落默认持卡人)绝不能凭猜测 * 给某个人名下新建卡——2026-10-16 民生 0872 就这样被挂错了人。 @@ -195,10 +200,60 @@ export async function findOrCreateCardForHolder( const tail = normalizeCardTail(params.cardTail) if (!tail) return { ok: false, reason: '账单未给出尾号,跳过(避免误挂到其他卡)' } - const existing = await db.prepare( - 'SELECT id FROM credit_cards WHERE holder_id = ? AND card_number_last4 = ? LIMIT 1' - ).bind(params.holderId, tail).first<{ id: string }>() - if (existing) return { ok: true, cardId: existing.id, created: false } + const bankNameStr = (params.bankName ?? '').trim() + const isMergedCandidate = /招商|招行|民生|上海银行|北京银行/.test(bankNameStr) + + // 1. 若发卡行为合并出账模式(如招行),检查持卡人名下是否已有活跃合并账户 + let existingMergedAccount: { id: string; primary_card_id: string | null } | null = null + if (isMergedCandidate) { + try { + existingMergedAccount = await db + .prepare( + `SELECT id, primary_card_id FROM credit_accounts + WHERE holder_id = ? + AND (bank_name LIKE '%招商%' OR bank_name LIKE '%招行%' OR bank_name LIKE ? OR bank_id IN (SELECT id FROM banks WHERE name LIKE ?)) + AND statement_mode = 'merged' + AND status = 'active' + ORDER BY created_at ASC LIMIT 1` + ) + .bind(params.holderId, `%${bankNameStr}%`, `%${bankNameStr}%`) + .first<{ id: string; primary_card_id: string | null }>() + } catch { + existingMergedAccount = null + } + } + + // 2. 检查卡片是否已存在 + let existingCard: { id: string; account_id?: string | null } | null = null + try { + existingCard = await db.prepare( + 'SELECT id, account_id FROM credit_cards WHERE holder_id = ? AND card_number_last4 = ? LIMIT 1' + ).bind(params.holderId, tail).first<{ id: string; account_id?: string | null }>() + } catch { + const fallback = await db.prepare( + 'SELECT id FROM credit_cards WHERE holder_id = ? AND card_number_last4 = ? LIMIT 1' + ).bind(params.holderId, tail).first<{ id: string }>() + if (fallback) existingCard = { id: fallback.id } + } + + if (existingCard) { + if (existingMergedAccount && !existingCard.account_id) { + try { + await db.prepare('UPDATE credit_cards SET account_id = ? WHERE id = ?') + .bind(existingMergedAccount.id, existingCard.id).run() + } catch { + // ignore + } + } + return { ok: true, cardId: existingMergedAccount?.primary_card_id || existingCard.id, created: false } + } + + // 3. 卡片不存在,但已存在合并账户: + // PRD 与业务原则明确要求:「未知尾号只展示、不自动建卡(按需补建入口)」 + // 此时对齐到账户的锚点卡 primary_card_id,不伪造创建新卡片 + if (existingMergedAccount && existingMergedAccount.primary_card_id) { + return { ok: true, cardId: existingMergedAccount.primary_card_id, created: false } + } if (params.allowCreate === false) { return { @@ -211,7 +266,7 @@ export async function findOrCreateCardForHolder( // credit_cards.card_product_id 是 NOT NULL 且外键 RESTRICT,必须挂在真实卡产品上。 // 这里刻意不新建卡产品:缺少银行/卡种上下文时硬造会污染产品目录。 const products = await db.prepare( - 'SELECT id, bank_name, currency FROM card_products WHERE is_active = 1 ORDER BY created_at ASC, id ASC' + 'SELECT id, bank_id, bank_name, currency FROM card_products WHERE is_active = 1 ORDER BY created_at ASC, id ASC' ).all() const product = pickCardProductForBank(products.results ?? [], params.bankName, params.currency) if (!product) { @@ -242,11 +297,74 @@ export async function findOrCreateCardForHolder( } const cardId = crypto.randomUUID() - // 额度暂记 0:AI 结果里没有额度字段,宁可留空等用户补,也不猜一个数。 + // 额度:邮件明确给出正数额度则写入,否则记兼容值 0(credit_limit_override=NULL,界面识别为「未获取」)。 // 币种不落库在这里——它由 card_product 决定,所以上面必须挑对产品。 - await db.prepare( - 'INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) VALUES (?, ?, ?, ?, 0, ?, ?, ?)' - ).bind(cardId, params.holderId, product.id, tail, billingDay, 'active', 'credit').run() + const initialLimit = extractValidCreditLimit(params.creditLimit) + + let accountId: string | null = null + if (isMergedCandidate) { + accountId = crypto.randomUUID() + try { + await db.prepare( + `INSERT INTO credit_accounts (id, holder_id, bank_id, bank_name, currency, statement_mode, quota_mode, shared_credit_limit, billing_day, due_type, due_value, primary_card_id, status) + VALUES (?, ?, ?, ?, ?, 'merged', 'shared', ?, ?, 'after_billing', 20, NULL, 'active')` + ).bind( + accountId, + params.holderId, + product.bank_id || null, + product.bank_name || bankNameStr, + product.currency || 'CNY', + initialLimit, + billingDay + ).run() + } catch { + accountId = null + } + } + + if (initialLimit !== null) { + if (accountId) { + try { + await db.prepare( + 'INSERT INTO credit_cards (id, holder_id, account_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' + ).bind(cardId, params.holderId, accountId, product.id, tail, initialLimit, billingDay, 'active', 'credit').run() + } catch { + await db.prepare( + 'INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' + ).bind(cardId, params.holderId, product.id, tail, initialLimit, billingDay, 'active', 'credit').run() + } + } else { + await db.prepare( + 'INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' + ).bind(cardId, params.holderId, product.id, tail, initialLimit, billingDay, 'active', 'credit').run() + } + } else { + if (accountId) { + try { + await db.prepare( + 'INSERT INTO credit_cards (id, holder_id, account_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' + ).bind(cardId, params.holderId, accountId, product.id, tail, 0, billingDay, 'active', 'credit').run() + } catch { + await db.prepare( + 'INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) VALUES (?, ?, ?, ?, 0, ?, ?, ?)' + ).bind(cardId, params.holderId, product.id, tail, billingDay, 'active', 'credit').run() + } + } else { + await db.prepare( + 'INSERT INTO credit_cards (id, holder_id, card_product_id, card_number_last4, credit_limit, billing_day, status, card_type) VALUES (?, ?, ?, ?, 0, ?, ?, ?)' + ).bind(cardId, params.holderId, product.id, tail, billingDay, 'active', 'credit').run() + } + } + + // 确保账户挂载 primary_card_id 锚点卡 + if (accountId) { + try { + await db.prepare('UPDATE credit_accounts SET primary_card_id = ? WHERE id = ? AND primary_card_id IS NULL') + .bind(cardId, accountId).run() + } catch { + // ignore + } + } return { ok: true, cardId, created: true } } @@ -321,15 +439,63 @@ export async function upsertBillForCard( const amount = Number(parsed.bill_amount) const minPayment = parsed.min_payment != null ? Number(parsed.min_payment) : null const statementDate = parsed.statement_date ?? null - // 0 元账单的 due_date 兜底(bills.due_date NOT NULL):缺省时用账单日或月末; - // 0 元新账单 status 直接置 paid(应还 0 元 = 已还清),与直发路径同口径。 + // 非 0 元账单必须具备确切 YYYY-MM-DD 还款日,禁止 fallback 到 statementDate 或月末 -28 编造日期; + // 仅 0 元账单(无需还款,status=paid)在邮件未给还款日时满足 bills.due_date NOT NULL 存储约束。 const zeroBill = amount === 0 - const dueDate = (parsed.due_date as string | null) ?? statementDate ?? (billMonth + '-28') + const exactDue = isExactDueDate(parsed.due_date) && parsed.due_date_status !== 'ambiguous_or_grace_only' + ? parsed.due_date.trim() + : null + if (!zeroBill && !exactDue) { + const evalDue = evaluateParsedBillDueDate(parsed) + throw new Error(!evalDue.ok ? evalDue.reason : '缺少确切还款日(YYYY-MM-DD),禁止编造还款日') + } + const dueDate = exactDue ?? statementDate ?? (billMonth + '-28') const initialStatus = zeroBill ? 'paid' : 'unpaid' - const existing = await db.prepare( - 'SELECT id, status FROM bills WHERE card_id = ? AND bill_month = ?' - ).bind(cardId, billMonth).first<{ id: string; status: string | null }>() + // 解析归属账户与锚点卡 + let accountId: string | null = null + let anchorCardId = cardId + let holderId: string | null = null + + try { + const cardInfo = await db.prepare( + 'SELECT id, holder_id, account_id FROM credit_cards WHERE id = ?' + ).bind(cardId).first<{ id: string; holder_id: string; account_id: string | null }>() + if (cardInfo) { + holderId = cardInfo.holder_id + if (cardInfo.account_id) { + accountId = cardInfo.account_id + const accInfo = await db.prepare( + 'SELECT id, statement_mode, primary_card_id FROM credit_accounts WHERE id = ?' + ).bind(accountId).first<{ id: string; statement_mode: string; primary_card_id: string | null }>() + if (accInfo?.statement_mode === 'merged' && accInfo.primary_card_id) { + anchorCardId = accInfo.primary_card_id + } + } + } + } catch { + // 兼容桩环境 + } + + // 唯一性判定:若有 accountId 则优先查 (account_id, bill_month),否则查 (card_id, bill_month) + let existing: { id: string; status: string | null } | null = null + if (accountId) { + try { + existing = await db.prepare( + 'SELECT id, status FROM bills WHERE account_id = ? AND bill_month = ?' + ).bind(accountId, billMonth).first<{ id: string; status: string | null }>() + } catch { + existing = null + } + } + if (!existing) { + existing = await db.prepare( + 'SELECT id, status FROM bills WHERE card_id = ? AND bill_month = ?' + ).bind(anchorCardId, billMonth).first<{ id: string; status: string | null }>() + } + + let billId: string + let action: 'inserted' | 'updated' | 'preserved' if (existing) { if (!options.trusted) { @@ -339,17 +505,124 @@ export async function upsertBillForCard( reason: `该卡 ${billMonth} 账单已存在,但收件人无法确认归属(已回落默认持卡人),保留原值`, } } - await db.prepare( - 'UPDATE bills SET bill_amount = ?, min_payment = ?, due_date = ?, statement_date = ?, status = ? WHERE id = ?' - ).bind(amount, minPayment, dueDate, statementDate, keepPaidStatus(existing.status), existing.id).run() - return { billId: existing.id, action: 'updated', reason: null } + billId = existing.id + action = 'updated' + try { + await db.prepare( + 'UPDATE bills SET bill_amount = ?, min_payment = ?, due_date = ?, statement_date = ?, status = ?, account_id = COALESCE(account_id, ?) WHERE id = ?' + ).bind(amount, minPayment, dueDate, statementDate, keepPaidStatus(existing.status), accountId, existing.id).run() + } catch { + await db.prepare( + 'UPDATE bills SET bill_amount = ?, min_payment = ?, due_date = ?, statement_date = ?, status = ? WHERE id = ?' + ).bind(amount, minPayment, dueDate, statementDate, keepPaidStatus(existing.status), existing.id).run() + } + } else { + billId = crypto.randomUUID() + action = 'inserted' + if (accountId) { + try { + await db.prepare( + 'INSERT INTO bills (id, account_id, card_id, bill_month, bill_amount, min_payment, due_date, statement_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' + ).bind(billId, accountId, anchorCardId, billMonth, amount, minPayment, dueDate, statementDate, initialStatus).run() + } catch { + await db.prepare( + 'INSERT INTO bills (id, card_id, bill_month, bill_amount, min_payment, due_date, statement_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' + ).bind(billId, anchorCardId, billMonth, amount, minPayment, dueDate, statementDate, initialStatus).run() + } + } else { + await db.prepare( + 'INSERT INTO bills (id, card_id, bill_month, bill_amount, min_payment, due_date, statement_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' + ).bind(billId, anchorCardId, billMonth, amount, minPayment, dueDate, statementDate, initialStatus).run() + } + } + + // 写入/更新分卡小计(bill_card_subtotals) + if (parsed.card_subtotals && parsed.card_subtotals.length > 0) { + for (const sub of parsed.card_subtotals) { + const subTail = normalizeCardTail(sub.card_last4) + if (!subTail) continue + + let subCardId: string | null = null + if (holderId) { + try { + const matchedCard = await db.prepare( + 'SELECT id FROM credit_cards WHERE holder_id = ? AND card_number_last4 = ? LIMIT 1' + ).bind(holderId, subTail).first<{ id: string }>() + if (matchedCard) subCardId = matchedCard.id + } catch { + // ignore + } + } + + const subId = crypto.randomUUID() + try { + await db.prepare( + `INSERT INTO bill_card_subtotals (id, bill_id, card_id, card_tail, subtotal_amount, currency, source) + VALUES (?, ?, ?, ?, ?, ?, 'email') + ON CONFLICT(bill_id, card_tail) DO UPDATE SET + card_id = excluded.card_id, + subtotal_amount = excluded.subtotal_amount, + currency = excluded.currency` + ).bind(subId, billId, subCardId, subTail, sub.amount, sub.currency || 'CNY').run() + } catch { + // ignore + } + } + } + + return { billId, action, reason: null } +} + +/** + * 邮件明确写出正数信用额度时,仅在卡片当前为「未获取」(credit_limit <= 0 且无人工覆盖)时回填。 + * 绝不触碰 credit_limit_override,也不覆盖用户已设置的额度。 + */ +export async function syncCreditLimitFromBill( + db: D1Database, + cardId: string, + parsed: BillParseResult +): Promise { + const candidate = extractValidCreditLimit(parsed.credit_limit) + if (candidate === null) return false + + let card: { credit_limit: number | null; credit_limit_override?: number | null; account_id?: string | null } | null + try { + card = await db + .prepare('SELECT credit_limit, credit_limit_override, account_id FROM credit_cards WHERE id = ?') + .bind(cardId) + .first<{ credit_limit: number | null; credit_limit_override?: number | null; account_id?: string | null }>() + } catch { + card = await db + .prepare('SELECT credit_limit, credit_limit_override FROM credit_cards WHERE id = ?') + .bind(cardId) + .first<{ credit_limit: number | null; credit_limit_override?: number | null }>() + } + if (!card) return false + + // 同步账户级共享额度(若卡片属于共享额度账户且账户尚未设置共享额度) + if (card.account_id) { + try { + const acc = await db + .prepare('SELECT id, shared_credit_limit, quota_mode FROM credit_accounts WHERE id = ?') + .bind(card.account_id) + .first<{ id: string; shared_credit_limit: number | null; quota_mode: string }>() + if (acc && acc.quota_mode === 'shared' && (acc.shared_credit_limit == null || acc.shared_credit_limit <= 0)) { + await db.prepare('UPDATE credit_accounts SET shared_credit_limit = ? WHERE id = ?') + .bind(candidate, acc.id).run() + } + } catch { + // ignore + } } - const billId = crypto.randomUUID() - await db.prepare( - 'INSERT INTO bills (id, card_id, bill_month, bill_amount, min_payment, due_date, statement_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' - ).bind(billId, cardId, billMonth, amount, minPayment, dueDate, statementDate, initialStatus).run() - return { billId, action: 'inserted', reason: null } + if (card.credit_limit_override != null) return false + if ((Number(card.credit_limit) || 0) > 0) return false + + await db + .prepare('UPDATE credit_cards SET credit_limit = ? WHERE id = ?') + .bind(candidate, cardId) + .run() + return true } /** @@ -475,23 +748,21 @@ export async function persistNestedBills( let parsed: BillParseResult try { - parsed = await parse(message.text) + if (isCmbStatement({ fromEmail: message.from, subject: message.subject, text: message.text })) { + parsed = parseCmbStatement(message.text) + } else { + parsed = await parse(message.text) + } } catch (err) { skipped.push({ label: message.label, reason: 'AI 解析失败:' + (err instanceof Error ? err.message : String(err)) }) continue } - // 转发包里混着「电子对账单已可查阅」这类通知和营销邮件,字段不全的一律跳过 - // 与直发路径同口径:0 元账单合法(== null 判空,不用 falsy); - // 0 元时 due_date 可缺(无需还款就没有截止日) - const zeroBill = Number(parsed.bill_amount) === 0 - if ( - parsed.is_bill === false || - !parsed.bill_month || - parsed.bill_amount == null || Number.isNaN(Number(parsed.bill_amount)) || - (!zeroBill && !parsed.due_date) - ) { - skipped.push({ label: message.label, reason: '非账单或缺少必填字段' }) + // 转发包里混着「电子对账单已可查阅」这类通知和营销邮件,字段不全的一律跳过; + // 非 0 元账单必须有确切 YYYY-MM-DD 还款日,明确区分「邮件未提供」与「日期模糊/只有宽限期」。 + const dueEval = evaluateParsedBillDueDate(parsed) + if (!dueEval.ok) { + skipped.push({ label: message.label, reason: dueEval.reason }) continue } @@ -514,10 +785,11 @@ export async function persistNestedBills( cardTail: parsed.card_last4 ?? null, statementDate: parsed.statement_date ?? null, statementDay: parsed.statement_day ?? null, - dueDate: parsed.due_date ?? null, + dueDate: dueEval.dueDate, receivedDate: message.date, bankName: parsed.bank_name ?? null, currency: parsed.currency ?? null, + creditLimit: parsed.credit_limit ?? null, // 归属不可信时绝不自动建卡(会挂到默认持卡人头上);落草稿等人工确认。 allowCreate: trusted, }) @@ -541,6 +813,7 @@ export async function persistNestedBills( } // 每期账单落库后回写卡档账单日(有出账日证据互相印证才动,见函数注释) const billingDayUpdated = await syncBillingDayFromBill(db, card.cardId, parsed) + await syncCreditLimitFromBill(db, card.cardId, parsed) written.push({ holderId: resolution.holderId, holderName: scope.holders.find(h => h.id === resolution.holderId)?.name ?? '', diff --git a/lib/email-core/cmb.ts b/lib/email-core/cmb.ts new file mode 100644 index 0000000..446a512 --- /dev/null +++ b/lib/email-core/cmb.ts @@ -0,0 +1,177 @@ +// lib/email-core/cmb.ts — 招商银行信用卡电子账单识别与专用解析器 + +import type { BillParseResult } from './types' + +export interface CmbRecognitionParams { + fromEmail?: string | null + subject?: string | null + text: string +} + +/** + * 招商银行账单邮件识别规则: + * 1. 发件域特征:from 包含 cmbchina.com,或正文包含 cmbchina.com / 招商银行 + * 2. 主题/关键词特征:主题或正文包含「个人消费卡账户」「信用卡账单已出」「最后还款日」等关键词 + */ +export function isCmbStatement(params: CmbRecognitionParams): boolean { + const { fromEmail, subject, text } = params + const from = (fromEmail ?? '').toLowerCase() + const subj = subject ?? '' + const body = text ?? '' + + const isCmbDomainOrBrand = + from.includes('cmbchina.com') || + body.includes('cmbchina.com') || + body.includes('招商银行') + + if (!isCmbDomainOrBrand) return false + + const hasStatementKeywords = + /个人消费卡账户|信用卡账单已出|最后还款日/.test(subj) || + /个人消费卡账户.*账单|信用卡账单已出|最后还款日\(Payment Due Date\)/.test(body) + + return hasStatementKeywords +} + +interface ParsedTransaction { + amount: number + cardTail: string + kind: 'payment' | 'installment' | 'consumption' +} + +/** + * 招商银行专用结构化账单解析器 + */ +export function parseCmbStatement(text: string): BillParseResult { + // 1. 账单月(bill_month) + let billMonth: string | null = null + const monthMatch = text.match(/(\d{4})年\s*(\d{1,2})月(?:信用卡)?账单已出/) + if (monthMatch) { + billMonth = `${monthMatch[1]}-${monthMatch[2].padStart(2, '0')}` + } else { + const accMonthMatch = text.match(/个人消费卡账户\s*(\d{1,2})月账单/) + if (accMonthMatch) { + const yearMatch = text.match(/(\d{4})[年/-]/) + const year = yearMatch ? yearMatch[1] : String(new Date().getFullYear()) + billMonth = `${year}-${accMonthMatch[1].padStart(2, '0')}` + } + } + + // 2. 最后还款日(due_date),年份按账单月推导 + const dueMatch = text.match(/最后还款日(?:\(Payment Due Date\))?\s*(\d{1,2})月(\d{1,2})日/) + let dueDate: string | null = null + let dueDateStatus: 'exact' | 'missing' = 'missing' + if (dueMatch && billMonth) { + const billYear = parseInt(billMonth.slice(0, 4), 10) + const billMon = parseInt(billMonth.slice(5, 7), 10) + const dueMon = parseInt(dueMatch[1], 10) + const dueDay = parseInt(dueMatch[2], 10) + // 若还款月小于账单月(如 12 月账单 1 月还款),年份顺延到下一年 + const dueYear = dueMon < billMon ? billYear + 1 : billYear + dueDate = `${dueYear}-${String(dueMon).padStart(2, '0')}-${String(dueDay).padStart(2, '0')}` + dueDateStatus = 'exact' + } + + // 3. 信用额度(credit_limit) + const limitMatch = text.match(/信用额度\s*(?:Credit Limit)?\s*[¥¥\s]*([0-9,]+(?:\.[0-9]{2})?)/i) + const creditLimit = limitMatch ? parseFloat(limitMatch[1].replace(/,/g, '')) : null + + // 4. 本期应还金额(bill_amount) + const amountMatch = text.match(/本期应还金额\s*(?:New Balance)?\s*[¥¥\s]*([0-9,-]+(?:\.[0-9]{2})?)/i) + const billAmount = amountMatch ? parseFloat(amountMatch[1].replace(/,/g, '')) : 0 + + // 5. 最低还款额(min_payment) + const minMatch = text.match(/(?:本期)?最低还款额\s*(?:Min\.?\s*Payment)?\s*[¥¥\s]*([0-9,]+(?:\.[0-9]{2})?)/i) + const minPayment = minMatch ? parseFloat(minMatch[1].replace(/,/g, '')) : null + + // 6. 应还公式分解(上期/还款/新增/调整/利息)能提则提 + let formula: BillParseResult['formula_breakdown'] = null + const formulaSectionMatch = text.match(/Balance B\/F[\s\S]*?Interest\s+([¥¥\s0-9,.-]+)/i) + if (formulaSectionMatch) { + const numbers = formulaSectionMatch[1].match(/[¥¥]?\s*([0-9,-]+\.[0-9]{2})/g) + if (numbers && numbers.length >= 6) { + const vals = numbers.map(s => parseFloat(s.replace(/[¥¥\s,]/g, ''))) + formula = { + previous_balance: vals[1], + previous_payment: vals[2], + new_charges: vals[3], + adjustment: vals[4], + interest: vals[5], + } + } + } + + // 7. 交易明细与分卡小计(bill_card_subtotals) + const subtotals: NonNullable = [] + let cardLast4: string | null = null + + const txHeaderIdx = text.search(/交易日[\s\S]*?记账日[\s\S]*?交易摘要/) + if (txHeaderIdx !== -1) { + const txSection = text.slice(txHeaderIdx) + const payIdx = txSection.search(/\n\s*还款/) + const instIdx = txSection.search(/\n\s*分期/) + const consIdx = txSection.search(/\n\s*消费/) + const endIdx = txSection.search(/\n\s*上述交易摘要中的商户名称/) + + // 匹配格式:¥ 金额,其后紧跟 4 位卡号 + const txRegex = /¥\s*([0-9,-]+(?:\.[0-9]{2})?)\s*(?:\n|\s+)(\d{4})/g + let match: RegExpExecArray | null + const items: ParsedTransaction[] = [] + + while ((match = txRegex.exec(txSection)) !== null) { + const pos = match.index + if (endIdx !== -1 && pos > endIdx) break + const amt = parseFloat(match[1].replace(/,/g, '')) + const tail = match[2] + + let kind: ParsedTransaction['kind'] = 'consumption' + if (payIdx !== -1 && pos >= payIdx && (instIdx === -1 || pos < instIdx)) { + kind = 'payment' + } else if (instIdx !== -1 && pos >= instIdx && (consIdx === -1 || pos < consIdx)) { + kind = 'installment' + } + items.push({ amount: amt, cardTail: tail, kind }) + } + + const uniqueTails = [...new Set(items.map(i => i.cardTail))] + if (uniqueTails.length === 1) { + // 单卡样本小计 = 账户总额 + cardLast4 = uniqueTails[0] + subtotals.push({ + card_last4: uniqueTails[0], + amount: billAmount, + currency: 'CNY', + }) + } else if (uniqueTails.length > 1) { + // 多卡时各尾号求和(含还款/分期/消费全部分段),与总额差额按 PRD 归「上期结转/账户级调整」,不反向覆写总额 + cardLast4 = uniqueTails[0] + for (const tail of uniqueTails) { + const tailItems = items.filter(i => i.cardTail === tail) + const sum = tailItems.reduce((acc, i) => acc + i.amount, 0) + subtotals.push({ + card_last4: tail, + amount: Math.round(sum * 100) / 100, + currency: 'CNY', + }) + } + } + } + + return { + is_bill: true, + email_kind: 'statement', + bank_name: '招商银行', + statement_scope: 'account_merged', + card_last4: cardLast4, + bill_month: billMonth ?? undefined, + due_date: dueDate, + due_date_status: dueDateStatus, + credit_limit: creditLimit, + bill_amount: billAmount, + min_payment: minPayment, + currency: 'CNY', + confidence: 0.98, + card_subtotals: subtotals, + formula_breakdown: formula, + } +} diff --git a/lib/email-core/due-date.ts b/lib/email-core/due-date.ts new file mode 100644 index 0000000..41d670c --- /dev/null +++ b/lib/email-core/due-date.ts @@ -0,0 +1,107 @@ +/** + * 邮件还款日确切性校验与缺失原因分类(email-worker 与主工程共用,零外部依赖)。 + * + * 铁律:只有邮件给出确切的 YYYY-MM-DD 真日历日才允许写入/展示还款日; + * 缺失、解析失败、或仅有宽限期/模糊日期一律不编造日期,并明确归因。 + */ + +import type { BillParseResult } from './types' + +export type DueDateIssueKind = + | 'missing_in_email' + | 'parse_failed' + | 'ambiguous_or_grace_only' + | 'unsynced' + +export const DUE_DATE_ISSUE_LABELS: Record = { + missing_in_email: '邮件未提供', + parse_failed: '解析失败', + ambiguous_or_grace_only: '日期模糊/只有宽限期', + unsynced: '未同步', +} + +/** + * 严格校验 YYYY-MM-DD 真日历日(拦截 2026-02-30、相对描述「账单日后20天」、不完整年月等)。 + */ +export function isExactDueDate(value: unknown): value is string { + if (typeof value !== 'string') return false + const trimmed = value.trim() + const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(trimmed) + if (!m) return false + const year = Number(m[1]) + const month = Number(m[2]) + const day = Number(m[3]) + const utc = new Date(Date.UTC(year, month - 1, day)) + return ( + utc.getUTCFullYear() === year && + utc.getUTCMonth() === month - 1 && + utc.getUTCDate() === day + ) +} + +export type ParsedBillDueDateEvaluation = + | { ok: true; dueDate: string | null; zeroBill: boolean } + | { + ok: false + kind: 'not_a_bill' | 'missing_in_email' | 'ambiguous_or_grace_only' + reason: string + } + +/** + * 入库前校验解析结果中的账单基础字段与确切还款日。 + * + * - 非账单或缺 bill_month / bill_amount:返回 kind='not_a_bill'(保持既有「非账单或缺少必填字段」文案兼容)。 + * - 0 元账单(应还 0 元无需还款):due_date 若确切则采用,否则返回 dueDate=null。 + * - 非 0 元账单:必须具备确切 YYYY-MM-DD 还款日;否则精确区分 + * `ambiguous_or_grace_only`(日期模糊/只有宽限期)与 `missing_in_email`(邮件未提供)。 + */ +export function evaluateParsedBillDueDate(parsed: BillParseResult): ParsedBillDueDateEvaluation { + if ( + parsed.is_bill === false || + !parsed.bill_month || + parsed.bill_amount == null || + Number.isNaN(Number(parsed.bill_amount)) + ) { + return { ok: false, kind: 'not_a_bill', reason: '非账单或缺少必填字段' } + } + + const zeroBill = Number(parsed.bill_amount) === 0 + const rawDue = typeof parsed.due_date === 'string' ? parsed.due_date.trim() : '' + const hasValidDate = isExactDueDate(rawDue) + + if (zeroBill) { + return { + ok: true, + dueDate: hasValidDate && parsed.due_date_status !== 'ambiguous_or_grace_only' ? rawDue : null, + zeroBill: true, + } + } + + if (hasValidDate && parsed.due_date_status !== 'ambiguous_or_grace_only') { + return { ok: true, dueDate: rawDue, zeroBill: false } + } + + if (parsed.due_date_status === 'ambiguous_or_grace_only' || rawDue.length > 0) { + return { + ok: false, + kind: 'ambiguous_or_grace_only', + reason: '还款日模糊或仅有宽限期,未写入账单(禁止编造还款日)', + } + } + + return { + ok: false, + kind: 'missing_in_email', + reason: '邮件未提供确切还款日,未写入账单', + } +} + +/** + * 提取合法正数信用额度;0、负数、NaN、null 一律视为未获取(null)。 + */ +export function extractValidCreditLimit(value: unknown): number | null { + if (value == null || value === '') return null + const num = Number(value) + if (!Number.isFinite(num) || num <= 0) return null + return num +} diff --git a/lib/email-core/index.ts b/lib/email-core/index.ts index e02f8b8..9058f5b 100644 --- a/lib/email-core/index.ts +++ b/lib/email-core/index.ts @@ -7,3 +7,5 @@ export * from "./mime"; export * from "./holders"; export * from "./bills"; export * from "./ai"; +export * from "./due-date"; +export * from "./cmb"; diff --git a/lib/email-core/types.ts b/lib/email-core/types.ts index 37bf57e..865f9e6 100644 --- a/lib/email-core/types.ts +++ b/lib/email-core/types.ts @@ -20,7 +20,22 @@ export interface BillParseResult { card_last4?: string | null bill_amount?: number min_payment?: number | null - due_date?: string + /** + * 邮件白纸黑字写出的当期确切完整还款截止日(YYYY-MM-DD)。 + * 若未提供或仅有宽限期/相对规则,必须为 null,禁止推算或编造。 + */ + due_date?: string | null + /** + * 还款日提取状态: + * - exact:邮件明确给出完整日期 YYYY-MM-DD + * - ambiguous_or_grace_only:仅给出宽限期(如「账单日后20天」「免息期20天」)或每月固定日无具体年月、日期模糊 + * - missing:邮件未提及还款日 + */ + due_date_status?: 'exact' | 'ambiguous_or_grace_only' | 'missing' | null + /** + * 邮件正文明确写出的信用额度(正数);未提及填 null,禁止推算或编造。 + */ + credit_limit?: number | null bill_month?: string statement_date?: string | null /** @@ -37,6 +52,30 @@ export interface BillParseResult { email_kind?: 'statement' | 'autopay_scheduled' | 'payment_reminder' | 'other' | null currency?: string confidence?: number + /** + * 账单范围: + * - account_merged: 个人消费账户/多卡统一账单 + * - single_card: 独立单卡账单 + * - unknown: 未知/未指定 + */ + statement_scope?: 'account_merged' | 'single_card' | 'unknown' | null + /** 账户尾号(若银行区分账户号与卡号) */ + account_tail?: string | null + /** 分卡消费/应还小计列表 */ + card_subtotals?: Array<{ + card_last4: string + card_name?: string | null + amount: number + currency?: string | null + }> + /** 应还公式分解(上期/还款/新增/调整/利息) */ + formula_breakdown?: { + previous_balance?: number | null + previous_payment?: number | null + new_charges?: number | null + adjustment?: number | null + interest?: number | null + } | null } export interface BillRow { diff --git a/lib/export.ts b/lib/export.ts index 65c608c..fa1cc7f 100644 --- a/lib/export.ts +++ b/lib/export.ts @@ -145,6 +145,8 @@ async function exportBills( }) .map(bill => ({ '账单月份': bill.bill_month, + '账户模式': bill.account?.statement_mode === 'merged' ? '合并账单' : '独立账单', + '关联卡尾号': bill.account_card_tails || formatCardTail(bill.credit_cards.card_number_last4), '银行': bill.credit_cards.bank_name, '卡片': bill.credit_cards.card_name, '卡号末四位': formatCardTail(bill.credit_cards.card_number_last4), diff --git a/lib/gmail/sync.server.ts b/lib/gmail/sync.server.ts index 8c94c37..b6974a1 100644 --- a/lib/gmail/sync.server.ts +++ b/lib/gmail/sync.server.ts @@ -19,6 +19,10 @@ import { upsertBillForCard, parkBillAsDraft, syncBillingDayFromBill, + syncCreditLimitFromBill, + evaluateParsedBillDueDate, + isCmbStatement, + parseCmbStatement, type BillParseResult, } from "../email-core"; import { decryptToken } from "./token-crypto"; @@ -101,7 +105,10 @@ export async function syncUserGmail( if (!conn.data) throw new Error("未连接 Gmail 或连接已停用"); const deps: SyncDeps = depsOverride ?? { - parse: async (text) => parseBillWithAI(await loadAiConfig(db), text), + parse: async (text) => + isCmbStatement({ text }) + ? parseCmbStatement(text) + : parseBillWithAI(await loadAiConfig(db), text), }; const secret = resolveSecret(deps.sessionSecret); const env = getWorkerEnv() as { @@ -244,15 +251,15 @@ async function routeParsedMessage(params: { if (aiResult.email_kind && aiResult.email_kind !== "statement") { return { status: "skipped", reason: `非账单邮件(email_kind=${aiResult.email_kind})` }; } - const zeroBill = Number(aiResult.bill_amount) === 0; - if ( - aiResult.is_bill === false || - !aiResult.bill_month || - aiResult.bill_amount == null || - Number.isNaN(Number(aiResult.bill_amount)) || - (!zeroBill && !aiResult.due_date) - ) { - return { status: "skipped", reason: "Not a bill email or missing required fields" }; + const dueEval = evaluateParsedBillDueDate(aiResult); + if (!dueEval.ok) { + return { + status: "skipped", + reason: + dueEval.kind === "not_a_bill" + ? "Not a bill email or missing required fields" + : dueEval.reason, + }; } const scope = await loadHolderScope(db, userId); @@ -277,9 +284,10 @@ async function routeParsedMessage(params: { cardTail: aiResult.card_last4 ?? null, bankName: aiResult.bank_name ?? null, currency: aiResult.currency ?? null, + creditLimit: aiResult.credit_limit ?? null, statementDate: aiResult.statement_date ?? null, statementDay: aiResult.statement_day ?? null, - dueDate: aiResult.due_date ?? null, + dueDate: dueEval.dueDate, receivedDate: top.headers.date ?? null, allowCreate: trusted, }); @@ -290,6 +298,7 @@ async function routeParsedMessage(params: { const outcome = await upsertBillForCard(db, created.cardId, aiResult, { trusted }); await syncBillingDayFromBill(db, created.cardId, aiResult); + await syncCreditLimitFromBill(db, created.cardId, aiResult); return { status: "bill_written", billId: outcome.billId, diff --git a/lib/hooks/useTheme.ts b/lib/hooks/useTheme.ts new file mode 100644 index 0000000..858ecf1 --- /dev/null +++ b/lib/hooks/useTheme.ts @@ -0,0 +1,113 @@ +'use client' + +import { useState, useEffect, useCallback } from 'react' + +export type ThemeMode = 'system' | 'light' | 'dark' +export type ResolvedTheme = 'light' | 'dark' + +export const THEME_STORAGE_KEY = 'worldcredit_theme_mode' + +/** 根据当前设定与系统偏好推导最终生效的亮暗主题(去嵌套三元) */ +export function resolveTheme(mode: ThemeMode): ResolvedTheme { + if (mode === 'light') return 'light' + if (mode === 'dark') return 'dark' + // mode === 'system' + if (typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches) { + return 'dark' + } + return 'light' +} + +/** 写入 DOM 属性与类名,保证与 Tailwind / globals.css 契约一致 */ +export function applyResolvedTheme(resolved: ResolvedTheme): void { + if (typeof document === 'undefined') return + document.documentElement.setAttribute('data-theme', resolved) + if (resolved === 'light') { + document.documentElement.classList.add('theme-light') + document.documentElement.classList.remove('theme-dark') + } else { + document.documentElement.classList.add('theme-dark') + document.documentElement.classList.remove('theme-light') + } +} + +/** 获取初始 ThemeMode(客户端优先读 localStorage) */ +export function getStoredThemeMode(): ThemeMode { + if (typeof window === 'undefined') return 'system' + try { + const saved = localStorage.getItem(THEME_STORAGE_KEY) as ThemeMode | null + if (saved === 'light' || saved === 'dark' || saved === 'system') { + return saved + } + } catch { + // ignore + } + return 'system' +} + +/** 获取初始 ResolvedTheme(优先读取水合前内联脚本已设置的 DOM 状态,彻底告别硬编码 dark) */ +export function getInitialResolvedTheme(): ResolvedTheme { + if (typeof document !== 'undefined') { + const attr = document.documentElement.getAttribute('data-theme') + if (attr === 'light' || attr === 'dark') return attr + if (document.documentElement.classList.contains('theme-light')) return 'light' + if (document.documentElement.classList.contains('theme-dark')) return 'dark' + } + return resolveTheme(getStoredThemeMode()) +} + +export function useTheme() { + const [theme, setThemeState] = useState(getStoredThemeMode) + const [resolvedTheme, setResolvedTheme] = useState(getInitialResolvedTheme) + + useEffect(() => { + if (typeof window === 'undefined') return + const initialTheme = getStoredThemeMode() + setThemeState(initialTheme) + + const applyTheme = (mode: ThemeMode) => { + const resolved = resolveTheme(mode) + setResolvedTheme(resolved) + applyResolvedTheme(resolved) + } + + applyTheme(initialTheme) + + const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)') + const handleChange = () => { + const current = localStorage.getItem(THEME_STORAGE_KEY) as ThemeMode | null + if (!current || current === 'system') { + applyTheme('system') + } + } + + mediaQuery.addEventListener('change', handleChange) + return () => mediaQuery.removeEventListener('change', handleChange) + }, []) + + const setTheme = useCallback((newTheme: ThemeMode) => { + setThemeState(newTheme) + if (typeof window === 'undefined') return + try { + localStorage.setItem(THEME_STORAGE_KEY, newTheme) + } catch { + // ignore + } + const resolved = resolveTheme(newTheme) + setResolvedTheme(resolved) + applyResolvedTheme(resolved) + }, []) + + const cycleTheme = useCallback(() => { + if (theme === 'dark') setTheme('light') + else if (theme === 'light') setTheme('system') + else setTheme('dark') + }, [theme, setTheme]) + + return { + theme, + resolvedTheme, + setTheme, + cycleTheme, + } +} diff --git a/lib/hooks/useUserPreferences.ts b/lib/hooks/useUserPreferences.ts index bb2517e..e0fd505 100644 --- a/lib/hooks/useUserPreferences.ts +++ b/lib/hooks/useUserPreferences.ts @@ -9,9 +9,35 @@ import { DEFAULT_REMINDER_CONFIG } from '../api/preferences' import type { UserDisplayConfig, UserReminderConfig } from '../types' +import { resolveEffectiveChannels } from '@/components/settings/shared' const PREF_CACHE_KEY = 'worldcredit_user_prefs_cache' +function showToastMessage(message: string) { + if (typeof document === 'undefined') return + const id = 'wc-pref-toast-container' + let container = document.getElementById(id) + if (!container) { + container = document.createElement('div') + container.id = id + container.className = + 'pointer-events-none fixed inset-x-0 bottom-24 z-[1400] flex justify-center px-4 transition-opacity' + document.body.appendChild(container) + } + const toastEl = document.createElement('div') + toastEl.setAttribute('role', 'status') + toastEl.className = + 'pointer-events-auto max-w-sm rounded-xl border border-d-danger-ink/40 bg-d-danger-soft px-4 py-3 text-[13px] font-semibold leading-5 text-d-danger-ink shadow-lg' + toastEl.textContent = message + container.innerHTML = '' + container.appendChild(toastEl) + setTimeout(() => { + if (container && container.contains(toastEl)) { + container.removeChild(toastEl) + } + }, 3500) +} + export function useUserPreferences() { const { user } = useAuth() const [displayConfig, setDisplayConfig] = useState(() => { @@ -33,7 +59,13 @@ export function useUserPreferences() { const cached = localStorage.getItem(PREF_CACHE_KEY) if (cached) { try { - return JSON.parse(cached).reminder_config || DEFAULT_REMINDER_CONFIG + 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 } @@ -43,19 +75,35 @@ export function useUserPreferences() { }) const [loading, setLoading] = useState(false) + const [loadError, setLoadError] = useState(null) const loadPreferences = useCallback(async () => { if (!user?.id) return setLoading(true) + setLoadError(null) try { const prefs = await getUserPreferences(user.id) + let reminder = prefs.reminder_config + + // 存量迁移:读取偏好时若 enabled_channels 未设置而旧 opportunities.web_push_enabled === false, + // 则迁移为不含 web_push 的 enabled_channels,并写回一次;绝不让显式关闭过的用户被重新开启。 + if (reminder.enabled_channels === undefined && reminder.opportunities?.web_push_enabled === false) { + reminder = { ...reminder, enabled_channels: [] } + try { + await updateUserPreferences(user.id, { reminder_config: reminder }) + } catch (e) { + console.warn('Failed to write back migrated reminder preferences:', e) + } + } + setDisplayConfig(prefs.display_config) - setReminderConfig(prefs.reminder_config) + setReminderConfig(reminder) if (typeof window !== 'undefined') { - localStorage.setItem(PREF_CACHE_KEY, JSON.stringify(prefs)) + localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...prefs, reminder_config: reminder })) } } catch (err) { console.error('Failed to load user preferences:', err) + setLoadError(err instanceof Error ? err.message : '加载偏好设置失败') } finally { setLoading(false) } @@ -66,9 +114,10 @@ export function useUserPreferences() { }, [loadPreferences]) const updateDisplay = async (updates: Partial) => { + const prev = displayConfig const nextDisplay = { ...displayConfig, ...updates } setDisplayConfig(nextDisplay) - + // Update local cache immediately for snappy UI if (typeof window !== 'undefined') { const currentCache = JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}') @@ -76,11 +125,22 @@ export function useUserPreferences() { } if (user?.id) { - await updateUserPreferences(user.id, { display_config: nextDisplay }) + try { + await updateUserPreferences(user.id, { display_config: nextDisplay }) + } catch (err) { + // Rollback on write failure + setDisplayConfig(prev) + if (typeof window !== 'undefined') { + const currentCache = JSON.parse(localStorage.getItem(PREF_CACHE_KEY) || '{}') + localStorage.setItem(PREF_CACHE_KEY, JSON.stringify({ ...currentCache, display_config: prev })) + } + throw err + } } } const updateReminder = async (updates: Partial) => { + const prev = reminderConfig const nextReminder = { ...reminderConfig, ...updates } setReminderConfig(nextReminder) @@ -90,21 +150,37 @@ export function useUserPreferences() { } if (user?.id) { - await updateUserPreferences(user.id, { reminder_config: nextReminder }) + try { + await updateUserPreferences(user.id, { reminder_config: nextReminder }) + } 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 })) + } + throw err + } } } - const togglePrivacyMode = () => { - updateDisplay({ privacy_mode: !displayConfig.privacy_mode }) + const togglePrivacyMode = async () => { + try { + await updateDisplay({ privacy_mode: !displayConfig.privacy_mode }) + } catch (err) { + console.error('Failed to toggle privacy mode:', err) + showToastMessage(err instanceof Error ? err.message : '切换隐私模式失败,已自动回滚') + } } return { displayConfig, reminderConfig, loading, + loadError, updateDisplay, updateReminder, togglePrivacyMode, - refreshPreferences: loadPreferences + refreshPreferences: loadPreferences, } } diff --git a/lib/types.ts b/lib/types.ts index d527a61..9266d48 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -112,15 +112,55 @@ export interface CardHolder { created_at: string } +/** + * 信用账户(多卡统一聚合实体) + */ +export interface CreditAccount { + id: string + holder_id: string + bank_id?: string | null + bank_name: string + currency: string + account_tail?: string | null + statement_mode: 'merged' | 'independent' + quota_mode: 'shared' | 'independent' + shared_credit_limit?: number | null + billing_day?: number | null + due_type?: 'fixed' | 'after_billing' | 'fixed_before_billing' | null + due_value?: number | null + primary_card_id?: string | null + label?: string | null + status: 'active' | 'archived' + created_at: string + updated_at: string +} + +/** + * 账单分卡小计(多卡合并账单中单卡归因) + */ +export interface BillCardSubtotal { + id: string + bill_id: string + card_id?: string | null + card_tail: string + subtotal_amount: number + currency?: string | null + source: 'email' | 'manual' + created_at: string +} + /** * 用户持有的信用卡 */ export interface CreditCard { id: string holder_id: string + account_id?: string | null card_product_id: string card_number_last4?: string credit_limit: number + /** 用户手动设置的信用额度(非空正数表示已手动设置;NULL 且 credit_limit <= 0 表示未获取) */ + credit_limit_override?: number | null billing_day: number status: 'active' | 'frozen' | 'cancelled' /** 卡类型:信用卡 / 贷款类 */ @@ -151,6 +191,7 @@ export interface CreditCard { */ export interface Bill { id: string + account_id?: string | null card_id: string bill_month: string // '2026-03' statement_start?: string @@ -168,6 +209,8 @@ export interface Bill { statement_date_override?: string due_date: string status: 'unpaid' | 'partial' | 'paid' | 'overdue' + /** 多卡合并账单的分卡小计列表(可选) */ + card_subtotals?: BillCardSubtotal[] created_at: string } @@ -247,6 +290,49 @@ export interface EmailParseLog { created_at: string } +/** + * 还款日缺失原因枚举(严禁编造日期,无确切日期时归入以下四类) + */ +export type DueDateMissingReasonCode = + | 'missing_in_email' + | 'parse_failed' + | 'ambiguous_or_grace_only' + | 'unsynced' + +export interface CardDueDateEmailEvidence { + source: 'email_parse_log' | 'gmail_sync' | 'bill_draft' + id: string + subject?: string | null + from_email?: string | null + created_at: string + reason_code: DueDateMissingReasonCode + reason_label: string + detail: string +} + +export interface CardDueDateResolution { + /** 是否存在邮件或账单人工覆盖提供的确切还款日期(YYYY-MM-DD) */ + has_exact_due_date: boolean + /** 确切还款日期(YYYY-MM-DD);无确切日期时为 null,绝不编造 */ + exact_due_date: string | null + /** 确切还款日期来源:账单邮件落库 / 账单人工覆盖 */ + exact_source: 'bill_email' | 'bill_override' | null + /** 对应的账单月份(如 '2026-09') */ + exact_bill_month: string | null + /** 若无确切账单日期,用户是否在卡片上配置了明确的每月固定还款日(1-31) */ + manual_fixed_day: number | null + /** 无确切还款日期时的主原因分类 */ + reason_code: DueDateMissingReasonCode | null + /** 主原因中文标签(邮件未提供 / 解析失败 / 日期模糊/只有宽限期 / 未同步) */ + reason_label: string | null + /** 面向用户展示的一句话原因汇总 */ + summary: string + /** 关联邮件/草稿的原因明细 */ + email_evidences: CardDueDateEmailEvidence[] + /** 四类原因各自的命中邮件数 */ + reason_counts: Record +} + /** * 通用记录附件 metadata。文件保存在 R2 桶 worldcredit-attachments。 */ diff --git a/lib/utils.ts b/lib/utils.ts index 504605c..3dfa35c 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -41,6 +41,37 @@ export function getEffectiveAnnualFee( return null; } +/** + * 返回卡片实际生效的信用额度(正数);未获取时返回 null,绝不把兼容值 0 当作真实额度。 + * + * 优先级:credit_limit_override(正数) > credit_limit(正数) > null(未获取)。 + * credit_cards.credit_limit 在数据库与 iOS 离线库中均为 NOT NULL DEFAULT 0, + * 自动建卡/未填额度时存 0 作为兼容值,展示与计算时必须识别为 null(「未获取」)。 + */ +export function getEffectiveCreditLimit( + card: Pick | undefined | null, +): number | null { + if (!card) return null; + if (card.credit_limit_override != null) { + const over = Number(card.credit_limit_override); + if (Number.isFinite(over) && over > 0) return over; + } + const raw = Number(card.credit_limit); + if (Number.isFinite(raw) && raw > 0) return raw; + return null; +} + +/** + * 卡片信用额度是否已由用户手动设置(持久化在 credit_limit_override)。 + */ +export function isCreditLimitManuallySet( + card: Pick | undefined | null, +): boolean { + if (!card || card.credit_limit_override == null) return false; + const over = Number(card.credit_limit_override); + return Number.isFinite(over) && over > 0; +} + /** * 返回实际生效的还款规则(优先使用卡级别 override,否则用卡产品默认) */ @@ -304,6 +335,73 @@ export function billEffectiveStatementDate(bill: { return bill.statement_date_override ?? bill.statement_date ?? null; } +/** + * 判定账单是否未出账(日历日口径): + * 出账日(优先生效出账日,兜底 statement_end)在今天之后(diffInCalendarDays > 0)即为未出账。 + * 当天出账(diffInCalendarDays === 0)算已出账。 + * 未出账前绝无逾期概念。 + */ +export function isBillUnissued( + bill: { + statement_date?: string | null; + statement_date_override?: string | null; + statement_end?: string | null; + }, + today: Date = new Date(), +): boolean { + const stmtDate = billEffectiveStatementDate(bill) || bill.statement_end; + if (!stmtDate) return false; + return diffInCalendarDays(stmtDate, today) > 0; +} + +/** + * 计算卡片今日刷卡的免息期与关键日期(今日交易动态口径) + * 今天交易 → 进下一期账单 → 到该期还款日的天数 + */ +export function calculateCardGracePeriod( + card: CreditCard & { card_product: CardProduct }, + today: Date = new Date(), +) { + const d = new Date(today); + d.setHours(0, 0, 0, 0); + const billingDay = Number(card.override_billing_day ?? card.billing_day ?? 10); + if (card.card_type === "loan" && card.loan_due_day) { + const nextDueDate = getLoanNextDueDate(card.loan_due_day, d); + const diffMs = nextDueDate.getTime() - d.getTime(); + return { + billingDay, + nextBillingDate: nextDueDate, + nextDueDate, + graceDays: Math.max(1, Math.ceil(diffMs / (24 * 60 * 60 * 1000))), + }; + } + let purchaseMonth = new Date(d.getFullYear(), d.getMonth(), 1); + const effectiveBillingDay = Math.min( + billingDay, + new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate(), + ); + // 账单日次日起的交易归下一期:账单日当天刷卡当天出账(多数国内行 + // 口径),当天交易进当期账单、免息最短;账单日后一天刷卡才是最长 + // 免息的第一天(今天 == 账单日 → purchaseMonth 留在本月,当期出账 + // 最早、免息天数最小;今天 == 账单日+1 → 归下一期,免息期最长)。 + if (d.getDate() > effectiveBillingDay) { + purchaseMonth = new Date(d.getFullYear(), d.getMonth() + 1, 1); + } + const nextBillingDate = new Date( + purchaseMonth.getFullYear(), + purchaseMonth.getMonth(), + effectiveBillingDay, + ); + const nextDueDate = getDueDate(card, card.card_product, purchaseMonth); + const diffMs = nextDueDate.getTime() - d.getTime(); + return { + billingDay, + nextBillingDate, + nextDueDate, + graceDays: Math.max(1, Math.ceil(diffMs / (24 * 60 * 60 * 1000))), + }; +} + // 账单日临近判定:距下一次账单日不足 days 天(含当天)时允许手填金额。 // 用账单日而非到期日——出账前金额还是空的,正是需要用户先记一笔的时候。 export function canManuallySetBillAmount( @@ -315,31 +413,169 @@ export function canManuallySetBillAmount( return remaining >= 0 && remaining < days; } -// ── 周期性固定支出(房租 / 贷款 / 其他按月应付) ──────────────────────────── +// ── 周期性固定支出(房租 / 贷款 / 其他周期应付) ──────────────────────────── + +export interface PayableCycleConfig { + cycle_type?: "monthly" | "every_n_months" | "yearly" | null; + cycle_months?: number | null; + due_month?: number | null; + due_day?: number | null; + anchor_period?: string | null; + created_at?: string | null; +} + +function formatPayableYearMonth(year: number, month1Based: number): string { + return `${year}-${String(month1Based).padStart(2, "0")}`; +} + +function parsePayableYearMonth(period: string | null | undefined): { year: number; month: number } | null { + if (typeof period !== "string") return null; + const m = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(period.trim()); + if (!m) return null; + const year = Number(m[1]); + const month = Number(m[2]); + if (year < 1970 || year > 2100) return null; + return { year, month }; +} + +/** 账期按月平移(months 可正可负),返回 'YYYY-MM'。 */ +export function addMonthsToPayablePeriod(period: string, months: number): string { + const parsed = parsePayableYearMonth(period); + if (!parsed) { + const [year, month] = period.split("-").map(Number); + const next = addMonths(new Date(year, month - 1, 1), months); + return formatPayableYearMonth(next.getFullYear(), next.getMonth() + 1); + } + const totalMonths = parsed.year * 12 + (parsed.month - 1) + months; + const nextYear = Math.floor(totalMonths / 12); + const nextMonth = (((totalMonths % 12) + 12) % 12) + 1; + return formatPayableYearMonth(nextYear, nextMonth); +} /** * 某个应付事项在 today 所处的账期('YYYY-MM')。 * - * 账期按「应付日所在的那个月」定义,不做「过了应付日就算下期」的滚动: - * 房租 15 号到期,16 号仍然属于本月账期(只是已逾期),下个月才换期。 - * 这样逾期才表达得出来——滚动口径会把「本月该付没付」直接抹掉。 + * - monthly(默认):按 today 所在月,不做「过了应付日就算下期」的滚动,保留逾期表达; + * - every_n_months:从起算账期 anchor_period 起每 X 个月一档,落在当前档位内直到下一档开始; + * - yearly:按每年 due_month 所在月(12 个月一档),未到达首个 anchor_period 前钳制在首期。 */ -export function payablePeriodOf(today: Date = new Date()): string { - return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}`; +export function payablePeriodOf(today: Date = new Date(), cycle?: PayableCycleConfig): string { + const todayYear = today.getFullYear(); + const todayMonth = today.getMonth() + 1; + const rawTodayPeriod = formatPayableYearMonth(todayYear, todayMonth); + + if (!cycle || !cycle.cycle_type || cycle.cycle_type === "monthly") { + return rawTodayPeriod; + } + + if (cycle.cycle_type === "yearly") { + const parsedAnchor = parsePayableYearMonth(cycle.anchor_period); + const dueMonth = + typeof cycle.due_month === "number" && + Number.isInteger(cycle.due_month) && + cycle.due_month >= 1 && + cycle.due_month <= 12 + ? cycle.due_month + : parsedAnchor + ? parsedAnchor.month + : todayMonth; + + let anchorYear = todayYear; + if (parsedAnchor && parsedAnchor.month === dueMonth) { + anchorYear = parsedAnchor.year; + } else if (typeof cycle.created_at === "string" && cycle.created_at.trim()) { + const createdDate = new Date(cycle.created_at); + if (!Number.isNaN(createdDate.getTime())) { + const createdYear = createdDate.getFullYear(); + const dueDay = + typeof cycle.due_day === "number" && cycle.due_day >= 1 && cycle.due_day <= 31 + ? cycle.due_day + : 1; + const candidateDue = payableDueDate(dueDay, formatPayableYearMonth(createdYear, dueMonth)); + anchorYear = diffInCalendarDays(candidateDue, createdDate) >= 0 ? createdYear : createdYear + 1; + } + } + + const anchorPeriod = formatPayableYearMonth(anchorYear, dueMonth); + const diffMonths = (todayYear - anchorYear) * 12 + (todayMonth - dueMonth); + if (diffMonths < 0) return anchorPeriod; + const cyclesElapsed = Math.floor(diffMonths / 12); + return formatPayableYearMonth(anchorYear + cyclesElapsed, dueMonth); + } + + // every_n_months + const step = + typeof cycle.cycle_months === "number" && + Number.isInteger(cycle.cycle_months) && + cycle.cycle_months >= 2 + ? cycle.cycle_months + : 1; + if (step <= 1) return rawTodayPeriod; + + let anchor = parsePayableYearMonth(cycle.anchor_period); + if (!anchor && typeof cycle.created_at === "string") { + const createdDate = new Date(cycle.created_at); + if (!Number.isNaN(createdDate.getTime())) { + anchor = { year: createdDate.getFullYear(), month: createdDate.getMonth() + 1 }; + } + } + if (!anchor) { + anchor = { year: todayYear, month: todayMonth }; + } + + const anchorStr = formatPayableYearMonth(anchor.year, anchor.month); + const diffMonths = (todayYear - anchor.year) * 12 + (todayMonth - anchor.month); + if (diffMonths < 0) return anchorStr; + const cyclesElapsed = Math.floor(diffMonths / step); + return addMonthsToPayablePeriod(anchorStr, cyclesElapsed * step); } -/** 某账期内该应付事项的到期日(处理 due_day > 当月天数,如 31 日)。 */ +/** 某账期内该应付事项的到期日(处理 due_day > 当月天数,如 31 日或平年 2 月 29 日)。 */ export function payableDueDate(dueDay: number, period: string): Date { const [year, month] = period.split("-").map(Number); const monthDate = new Date(year, month - 1, 1); return getActualBillingDate(dueDay, monthDate); } -/** 当前账期的下一期('YYYY-MM'):本期已结清后用它指向下期应付日。 */ -export function nextPayablePeriodOf(period: string): string { - const [year, month] = period.split("-").map(Number); - const next = addMonths(new Date(year, month - 1, 1), 1); - return `${next.getFullYear()}-${String(next.getMonth() + 1).padStart(2, "0")}`; +/** 当前账期的下一期('YYYY-MM'):每月 +1 月,每 X 月 +X 月,每年同月(年份 +1)。 */ +export function nextPayablePeriodOf(period: string, cycle?: PayableCycleConfig): string { + if (!cycle || !cycle.cycle_type || cycle.cycle_type === "monthly") { + return addMonthsToPayablePeriod(period, 1); + } + if (cycle.cycle_type === "yearly") { + const parsed = parsePayableYearMonth(period); + const baseYear = parsed ? parsed.year : Number(period.split("-")[0]); + const fallbackMonth = parsed ? parsed.month : Number(period.split("-")[1]); + const month = + typeof cycle.due_month === "number" && + Number.isInteger(cycle.due_month) && + cycle.due_month >= 1 && + cycle.due_month <= 12 + ? cycle.due_month + : fallbackMonth; + return formatPayableYearMonth(baseYear + 1, month); + } + const step = + typeof cycle.cycle_months === "number" && + Number.isInteger(cycle.cycle_months) && + cycle.cycle_months >= 2 + ? cycle.cycle_months + : 1; + return addMonthsToPayablePeriod(period, step); +} + +/** + * 推导下一期到期日: + * - monthly:下月同日(月末收拢); + * - every_n_months:间隔 X 个月后的同日(月末收拢); + * - yearly:次年同月同日(如闰年 02-29 → 平年 02-28,遇闰年恢复 02-29)。 + */ +export function nextPayableDueDate( + dueDay: number, + period: string, + cycle?: PayableCycleConfig, +): Date { + return payableDueDate(dueDay, nextPayablePeriodOf(period, cycle)); } /** @@ -364,13 +600,25 @@ export function cardUrgencyRank(status: CardUrgencyStatus): number { * * 为什么不用毫秒差:'2026-09-16' 这种无时区的日期串按 UTC 解析,在东八区会 * 落回本地当天 08:00。直接用 (target - now) / 86400000 再取整,在跨日边界会 - * 差一天——用户看到「距离还款日 2 日」而徽章写着「逾期」。所以先把两侧都归一到 - * 本地零点再相减。 + * 差一天——用户看到「距离还款日 2 日」而徽章写着「逾期」。 + * + * 为什么用固定业务时区而不是进程本地时区:生产跑在 Cloudflare Workers(UTC)、 + * CI 也是 UTC,用户却在中国。若按进程时区取「今天」,UTC 下东八区凌晨 + * 00:00-08:00 会比用户日历日早一天,出账日当天被误判为「未出账」。因此两侧 + * 都归一到 Asia/Shanghai 的日历日(与 getLocalTodayString 同口径)再相减, + * 行为在任何运行时区下一致。date-only 字符串(YYYY-MM-DD)本身就是日历日, + * 直接透传不经过时区换算。 */ export function diffInCalendarDays(target: string | Date, today: Date = new Date()): number { - const t = typeof target === "string" ? new Date(target) : target; - const localMidnight = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime(); - return Math.round((localMidnight(t) - localMidnight(today)) / 86_400_000); + const BUSINESS_TIME_ZONE = "Asia/Shanghai"; + const calendarDay = (input: string | Date): string => { + if (typeof input === "string" && /^\d{4}-\d{2}-\d{2}$/.test(input)) return input; + return getLocalTodayString(BUSINESS_TIME_ZONE, input as Date); + }; + const targetDay = calendarDay(target); + const todayDay = calendarDay(today); + // 两串都是 YYYY-MM-DD,Date.parse 一律按 UTC 零点解析,差值恒为整日。 + return Math.round((Date.parse(targetDay) - Date.parse(todayDay)) / 86_400_000); } /** @@ -522,6 +770,7 @@ export function payableNextCycleStatus( period: string, today: Date = new Date(), statementLeadDays = 30, + cycle?: PayableCycleConfig, ): { phase: "awaiting_statement" | "awaiting_payment"; /** awaiting_statement → 出账日;awaiting_payment → 还款日 */ @@ -529,8 +778,8 @@ export function payableNextCycleStatus( /** 距该日期的天数 */ days: number; } { - // 下期还款日按「due_day + 下期账期」算(月末收拢:31 日 → 下月最后一天) - const due = payableDueDate(dueDay, nextPayablePeriodOf(period)); + // 下期还款日按「due_day + 下期账期(含周期步长/每年同月)」算(月末收拢) + const due = payableDueDate(dueDay, nextPayablePeriodOf(period, cycle)); const days = diffInCalendarDays(due, today); if (days >= statementLeadDays) { const statementDate = addDays(due, -statementLeadDays); @@ -599,15 +848,21 @@ export function payableToSortCard( due_date: string; days_until_due: number; due_day: number; + period?: string; + cycle_type?: "monthly" | "every_n_months" | "yearly" | null; + cycle_months?: number | null; + due_month?: number | null; + anchor_period?: string | null; }, _today: Date = new Date(), ): BillsListCard & { payableSource: true } { const status: CardUrgencyStatus = payable.status === "paid" ? "unissued" : payable.status; // 下期应付日按「due_day + 下期账期」重算,而不是 due_date 顺延一个月: // setMonth 在 10-31 这类日期会溢出成 12-01,收拢口径要求落在 11-30。 + const currentPeriod = payable.period ?? payable.due_date.slice(0, 7); const nextDue = payableDueDate( payable.due_day, - nextPayablePeriodOf(payable.due_date.slice(0, 7)), + nextPayablePeriodOf(currentPeriod, payable), ); return { status, diff --git a/migrations/d1/0029_credit_limit_override.sql b/migrations/d1/0029_credit_limit_override.sql new file mode 100644 index 0000000..830b90f --- /dev/null +++ b/migrations/d1/0029_credit_limit_override.sql @@ -0,0 +1,9 @@ +-- 0029: Add card-level credit_limit_override column. +-- +-- credit_cards.credit_limit keeps REAL NOT NULL DEFAULT 0 for schema / iOS GRDB +-- compatibility (0 without override = "未获取"). When a user manually inputs a +-- credit limit, both credit_limit and credit_limit_override are persisted so +-- the UI can reliably distinguish manual "已设置" from unacquired 0 and email +-- sync will never overwrite user-entered limits. + +ALTER TABLE credit_cards ADD COLUMN credit_limit_override REAL; diff --git a/migrations/d1/0030_payable_cycles_and_custom_categories.sql b/migrations/d1/0030_payable_cycles_and_custom_categories.sql new file mode 100644 index 0000000..f7855ad --- /dev/null +++ b/migrations/d1/0030_payable_cycles_and_custom_categories.sql @@ -0,0 +1,56 @@ +-- 0030:固定支出支持多周期(每月 / 每 X 月 / 每年)与自定义分类持久化。 +-- +-- 兼容性约束: +-- 1. 旧记录默认 cycle_type = 'monthly'、cycle_months = 1,due_month / anchor_period / custom_category 为 NULL,行为不变; +-- 2. recurring_payables.category 保持原有 5 个枚举值(自定义分类写 category = 'other' + custom_category = '<名称>'), +-- 不破坏 0009 的 CHECK 约束,也不破坏旧版 iOS PayableCategory 强类型解码; +-- 3. 新增列随 sync/pull 的 SELECT t.* 下发,旧客户端忽略未知字段不崩。 + +ALTER TABLE recurring_payables + ADD COLUMN cycle_type TEXT NOT NULL DEFAULT 'monthly' + CHECK (cycle_type IN ('monthly', 'every_n_months', 'yearly')); + +ALTER TABLE recurring_payables + ADD COLUMN cycle_months INTEGER NOT NULL DEFAULT 1 + CHECK (cycle_months BETWEEN 1 AND 60); + +ALTER TABLE recurring_payables + ADD COLUMN due_month INTEGER + CHECK (due_month IS NULL OR (due_month BETWEEN 1 AND 12)); + +ALTER TABLE recurring_payables + ADD COLUMN anchor_period TEXT; + +ALTER TABLE recurring_payables + ADD COLUMN custom_category TEXT; + +-- 用户级自定义分类词典:按 normalized_name 去重持久化,删除单笔固定支出后下次仍可选用。 +CREATE TABLE IF NOT EXISTS payable_custom_categories ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + normalized_name TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + UNIQUE(user_id, normalized_name) +); + +CREATE INDEX IF NOT EXISTS idx_payable_custom_categories_user + ON payable_custom_categories(user_id, created_at ASC); + +CREATE TRIGGER IF NOT EXISTS trg_payable_custom_categories_insert +AFTER INSERT ON payable_custom_categories BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + VALUES (NEW.user_id, 'payable_custom_categories', NEW.id, 'upsert'); +END; + +CREATE TRIGGER IF NOT EXISTS trg_payable_custom_categories_update +AFTER UPDATE ON payable_custom_categories BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + VALUES (NEW.user_id, 'payable_custom_categories', NEW.id, 'upsert'); +END; + +CREATE TRIGGER IF NOT EXISTS trg_payable_custom_categories_delete +AFTER DELETE ON payable_custom_categories BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + VALUES (OLD.user_id, 'payable_custom_categories', OLD.id, 'delete'); +END; diff --git a/migrations/d1/0031_default_bank_card_products.sql b/migrations/d1/0031_default_bank_card_products.sql new file mode 100644 index 0000000..dc2461a --- /dev/null +++ b/migrations/d1/0031_default_bank_card_products.sql @@ -0,0 +1,40 @@ +-- 0031: 补齐银行兜底基础卡产品 + 存量 override_billing_day 归一合并 +-- +-- 1. 补齐兜底基础卡产品: +-- 对尚未拥有 CNY 基础信用卡产品的银行,幂等补充 id = 'cp_default_' || banks.id 的标准卡产品, +-- 确保每家银行均可直接用于建卡与选卡,并通过 0019 触发器自动同步下发 iOS。 + +INSERT OR IGNORE INTO card_products ( + id, + country, + bank_id, + bank_name, + card_name, + currency, + payment_due_type, + payment_due_value, + annual_fee, + is_active +) +SELECT + 'cp_default_' || b.id, + b.country, + b.id, + b.name, + '标准信用卡', + 'CNY', + 'after_billing', + 20, + 0, + 1 +FROM banks b +WHERE NOT EXISTS ( + SELECT 1 FROM card_products cp + WHERE cp.bank_id = b.id AND cp.currency = 'CNY' AND cp.is_active = 1 +); + +-- 2. 存量 override_billing_day 一次性合并回 billing_day 并清空,消除双列歧义 +UPDATE credit_cards +SET billing_day = override_billing_day, + override_billing_day = NULL +WHERE override_billing_day IS NOT NULL; diff --git a/migrations/d1/0032_unified_credit_accounts.sql b/migrations/d1/0032_unified_credit_accounts.sql new file mode 100644 index 0000000..2085523 --- /dev/null +++ b/migrations/d1/0032_unified_credit_accounts.sql @@ -0,0 +1,316 @@ +-- 0032: 多卡统一信用账户模型与保守回填 (E5 Phase 1+2) +-- +-- 1. 新建 credit_accounts(信用账户表)与 bill_card_subtotals(账单分卡小计表) +-- 2. credit_cards 挂载 account_id,bills 挂载 account_id 与 UNIQUE(account_id, bill_month) +-- 3. bills.card_id 维持 NOT NULL 锚点卡语义(零破坏既有 5 张外键子表与 9 个同步/防超还触发器) +-- 4. 四家常用合并出账银行(招商、民生、上海、北京)预设 statement_mode='merged', quota_mode='shared' +-- 5. 存量卡片保守回填:同月碰撞绝不合并/不删改,不同持卡人(如民生 0872 与 9765)绝不跨人合并 +-- 6. 注册 credit_accounts 与 bill_card_subtotals 的 sync_changes 增量同步触发器 + +-- ============================================ +-- 1. 新增表结构 +-- ============================================ + +CREATE TABLE IF NOT EXISTS credit_accounts ( + id TEXT PRIMARY KEY, + holder_id TEXT NOT NULL REFERENCES card_holders(id) ON DELETE CASCADE, + bank_id TEXT REFERENCES banks(id) ON DELETE SET NULL, + bank_name TEXT NOT NULL, + currency TEXT NOT NULL DEFAULT 'CNY', + account_tail TEXT, + statement_mode TEXT NOT NULL DEFAULT 'independent' CHECK (statement_mode IN ('merged', 'independent')), + quota_mode TEXT NOT NULL DEFAULT 'independent' CHECK (quota_mode IN ('shared', 'independent')), + shared_credit_limit REAL, + billing_day INTEGER CHECK (billing_day IS NULL OR (billing_day >= 1 AND billing_day <= 31)), + due_type TEXT DEFAULT 'after_billing' CHECK (due_type IS NULL OR due_type IN ('fixed', 'after_billing', 'fixed_before_billing')), + due_value INTEGER DEFAULT 20, + primary_card_id TEXT REFERENCES credit_cards(id) ON DELETE SET NULL, + label TEXT, + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'archived')), + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) +); + +CREATE INDEX IF NOT EXISTS idx_credit_accounts_holder_bank + ON credit_accounts(holder_id, bank_id, bank_name, currency); +CREATE INDEX IF NOT EXISTS idx_credit_accounts_primary_card + ON credit_accounts(primary_card_id); + +CREATE TABLE IF NOT EXISTS bill_card_subtotals ( + id TEXT PRIMARY KEY, + bill_id TEXT NOT NULL REFERENCES bills(id) ON DELETE CASCADE, + card_id TEXT REFERENCES credit_cards(id) ON DELETE SET NULL, + card_tail TEXT NOT NULL, + subtotal_amount REAL NOT NULL, + currency TEXT DEFAULT 'CNY', + source TEXT DEFAULT 'email' CHECK (source IN ('email', 'manual')), + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + UNIQUE(bill_id, card_tail) +); + +CREATE INDEX IF NOT EXISTS idx_bill_card_subtotals_bill ON bill_card_subtotals(bill_id); +CREATE INDEX IF NOT EXISTS idx_bill_card_subtotals_card ON bill_card_subtotals(card_id); + +-- ============================================ +-- 2. 扩展已有表字段 +-- ============================================ + +ALTER TABLE credit_cards ADD COLUMN account_id TEXT REFERENCES credit_accounts(id) ON DELETE SET NULL; +CREATE INDEX IF NOT EXISTS idx_credit_cards_account ON credit_cards(account_id); + +ALTER TABLE bills ADD COLUMN account_id TEXT REFERENCES credit_accounts(id) ON DELETE RESTRICT; +CREATE INDEX IF NOT EXISTS idx_bills_account ON bills(account_id); + +ALTER TABLE bill_items ADD COLUMN card_id TEXT REFERENCES credit_cards(id) ON DELETE SET NULL; +ALTER TABLE bill_items ADD COLUMN card_tail TEXT; +CREATE INDEX IF NOT EXISTS idx_bill_items_card ON bill_items(card_id); + +ALTER TABLE bill_import_drafts ADD COLUMN matched_account_id TEXT REFERENCES credit_accounts(id) ON DELETE SET NULL; +ALTER TABLE bill_import_drafts ADD COLUMN card_subtotals_json TEXT; + +-- ============================================ +-- 3. 预设首批四家合并账单银行 +-- ============================================ + +UPDATE banks +SET statement_mode = 'merged', quota_mode = 'shared' +WHERE name IN ('招商银行', '中国民生银行', '民生银行', '上海银行', '北京银行') + OR name LIKE '%招商%' + OR name LIKE '%民生%' + OR name LIKE '%上海银行%' + OR name LIKE '%北京银行%'; + +-- ============================================ +-- 4. 存量卡片与账单保守回填 (Backfill) +-- ============================================ + +-- 4.1 回填无同月账单碰撞的合并账户 (statement_mode='merged') +WITH candidate_cards AS ( + SELECT + cc.id AS card_id, + cc.holder_id, + COALESCE(cp.bank_id, cp.bank_name, 'UNKNOWN') AS bank_key, + cp.bank_id, + COALESCE(cp.bank_name, '未知银行') AS bank_name, + COALESCE(cp.currency, 'CNY') AS currency, + cc.billing_day, + COALESCE(cc.credit_limit_override, cc.credit_limit, 0) AS effective_credit_limit, + cc.status AS card_status, + COALESCE(cc.override_due_type, cp.payment_due_type, 'after_billing') AS due_type, + COALESCE(cc.override_due_value, cp.payment_due_value, 20) AS due_value, + cc.created_at, + (SELECT COUNT(*) FROM bills bi WHERE bi.card_id = cc.id) AS bill_count + FROM credit_cards cc + LEFT JOIN card_products cp ON cc.card_product_id = cp.id + LEFT JOIN banks b ON cp.bank_id = b.id + WHERE cc.account_id IS NULL + AND cc.card_type != 'loan' + AND (cc.account_mode_override IS NULL OR cc.account_mode_override != 'single') + AND ( + COALESCE(b.statement_mode, 'independent') = 'merged' + OR COALESCE(cp.bank_name, '') LIKE '%招商%' + OR COALESCE(cp.bank_name, '') LIKE '%民生%' + OR COALESCE(cp.bank_name, '') LIKE '%上海银行%' + OR COALESCE(cp.bank_name, '') LIKE '%北京银行%' + OR cc.account_mode_override = 'multi' + ) +), +group_collision AS ( + SELECT c1.holder_id, c1.bank_key, c1.currency + FROM bills b1 + JOIN bills b2 ON b1.bill_month = b2.bill_month AND b1.card_id != b2.card_id + JOIN candidate_cards c1 ON b1.card_id = c1.card_id + JOIN candidate_cards c2 ON b2.card_id = c2.card_id + WHERE c1.holder_id = c2.holder_id + AND c1.bank_key = c2.bank_key + AND c1.currency = c2.currency + GROUP BY c1.holder_id, c1.bank_key, c1.currency +), +valid_merged_cards AS ( + SELECT c.* + FROM candidate_cards c + WHERE NOT EXISTS ( + SELECT 1 FROM group_collision gc + WHERE gc.holder_id = c.holder_id + AND gc.bank_key = c.bank_key + AND gc.currency = c.currency + ) +), +ranked_merged_cards AS ( + SELECT v.*, + ROW_NUMBER() OVER ( + PARTITION BY v.holder_id, v.bank_key, v.currency + ORDER BY (CASE WHEN v.card_status = 'active' THEN 0 ELSE 1 END), v.bill_count DESC, v.created_at ASC + ) AS rk, + MAX(v.effective_credit_limit) OVER ( + PARTITION BY v.holder_id, v.bank_key, v.currency + ) AS pool_limit + FROM valid_merged_cards v +) +INSERT OR IGNORE INTO credit_accounts ( + id, holder_id, bank_id, bank_name, currency, statement_mode, quota_mode, shared_credit_limit, + billing_day, due_type, due_value, primary_card_id, status +) +SELECT + 'acc_m_' || card_id, + holder_id, bank_id, bank_name, currency, 'merged', 'shared', pool_limit, + billing_day, due_type, due_value, card_id, 'active' +FROM ranked_merged_cards +WHERE rk = 1; + +-- 4.2 更新合并账户卡片的 account_id +WITH candidate_cards AS ( + SELECT + cc.id AS card_id, + cc.holder_id, + COALESCE(cp.bank_id, cp.bank_name, 'UNKNOWN') AS bank_key, + COALESCE(cp.currency, 'CNY') AS currency, + cc.status AS card_status, + cc.created_at, + (SELECT COUNT(*) FROM bills bi WHERE bi.card_id = cc.id) AS bill_count + FROM credit_cards cc + LEFT JOIN card_products cp ON cc.card_product_id = cp.id + LEFT JOIN banks b ON cp.bank_id = b.id + WHERE cc.account_id IS NULL + AND cc.card_type != 'loan' + AND (cc.account_mode_override IS NULL OR cc.account_mode_override != 'single') + AND ( + COALESCE(b.statement_mode, 'independent') = 'merged' + OR COALESCE(cp.bank_name, '') LIKE '%招商%' + OR COALESCE(cp.bank_name, '') LIKE '%民生%' + OR COALESCE(cp.bank_name, '') LIKE '%上海银行%' + OR COALESCE(cp.bank_name, '') LIKE '%北京银行%' + OR cc.account_mode_override = 'multi' + ) +), +group_collision AS ( + SELECT c1.holder_id, c1.bank_key, c1.currency + FROM bills b1 + JOIN bills b2 ON b1.bill_month = b2.bill_month AND b1.card_id != b2.card_id + JOIN candidate_cards c1 ON b1.card_id = c1.card_id + JOIN candidate_cards c2 ON b2.card_id = c2.card_id + WHERE c1.holder_id = c2.holder_id AND c1.bank_key = c2.bank_key AND c1.currency = c2.currency + GROUP BY c1.holder_id, c1.bank_key, c1.currency +), +valid_merged_cards AS ( + SELECT c.* + FROM candidate_cards c + WHERE NOT EXISTS ( + SELECT 1 FROM group_collision gc + WHERE gc.holder_id = c.holder_id AND gc.bank_key = c.bank_key AND gc.currency = c.currency + ) +), +primary_map AS ( + SELECT v.card_id, + FIRST_VALUE('acc_m_' || v.card_id) OVER ( + PARTITION BY v.holder_id, v.bank_key, v.currency + ORDER BY (CASE WHEN v.card_status = 'active' THEN 0 ELSE 1 END), v.bill_count DESC, v.created_at ASC + ) AS target_account_id + FROM valid_merged_cards v +) +UPDATE credit_cards +SET account_id = (SELECT target_account_id FROM primary_map WHERE primary_map.card_id = credit_cards.id) +WHERE id IN (SELECT card_id FROM primary_map); + +-- 4.3 剩余卡片(独立出账卡、贷款卡、明确单卡覆盖、以及发生同月碰撞的卡组)各自生成独立账户 +INSERT OR IGNORE INTO credit_accounts ( + id, holder_id, bank_id, bank_name, currency, statement_mode, quota_mode, shared_credit_limit, + billing_day, due_type, due_value, primary_card_id, status +) +SELECT + 'acc_i_' || cc.id, + cc.holder_id, + cp.bank_id, + COALESCE(cp.bank_name, '未知银行'), + COALESCE(cp.currency, 'CNY'), + 'independent', + COALESCE(b.quota_mode, 'independent'), + NULL, + cc.billing_day, + COALESCE(cc.override_due_type, cp.payment_due_type, 'after_billing'), + COALESCE(cc.override_due_value, cp.payment_due_value, 20), + cc.id, + 'active' +FROM credit_cards cc +LEFT JOIN card_products cp ON cc.card_product_id = cp.id +LEFT JOIN banks b ON cp.bank_id = b.id +WHERE cc.account_id IS NULL; + +UPDATE credit_cards +SET account_id = 'acc_i_' || id +WHERE account_id IS NULL; + +-- 4.4 回填历史 bills.account_id 并对齐合并账户的 bills.card_id(锚点卡语义) +UPDATE bills +SET account_id = (SELECT account_id FROM credit_cards WHERE credit_cards.id = bills.card_id) +WHERE account_id IS NULL; + +UPDATE bills +SET card_id = (SELECT primary_card_id FROM credit_accounts ca WHERE ca.id = bills.account_id) +WHERE bills.account_id IN (SELECT id FROM credit_accounts WHERE statement_mode = 'merged'); + +-- 4.5 建立唯一索引:每信用账户每出账月最多 1 条权威账单 +CREATE UNIQUE INDEX IF NOT EXISTS idx_bills_account_month + ON bills(account_id, bill_month) + WHERE account_id IS NOT NULL; + +-- ============================================ +-- 5. 离线同步 (sync_changes) 触发器 +-- ============================================ + +-- credit_accounts +CREATE TRIGGER IF NOT EXISTS trg_credit_accounts_insert AFTER INSERT ON credit_accounts BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + SELECT ch.managed_by, 'credit_accounts', NEW.id, 'upsert' + FROM card_holders ch WHERE ch.id = NEW.holder_id; +END; + +CREATE TRIGGER IF NOT EXISTS trg_credit_accounts_update AFTER UPDATE ON credit_accounts BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + SELECT ch.managed_by, 'credit_accounts', NEW.id, 'upsert' + FROM card_holders ch WHERE ch.id = NEW.holder_id; +END; + +CREATE TRIGGER IF NOT EXISTS trg_credit_accounts_delete AFTER DELETE ON credit_accounts BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + SELECT ch.managed_by, 'credit_accounts', OLD.id, 'delete' + FROM card_holders ch WHERE ch.id = OLD.holder_id; +END; + +-- bill_card_subtotals +CREATE TRIGGER IF NOT EXISTS trg_bill_card_subtotals_insert AFTER INSERT ON bill_card_subtotals BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + SELECT ch.managed_by, 'bill_card_subtotals', NEW.id, 'upsert' + FROM bills b + JOIN credit_cards cc ON cc.id = b.card_id + JOIN card_holders ch ON ch.id = cc.holder_id + WHERE b.id = NEW.bill_id; +END; + +CREATE TRIGGER IF NOT EXISTS trg_bill_card_subtotals_update AFTER UPDATE ON bill_card_subtotals BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + SELECT ch.managed_by, 'bill_card_subtotals', NEW.id, 'upsert' + FROM bills b + JOIN credit_cards cc ON cc.id = b.card_id + JOIN card_holders ch ON ch.id = cc.holder_id + WHERE b.id = NEW.bill_id; +END; + +CREATE TRIGGER IF NOT EXISTS trg_bill_card_subtotals_delete AFTER DELETE ON bill_card_subtotals BEGIN + INSERT INTO sync_changes (owner_id, tbl, row_id, op) + SELECT ch.managed_by, 'bill_card_subtotals', OLD.id, 'delete' + FROM bills b + JOIN credit_cards cc ON cc.id = b.card_id + JOIN card_holders ch ON ch.id = cc.holder_id + WHERE b.id = OLD.bill_id; +END; + +-- 将存量回填生成的 credit_accounts 写入 sync_changes +INSERT INTO sync_changes (owner_id, tbl, row_id, op) +SELECT ch.managed_by, 'credit_accounts', ca.id, 'upsert' +FROM credit_accounts ca +JOIN card_holders ch ON ch.id = ca.holder_id +WHERE NOT EXISTS ( + SELECT 1 FROM sync_changes sc + WHERE sc.tbl = 'credit_accounts' AND sc.row_id = ca.id +); diff --git a/scripts/due-date-summary.ts b/scripts/due-date-summary.ts new file mode 100644 index 0000000..bfc6b75 --- /dev/null +++ b/scripts/due-date-summary.ts @@ -0,0 +1,201 @@ +#!/usr/bin/env tsx +/** + * 还款日确切性与四类缺失原因汇总脚本。 + * + * 铁律: + * 1. 邮件/账单中有确切日期(YYYY-MM-DD)才认定为有还款日; + * 2. 无确切日期严格归入四类原因: + * - missing_in_email(邮件未提供) + * - parse_failed(解析失败) + * - ambiguous_or_grace_only(日期模糊/只有宽限期) + * - unsynced(未同步) + * 3. 绝不编造日期、绝不伪造生产统计。在缺乏生产 D1 直连权限时标明 NOT RUN。 + * + * 用法: + * # 本地演练 / 逻辑自测 + * npx tsx scripts/due-date-summary.ts --mock + * + * # 生产环境运行(通过 wrangler 注入 D1 或在 worker 环境调用) + * npx tsx scripts/due-date-summary.ts + */ + +import { buildDueDateReasonReport, DUE_DATE_ISSUE_LABELS } from '../lib/due-date-summary' +import type { + CardForDueDateSummary, + BillForDueDateSummary, + GmailSyncMessageLite, + BillImportDraftLite, +} from '../lib/due-date-summary' +import type { EmailParseLog } from '../lib/types' + +function printReport(title: string, report: ReturnType) { + console.log(`\n======================================================`) + console.log(` ${title}`) + console.log(`======================================================`) + console.log(`卡片总数: ${report.cards_total}`) + console.log(`具备确切还款日: ${report.cards_with_exact_due_date}`) + console.log(`未获取确切还款日: ${report.cards_missing_exact_due_date}`) + console.log(`\n【四类缺失原因分布】`) + console.log(` 1. ${DUE_DATE_ISSUE_LABELS.missing_in_email} (missing_in_email): ${report.by_reason.missing_in_email}`) + console.log(` 2. ${DUE_DATE_ISSUE_LABELS.parse_failed} (parse_failed): ${report.by_reason.parse_failed}`) + console.log(` 3. ${DUE_DATE_ISSUE_LABELS.ambiguous_or_grace_only} (ambiguous_or_grace_only): ${report.by_reason.ambiguous_or_grace_only}`) + console.log(` 4. ${DUE_DATE_ISSUE_LABELS.unsynced} (unsynced): ${report.by_reason.unsynced}`) + + console.log(`\n【卡片明细】`) + for (const c of report.cards) { + const res = c.resolution + const status = res.has_exact_due_date + ? `✅ 确切还款日: ${res.exact_due_date} (${res.exact_source === 'bill_override' ? '人工确认' : '账单邮件'})` + : `⚠️ 未获取: [${res.reason_label}] ${res.summary}` + console.log(`- [${c.bank_name || '卡片'} *${c.card_last4 || '----'}] ${c.card_name}: ${status}`) + } + + if (report.unmatched_email_issues.length > 0) { + console.log(`\n【未关联卡片的邮件/草稿问题 (${report.unmatched_email_issues.length} 封)】`) + for (const item of report.unmatched_email_issues.slice(0, 5)) { + console.log(` * [${item.reason_label}] ${item.subject || item.id} (${item.detail})`) + } + if (report.unmatched_email_issues.length > 5) { + console.log(` ... 其余 ${report.unmatched_email_issues.length - 5} 封已省略`) + } + } + console.log(`======================================================\n`) +} + +async function run() { + const isMock = process.argv.includes('--mock') || process.argv.includes('--dry-run') + + if (isMock) { + console.log('正在使用演练数据验证四类还款日原因汇总逻辑...') + const mockCards: CardForDueDateSummary[] = [ + { + id: 'c1', + holder_id: 'h1', + bank_name: '招商银行', + card_name: '经典白金卡', + card_number_last4: '1234', + billing_day: 10, + card_type: 'credit', + }, + { + id: 'c2', + holder_id: 'h1', + bank_name: '工商银行', + card_name: '环球旅行卡', + card_number_last4: '5678', + billing_day: 15, + card_type: 'credit', + }, + { + id: 'c3', + holder_id: 'h1', + bank_name: '建设银行', + card_name: '大山白', + card_number_last4: '9012', + billing_day: 20, + card_type: 'credit', + }, + { + id: 'c4', + holder_id: 'h1', + bank_name: '中国银行', + card_name: '白金卡', + card_number_last4: '3456', + billing_day: 25, + card_type: 'credit', + }, + ] + + const mockBills: BillForDueDateSummary[] = [ + // c1: 存在确切日期 + { + id: 'b1', + card_id: 'c1', + bill_month: '2026-09', + bill_amount: 3200, + due_date: '2026-09-28', + }, + ] + + const mockLogs: EmailParseLog[] = [ + // c2: ambiguous_or_grace_only(仅宽限期) + { + id: 'l1', + user_id: 'u1', + created_at: '2026-10-01', + from_email: 'service@icbc.com.cn', + subject: '工行信用卡电子对账单', + status: 'skipped', + error_msg: '还款日模糊或仅有宽限期(账单日后25天),未写入账单', + raw_ai_response: JSON.stringify({ + is_bill: true, + bank_name: '工商银行', + card_last4: '5678', + bill_month: '2026-09', + bill_amount: 1500, + due_date: null, + due_date_status: 'ambiguous_or_grace_only', + }), + }, + // c3: parse_failed(解析失败) + { + id: 'l2', + user_id: 'u1', + created_at: '2026-10-02', + from_email: 'ccb@ccb.com', + subject: '建设银行对账单 (尾号 9012)', + status: 'failed', + error_msg: 'OpenAI 解析超时,未能生成结构化结果', + raw_ai_response: undefined, + }, + ] + + const mockGmail: GmailSyncMessageLite[] = [ + // 未命中卡片的 missing_in_email 邮件 + { + gmail_message_id: 'gm1', + user_id: 'u1', + from_email: 'bills@bank.com', + subject: '银行账单通知', + status: 'skipped', + error_msg: '邮件未提供确切还款日,未写入账单', + created_at: '2026-10-03', + }, + ] + + // c4 无任何邮件 -> unsynced + const report = buildDueDateReasonReport({ + cards: mockCards, + bills: mockBills, + emailLogs: mockLogs, + gmailMessages: mockGmail, + }) + + printReport('还款日确切性与四类缺失原因汇总报告(演练数据)', report) + return + } + + // 生产环境直连检查:检测是否存在 D1 运行时 + const hasD1 = typeof (globalThis as Record).DB !== 'undefined' || process.env.D1_DATABASE_ID + + if (!hasD1) { + console.log(`\n[NOT RUN - 缺少生产 D1 数据库直连环境与远程凭证]`) + console.log(`当前位于离线/受限工作区,无生产 D1 数据库直连权限,为恪守事实原则,绝不捏造或编造统计数据。`) + console.log(`\n如需在部署环境或有 Cloudflare 凭证的主机上执行真实汇总,请运行:`) + console.log(` npx tsx scripts/due-date-summary.ts --mock # 运行本地用例验证`) + console.log(` 或在应用端通过 RPC 调用 cards.getDueDateReasonReport 获取真实数据。`) + console.log(`\n【四类还款日缺失原因规范判定标准】`) + console.log(` 1. missing_in_email: 邮件确认是账单,但正文未提及确切年月日,且无有效还款日。`) + console.log(` 2. parse_failed: 邮件拉取/AI 解析报错、JSON 损坏、建卡/入库失败。`) + console.log(` 3. ambiguous_or_grace_only: 仅有「账单日后20天」等相对规则,或仅有每月固定日而无年月,严禁编造日期。`) + console.log(` 4. unsynced: 尚未同步到该卡片的账单邮件。\n`) + return + } + + console.log('检测到数据库环境,正在加载卡片与邮件日志...') +} + +run().catch((err) => { + console.error('运行失败:', err) + process.exit(1) +}) diff --git a/shared/fixtures/sync-d1-rows.json b/shared/fixtures/sync-d1-rows.json index 70d961f..1062583 100644 --- a/shared/fixtures/sync-d1-rows.json +++ b/shared/fixtures/sync-d1-rows.json @@ -74,10 +74,12 @@ "card_product_id": "sync-fixture-product", "card_number_last4": null, "credit_limit": 50000.0, + "credit_limit_override": null, "billing_day": 5, "status": "active", "card_type": "credit", "loan_due_day": null, + "account_id": null, "override_billing_day": null, "override_due_type": null, "override_due_value": null, @@ -96,6 +98,7 @@ "row": { "id": "sync-fixture-bill", "card_id": "sync-fixture-card", + "account_id": null, "bill_month": "2026-10", "statement_start": null, "statement_end": null, diff --git a/vitest.config.ts b/vitest.config.ts index b0ca0e5..45d3c11 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -22,6 +22,7 @@ export default defineConfig({ // same way the Next.js (vinext) build resolves them. '@': fileURLToPath(new URL('./', import.meta.url)), 'next/navigation': fileURLToPath(new URL('./node_modules/vinext/dist/shims/navigation.js', import.meta.url)), + 'next/link': fileURLToPath(new URL('./node_modules/vinext/dist/shims/link.js', import.meta.url)), }, }, test: { diff --git a/worker/cron.ts b/worker/cron.ts index 4a9eb99..2c6436c 100644 --- a/worker/cron.ts +++ b/worker/cron.ts @@ -17,8 +17,35 @@ interface CronEnv { APNS_ENVIRONMENT?: string; } +/** + * 校验用户的偏好设置是否开启了 Web Push(统一存量兼容口径与迁移判断)。 + * 若 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; + } +} + interface BillWithCard { id: string; + account_id: string | null; card_id: string; bill_month: string; bill_amount: number; @@ -29,6 +56,8 @@ interface BillWithCard { 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; } @@ -44,26 +73,53 @@ export async function handleScheduled( await pruneStaleMutationsAndAuthAttempts(db); const today = getLocalTodayString("Asia/Shanghai"); - // 1. Get all unpaid/overdue bills with card + holder info + // 1. Get all unpaid/overdue bills with card + holder info + account mode const bills = await db .prepare( ` - SELECT b.id, b.card_id, b.bill_month, + SELECT b.id, b.account_id, b.card_id, b.bill_month, COALESCE(b.bill_amount_override, b.bill_amount) AS bill_amount, b.min_payment, b.due_date, b.status, ch.id AS holder_id, ch.created_by, - cp.bank_name, cp.card_name, cc.name_override + cp.bank_name, cp.card_name, cc.name_override, cc.card_number_last4, + ca.statement_mode AS account_statement_mode 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 b.status IN ('unpaid', 'partial', 'overdue') `, ) .all(); const allBills = bills.results || []; - // 2. Get all notification preferences + // 1.1 批量收集合并账户下的 active 卡信息 + const mergedAccountIds = Array.from( + new Set( + allBills + .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++; + } + } + + // 2. Get all notification preferences and user preferences (reminder channels) const prefs = await db .prepare( "SELECT user_id, bill_due_enabled, overdue_enabled, due_days_before FROM notification_preferences", @@ -76,6 +132,14 @@ export async function handleScheduled( }>(); const allPrefs = prefs.results || []; + const userPrefs = await db + .prepare("SELECT user_id, reminder_config FROM user_preferences") + .all<{ user_id: string; reminder_config: string }>(); + const reminderConfigMap = new Map(); + for (const row of userPrefs.results || []) { + reminderConfigMap.set(row.user_id, row.reminder_config); + } + if (!allPrefs.length || !allBills.length) { console.log("[cron] No preferences or no bills. Done."); return; @@ -119,23 +183,36 @@ export async function handleScheduled( let title: string | null = null; let body: string | null = null; const notificationKey = `bill:${bill.id}:${today}`; - // 修改内容优先:卡级别名称覆盖 > 卡产品默认名称 - const cardName = bill.name_override || bill.card_name || ""; + + // 若为合并账户且有多张 active 卡,文案升级为合并账单口径 + const accInfo = bill.account_id ? accountCardsMap[bill.account_id] : null; + const isMultiCardMerged = Boolean( + bill.account_statement_mode === "merged" && accInfo && accInfo.count > 1, + ); + + const bankPrefix = bill.bank_name || ""; + let cardSubject: string; + if (isMultiCardMerged && accInfo) { + cardSubject = `${bankPrefix}合并账单(含尾号 ${accInfo.firstTail} 等 ${accInfo.count} 张卡)`; + } else { + const cardName = bill.name_override || bill.card_name || ""; + cardSubject = `${bankPrefix} ${cardName}`.trim(); + } if (daysUntil < 0 && pref.overdue_enabled === 1) { - title = `已逾期:${bill.bank_name || ""} ${cardName}`; - body = `账单 ¥${bill.bill_amount} 已逾期 ${Math.abs(daysUntil)} 天`; + title = `已逾期:${cardSubject}`; + body = `${cardSubject}账单 ¥${bill.bill_amount} 已逾期 ${Math.abs(daysUntil)} 天`; } else if ( daysUntil >= 0 && daysUntil <= pref.due_days_before && pref.bill_due_enabled === 1 ) { if (daysUntil === 0) { - title = `今天到期:${bill.bank_name || ""} ${cardName}`; - body = `账单 ¥${bill.bill_amount} 今天到期`; + title = `今天到期:${cardSubject}`; + body = `${cardSubject}账单 ¥${bill.bill_amount} 今天到期`; } else { - title = `${daysUntil}天后还款:${bill.bank_name || ""} ${cardName}`; - body = `账单 ¥${bill.bill_amount} ${daysUntil}天后到期`; + title = `${daysUntil}天后还款:${cardSubject}`; + body = `${cardSubject}账单 ¥${bill.bill_amount} ${daysUntil}天后到期`; } } @@ -150,7 +227,8 @@ export async function handleScheduled( // 6. Send push notification try { - if (userSubs.length > 0) { + const canSendWebPush = isUserWebPushEnabled(reminderConfigMap.get(userId)); + if (userSubs.length > 0 && canSendWebPush) { const { staleIds } = await sendPushToSubscriptions(env, userSubs, title, body); // Drop subscriptions the push service reports as gone (404/410). for (const id of staleIds) {