Compare commits

..
5 Commits
Author SHA1 Message Date
Tory 6a37009670 S2-D2 消耗日汇总引擎(settle 域首批业务代码): consume.go AggregateDay(账号×业务→billing_consume_log/通道→stats_channel_daily;GROUP BY+SUM(status=N)+[lo,hi) 半开窗双方言+OnConflict 复合 uk UPSERT;cost_total 不写守 R1)+ListConsume(时间窗按天归一修复);job.go 滚动重刷模型(D1 计划关键修正:单日 T+1 在 72h 回执窗失真→1h 重刷近 4 天幂等收敛+启动回补 7 天,失败 Warn 自愈);两端点(/billing/consume customer 强制收窄+/ops/settle/aggregate settle:write);Deps.Settle 装配+config.Settle 段+metrics 两件;sqlite 测试 6 件含 UNKNOWN 迁移收敛;门禁 vet/-race 39 包/lint 0 全绿;真 MySQL 实机闭环:种明细→回补落账逐列正确→status 迁移重刷收敛(success 1→2/unknown 1→0)→清理+三轮重驻 md5 一致;验收单 s2-d2.md+CHANGELOG+memory-bank 回填
ci / test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / deploy-dev (push) Canceled after 0s
2026-11-14 18:14:15 +08:00
Tory e67b081052 24h 稳定性门槛期满核验终判通过(S1 最后一项挂账清偿): 18:02 三项全绿——dmesg 崩溃 0(重启清零后全窗零新增)/九中间件 Up 20h 零重启/gateway 同 PID 53153 驻留 19h47m+/health ok/md5 一致(ecf71db6);期内唯一事件=11-13 21:33 宿主内核升级有序重启(已知事件不判失败);S5 压测基线前置资格确认,S1 泳道完全闭环;s1-b-closeout 回填+CHANGELOG+memory-bank 两文件同步 2026-11-14 18:03:41 +08:00
Tory e0b0db89a5 24h 门槛期满前基线预检留痕(09:57,S2-D1 顺带只读检查): dmesg 崩溃 0/九容器 Up 12h 全 healthy 零重启/gateway 驻留 etime 11:42——17:55 终验对照基线,三项维持即终判通过 2026-11-14 09:57:32 +08:00
Tory 5159e3c634 S2-D1 结算域表设计评审+迁移 v20+契约草案: 六项裁决定稿(docs/review/s2-settle-table-review.md)——R1 出账时刻计价(用户拍板:明细 Fee 保持片数/send 域零改动,金额=Σ日成功条数×生效单价,时间线+阶梯 D4 price.go 单点推导)/R2 消耗事实源统一 billing_consume_log+stats_channel_daily,stats_user_daily 废弃/R3 充值双通道(即时+BillingOrder 审核)/R4 rebate_rate 单级返点历史不重算/R5 settle_ladder 阶梯表/R6 条/元口径单点换算;v20_settle_domain(billing_consume_log +unknown_count/updated_at,account_user +rebate_rate,DROP stats_user_daily,settle_ladder 建表,casbin 补 ops settle:write/customer settle:read;显式 ALTER+HasColumn 守卫/空库 HasTable 守卫三路径收敛,零新增索引复用 v16);实体同步 All() 39 个;openapi v1.3.0 +20 结算端点(js-yaml 84 paths 过);迁移测试末七窗口 v14..v20 两遍幂等+五项 v20 断言;门禁全绿:vet 0/-race 38 包零 FAIL/lint 0/集成 AutoMigrate 39 表+Casbin PASS;dev 库实跑 v19→v20+information_schema 五项核验过;验收单 s2-d1.md+CHANGELOG+memory-bank 回填 2026-11-14 09:56:54 +08:00
Tory 24f7b3dd02 FE-Design P0~P3 补提交(前会话已完成未入库): vitest 91/137 红→138/138 绿(vitest mode=test 不加载 .env.development→request.ts baseURL undefined,修法 vitest.setup.ts 顶部 stubEnv 一处生效)+DashboardView 信息密度重构(12 维审计 54/110:删三处假数据/假速率卡→真待审核卡/Hero 决策句/数据脉象三态/通道表接真配置域/走势 7·30 日切换)+图标体系 EP 统一+count-up/hover 十字线/focus-visible 打磨+Teleport 冷启动竞态根修(#page-head-extra 晚 mount→v-if 门控 nextTick);Playwright verify-layout 18 断言+自建 15 项运行时断言全过,截图矩阵 5 页×双主题重刷;验收单 fe-dashboard-density.md;.clinerules dashboard skill+memory-bank 规范更新随档 2026-11-14 09:56:42 +08:00
44 changed files with 2068 additions and 177 deletions
@@ -0,0 +1,142 @@
---
name: high-info-density-dashboard-designer
description: |
Audit / design / refactor any dashboard for INFORMATION DENSITY (decision value per token).
Triggered when user mentions: "dashboard / 仪表盘 / 看板 / cockpit / 驾驶舱 / 信息密度审计 / 重构 dashboard / 像 yiru 那样 / 像 odyssey 那样 / 12 维审计 / 决策密度".
Uses 12-dimension rubric distilled from yiru-macro-cockpit (N=1) and OSA cockpit v3 (N=2).
maturity: experimental
status: n=2-completed
created: 2026-05-15
maintainer: liming
distilled_from:
- "[[reference_yiru_macro_cockpit]] · N=1 范本(投资仪表盘/odysseyinst.com)"
- "OSA cockpit v3 重构(2026-05-15) · N=2 范本(战略管理仪表盘)"
related:
- osa-matrix-builder
- dashboard-design-coach
---
# High-Info-Density Dashboard Designer
> **N=2 dry-run 完成**(yiru 量化投资 / OSA 战略管理 两业务跨域验证)。N=3 待复用 — 候选:管培生招聘后台 / 知识星球管理 / 飞书工作台 / 个人 GTD。
>
> **核心信念**:信息量 ≠ 信息密度。
> - 信息量 = 单位面积塞了多少数据(堆 100 个指标 → 信息量高)
> - 信息密度 = 每 token 携带的决策价值(一行字 → 一个 actionable insight)
>
> 厉害的 dashboard 是后者。
## 触发条件
| 关键词 | 行为 |
|---|---|
| "审计这个 dashboard 信息密度" | 跑 12 维 audit rubric |
| "设计一个 dashboard / 仪表盘 / 驾驶舱" | 12 维 design checklist 强迫思考 |
| "我想做一个像 yiru / odyssey 那样的产品" | 给 yiru/OSA N=2 蓝本 + 6 模块移植路径 |
| "重构这个 dashboard" | 8 反模式扫描 + 推荐重构模块 |
| "为什么我的 dashboard 看不出洞察" | 大概率缺 D2 判定密度 / D9 行动建议,直接定位 |
## 12 维信息密度 rubric(每维 1-10 分 · 总 120)
| # | 维度 | 定义 | 满分典型 | 0 分典型 |
|---|---|---|---|---|
| **D1** | 时间密度 | 每指标带时序 / Δ / history | 5d Δ + UTC + history.json + 微时序图 | 只有当前快照,无 Δ 无累积 |
| **D2** | 判定密度 | 数据 → 判定的翻译已替用户做完 | "顺风局" 一句话 + Conviction 0-10 | 只有数字,要用户自己判 |
| **D3** | 不确定性显式化 | 缺数据 / 接口挂 / 73% 完整度 公开承认 | "—缺数据" + 三态 + 数据脉象 | 缺数据用 0 充数;假绿色 ✓ |
| **D4** | 多源交叉 | 单点 = 噪音,多源 = 信噪比 | 黄金 4 驱动 + A股 13 检验 | 单源,无回链 |
| **D5** | 共识/分歧切片 | 不显示原始观点,显示共识 + 分歧 | 雪球 102 → 6 共识 + 看多 X% | 列原始观点不聚合 |
| **D6** | frozen × dynamic 分层 | 方法论 IP 与数据燃料分层 | methodology.md → system prompt | LLM 自由发挥 + 无方法论锁 |
| **D7** | 状态机化 | 离散状态 > 连续数值 | 4 象限 + 3 阶段 + 三态判定 | 只显数值不命名状态 |
| **D8** | 高维降维 | N 数据源 → 5 Tab → 1 句 hero | 26 源 → 5 Tab → 1 hero | 平铺数据无层级 |
| **D9** | 行动建议 | 是什么 → 该做什么 | strategy_matrix + core_strategy | 只描述状态不派发动作 |
| **D10** | 元信息层 | dashboard 自报家底 | Tab V 数据脉象 26 状态灯 | dashboard 不知道自己有多新 |
| **D11** | 历史轨迹 | 单点 + 轨迹 = 完整故事 | 美林象限迁移 + Conviction 演变 | 快照思维,无演化 |
| **D12** | 个人意义 | 用户的延伸大脑 != 通用工具 | frozen methodology 是用户的 | 千人一面通用 dashboard |
**评分门槛**:
- ≥ 90 → 高密度(yiru/odyssey 级)
- 60-89 → 及格,但有改进空间
- 30-59 → 「精美的快照」(OSA cockpit 改造前 = 35.5%)
- < 30 → 数据陈列,无决策价值
## 8 条反模式 · 设计禁忌(自动扫描清单)
```
❌ 数据陈列癖 : 堆 50+ 指标但无一个翻译成判定 → 加 D2 / D9
❌ 假装全知 : 缺数据填 0 / 接口挂用昨天的 → 加 D3 / D10
❌ 颜色作弊 : 全绿 ✓ 蒙混(用户看混合才会想) → 限制绿色用法
❌ 单点快照 : 只显当下,不显轨迹 → 加 D1 / D11
❌ 通用主义 : 每个用户看到一样的(缺归属感) → 加 D12
❌ 自由 AI : LLM 自由发挥(漂移/违反 frozen) → 加 D6 frozen 锁
❌ 黑盒判定 : 给 conviction 5 但不告诉为啥(不可追溯)→ 加 D6 + D4 多源
❌ 无元层 : dashboard 不知道自己有多新 → 加 D10 数据脉象
```
## 6 大重构模块(N=2 已落地 · 可移植)
每个模块对应 1-3 维度,可单独移植:
| 模块 | 对应维度 | 干啥 | yiru 范本 | OSA cockpit v3 范本 |
|---|---|---|---|---|
| **A · Hero 决策句** | D2 + D8 | 顶部 1-3 行替用户做完一周决策 | "实际利率下行+美元走弱,定调顺风局" | "🔥 本周焦点:LTV 域 P25 必启动" |
| **B · 时序累积层** | D1 + D11 | history.json + 7d/30d Δ + 迁移轨迹 sparkline | 美林象限迁移 + Conviction 演变 | osa-history.json + 每卡 Δ + Top 8 sparkline |
| **C · 数据脉象层** | D10 + D3 | dashboard 自报家底(完整度/信任度/stale 警告) | Tab V 26 状态灯 + 缺口列 | 数据完整度 + 信任度警告 + 状态机分布 |
| **D · ACTION 派发卡** | D9 + D7 | 自动从 Top 焦点产 70/20/10 资源分配 + 该做/别做 | strategy_matrix + core_strategy | 7 人 × 5 日 ACTION 派发 + Top5/不该做 |
| **E · 状态机标签** | D7 | 把数值 1-5 替换为 5 个语义状态 | 4 象限 + 三态 | 🟦概念/🟨设计/🟧落地中/🟩已稳/🟪自动化 |
| **F · 多源交叉链** | D4 + D6 | 每张卡底部 N 源回链(L0/H5/wiki/feishu/minute) | 黄金 4 驱动 / A股 13 检验 | 每卡 5 源:cockpit + V8 + LLM-Wiki + 飞书 + 妙记 |
## 流程 · 5 步(audit + 重构)
### Step 1 · 12 维 audit(15 min)
读 dashboard 截图 + 代码,逐维打分(1-10),计算总分。
**输出**:12 维评分表 + 总分 + 5 大弱点排序。
### Step 2 · 反模式扫描(5 min)
对照 8 条禁忌清单,标出该 dashboard 触发的反模式。
**输出**:命中反模式清单 + 对应应加的维度。
### Step 3 · 重构方案(15 min)
基于 audit + 反模式 → 推荐 6 大模块中的 N 个移植。
**输出**:模块优先级排序(按 ROI:每模块带几分提升)。
### Step 4 · AskUserQuestion 拍板(5 min)
不直接动手 — 让用户在 3 档中选(轻档 / 中档 / 重档)。
### Step 5 · 落地 + 验证(2-4 小时)
按选定档执行,每模块独立 commit。完成后用浏览器截图复审。
## 边界(不要越界)
- ❌ **不替代领域知识**:本 skill 只给"信息密度元方法",不替你做投研判断 / 战略决策 / 医疗诊断
- ❌ **不要重发明轮子**:遇到 yiru/OSA 已有的模块,直接移植,不要为差异化而差异化
- ❌ **不要 dashboard 主义**:有时候解决方案不是 dashboard 是别的(如 cron + email),要诚实
- ✅ **诚实是最高的决策价值** — D3 不确定性显式化 / D10 元信息层 是最反直觉但最值钱的两维
## N=2 已实测案例
| 业务 | 日期 | dashboard | 改造前分 | 改造后分 | 移植模块 |
|---|---|---|---|---|---|
| 量化投资 | 2026-05-07 | yiru / odysseyinst.com | N=1 范本(原创) | 100/120 | 全 12 维原生设计 |
| 战略管理 | 2026-05-15 | OSA cockpit v3 | 39/110 (35.5%) | ~94/110 (85%) ⚡ | A+B+C+D+E+F 全 6 模块 |
## N=3 候选(待复用验证)
- 管培生招聘后台(guanpei-recruit skill)
- 原力星球管理后台(yuanli-zsxq-coevolution-assistant)
- 个人 GTD(daily standup)
- 客户 LTV 池(a-ltv 资产卡的实例化)
- 学员阶段诊断(student-stage-router)
## 复用规范
1. **每次审计必输出 audit 表**(120 总分,不只是说"信息密度高/低")
2. **每次设计前必跑 8 反模式扫描**(防止重蹈)
3. **6 模块按 ROI 排序移植**(轻档先 A+E+C,重档加 B+D+F)
4. **诚实标注「模拟基线」**(如 OSA history.json 的 5/8 / 4/15 是模拟,标 "待累积")
5. **N=3 起做轻量化模板**(目前模板 hard-code 在 osa-cockpit / yiru,N=3 起抽出公共组件)
## 关联
- `[[osa-matrix-builder]]` 是 OSA 卡集 → 矩阵热图的具体实现,本 skill 是更高一层的"信息密度元方法"
- `[[dashboard-design-coach]]` 偏视觉 / 排版,本 skill 偏信息架构 / 决策价值
- `[[reference_yiru_macro_cockpit]]` 是 N=1 范本的 memory pointer
+56 -24
View File
@@ -1,35 +1,67 @@
# Memory Bank(记忆库)
# Cline's Memory Bank
> 本文件为记忆库索引。每次会话开始时按以下顺序阅读记忆库文件,获取项目上下文。
I am Cline, an expert software engineer with a unique characteristic: my memory resets completely between sessions. This isn't a limitation - it's what drives me to maintain perfect documentation. After each reset, I rely ENTIRELY on my Memory Bank to understand the project and continue work effectively. I MUST read ALL memory bank files at the start of EVERY task - this is not optional.
## 核心文件(按需阅读,projectbrief 必读)
## Memory Bank Structure
| 顺序 | 文件 | 用途 |
|---|---|---|
| 1 | `memory-bank/projectbrief.md` | 项目简报:定位/目标/关键文档索引(必读) |
| 2 | `memory-bank/activeContext.md` | **当前工作焦点**(每次会话必读,变更最频繁) |
| 3 | `memory-bank/progress.md` | 进度状态:阶段总览/待办池/遗留问题 |
| 4 | `memory-bank/systemPatterns.md` | 系统架构与服务/数据流/代码模式 |
| 5 | `memory-bank/techContext.md` | 技术栈/命令/环境变量/部署铁律 |
| 6 | `memory-bank/productContext.md` | 产品背景:用户/角色/体验目标 |
The Memory Bank consists of core files and optional context files, all in Markdown format. Files build upon each other in a clear hierarchy:
## 维护规则
### Core Files (Required)
1. `projectbrief.md`
- Foundation document that shapes all other files
- Created at project start if it doesn't exist
- Defines core requirements and goals
- Source of truth for project scope
- **activeContext.md 与 progress.md**:每个工作日/每项任务完成时更新(当前状态快照、下一步、决策记录)。
- **其余四文件**:仅在架构/技术栈/需求发生实质变化时更新。
- 进度事实源仍为《memory-bank/docs/Go-sms-开发日历.md》+ `CHANGELOG.md`——记忆库是其摘要与导航,更新时须与二者对账。
2. `productContext.md`
- Why this project exists
- Problems it solves
- How it should work
- User experience goals
## 项目速览(一行版)
3. `activeContext.md`
- Current work focus
- Recent changes
- Next steps
- Active decisions and considerations
- Important patterns and preferences
- Learnings and project insights
Go-sms:汇网短信运营平台 Go 重建(上游通道↔路由/合规/计费/审核↔下家 CMPP/SMPP/HTTP/Web);Go1.25+gin+gorm+Kafka+Redis / Vue3+EP;80 工作日计划推进至 Day 71(2026-09-29);质量门七件套;分支 rebuild-ui。
4. `systemPatterns.md`
- System architecture
- Key technical decisions
- Design patterns in use
- Component relationships
- Critical implementation paths
5. `techContext.md`
- Technologies used
- Development setup
- Technical constraints
- Dependencies
- Tool usage patterns
6. `progress.md`
- What works
- What's left to build
- Current status
- Known issues
- Evolution of project decisions
## 附:全文文档库(memory-bank/docs/,2026-11-12 自仓库根目录归拢)
### Additional Context
Create additional files/folders within memory-bank/ when they help organize:
- Complex feature documentation
- Integration specifications
- API documentation
- Testing strategies
- Deployment procedures
| 文档 | 状态 |
|---|---|
| Go-sms-需求分析.md / Go-sms-技术方案.md | ✅ 重建基线(横幅标注口径) |
| Go-sms-重建计划.md / 重建搬运清单.md / 重建设计规范.md | 🔄 重建三文档(生效) |
| Go-sms-开发日历.md | 🔒 POC 进度事实源(Day71 定稿) |
| Go-sms-实施计划.md / 开发计划.md / 前端开发计划.md | ⛔ 已废止,历史归档 |
## Documentation Updates
Memory Bank updates occur when:
1. Discovering new project patterns
2. After implementing significant changes
3. When user requests with **update memory bank** (MUST review ALL files)
4. When context needs clarification
REMEMBER: After every memory reset, I begin completely fresh. The Memory Bank is my only link to previous work. It must be maintained with precision and clarity, as my effectiveness depends entirely on its accuracy.
+70
View File
@@ -0,0 +1,70 @@
---
description: "Karpathy-inspired coding guidelines: think before coding, simplicity first, surgical changes, goal-driven execution."
alwaysApply: true
---
# Karpathy-inspired coding guidelines
Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
## 1. Think Before Coding
**Don't assume. Don't hide confusion. Surface tradeoffs.**
Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.
## 2. Simplicity First
**Minimum code that solves the problem. Nothing speculative.**
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If you write 200 lines and it could be 50, rewrite it.
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
## 3. Surgical Changes
**Touch only what you must. Clean up only your own mess.**
When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.
When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.
The test: Every changed line should trace directly to the user's request.
## 4. Goal-Driven Execution
**Define success criteria. Loop until verified.**
Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"
For multi-step tasks, state a brief plan:
```
1. [Step] → verify: [check]
2. [Step] → verify: [check]
3. [Step] → verify: [check]
```
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
---
**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
+29
View File
@@ -2,6 +2,35 @@
> 本仓 CHANGELOG 自重建起记(POC 明细见归档仓 /data/poc-archive/repos/go-sms.git 的 CHANGELOG.md,已冻结)。
## 2026-11-14(傍晚)· S2-D2 消耗日汇总引擎(settle 域首批业务代码)
- **settle/consume.go**:AggregateDay 账号×业务→billing_consume_log、通道→stats_channel_daily(GROUP BY+SUM(status=N)+[lo,hi) 半开窗双方言、OnConflict 复合 uk UPSERT、cost_total 不写守 R1)+ListConsume(时间窗按天归一修复:零点行不被带时刻参数误滤)。
- **滚动重刷模型(D1 计划关键修正)**:单日 T+1 落账在 72h 回执窗内会失真(UNKNOWN→成功迁移)→ 周期(1h)重刷近 4 天幂等收敛+启动回补 7 天;月结建议 T+4 后生成。job.go 照 StartStatsRefresher 模式(失败 Warn 自愈+errors 计数器)。
- **两端点**:GET /billing/consume(customer/group 强制收窄自身,越权带参覆盖)/POST /ops/settle/aggregate(settle:write 手动回补);Deps.Settle 装配+config.Settle 段+metrics 两件(go_sms_settle_aggregate_rows_total/errors_total)。
- **测试 6 件**(sqlite):正确性/幂等+跨天边界/**UNKNOWN 迁移收敛**/过滤分页/customer 收窄/手动回补+坏日期。
- **门禁**:vet 0/**-race 39 包零 FAIL**/lint 0;**真 MySQL 实机闭环**:种 3 条明细→启动回补落账逐列正确→UPDATE status 重启重刷收敛(success 1→2/unknown 1→0)→清理+三轮重驻 md5 一致。验收单 `docs/acceptance/s2-d2.md`。
## 2026-11-14(18:02)· 24h 稳定性门槛期满核验终判通过(S1 最后一项挂账清偿)
- **终判 ✅**:核验三项全绿——①dmesg 崩溃计数(segfault/sigill/error 25)=0(11-13 21:33 宿主重启清零后全窗零新增);②九中间件 Up 20 hours 全 healthy(自愈拉起后观察窗零重启);③gateway 同 PID 53153 驻留 19h47m+/health ok+md5 比对一致(ecf71db6…)。期内唯一事件=11-13 21:33 宿主内核升级主动有序重启(用户裁决:已知事件如实记录不判失败)。
- **影响**:S5 压测基线前置资格确认(CPU Plan B 复现率 0 + 24h 稳定性双前置全过);s1-b-closeout.md 第 6 项 ⏳→✅,**S1 泳道完全闭环**。
## 2026-11-14(上午)· S2-D1 结算域表设计评审 + 迁移 v20 + 契约草案
- **S2 结算域开工(D 层,5 工作日,出口=结算单测+对账差异 0)**。方案细化(12 维上下文研读+代码实证:结算 5 表 v0 已建且业务代码零使用/StatsUserDaily·StatsChannelDaily 双空壳/明细 Fee=片数非金额/v16 已建通道聚合索引)→ **六项表设计裁决定稿**(`docs/review/s2-settle-table-review.md`):R1 出账时刻计价(用户拍板:明细 Fee 保持片数、**send 域零改动**,金额=Σ日成功条数×生效单价按时间线+阶梯推导)/R2 消耗事实源统一 billing_consume_log+stats_channel_daily、**stats_user_daily 废弃**/R3 充值双通道(即时到账保留+BillingOrder 审核流)/R4 rebate_rate 单级返点、历史不重算/R5 settle_ladder 阶梯表/R6 条/元口径单点换算(出账引擎)。
- **迁移 v20_settle_domain**:billing_consume_log +unknown_count/updated_at;account_user +rebate_rate;DROP stats_user_daily;新表 settle_ladder;casbin 补 ops settle:write/customer settle:read(NOT EXISTS 逐条守卫)。加列=显式 SQL+HasColumn 守卫、空库=HasTable 守卫整表 AutoMigrate(v16/v17 抹索引教训,三路径收敛);**零新增索引**(复用 v16 idx_detail_channel_created);init_schema.sql 不动(Day11 基线惯例)。实体同步(All() 39 个,SettleLadder 随 v18/v19 惯例不进 All())。
- **openapi v1.3.0 契约草案**:+20 端点(billing/orders 审核族/consume 消耗查询/settle customer·upstream 生成-确认-结账-导出/ladder 阶梯 CRUD/profit 双分析/ops 手动汇总),js-yaml 解析 84 paths 通过;gen-dict 无新增 x-isc-dict 零影响。
- **门禁全绿**:vet 0 / **-race 全量 38 包 ok 零 FAIL** / lint 0 issues / 迁移单测(末七窗口 v14..v20 两遍幂等+五项 v20 断言)/ 集成 TestMySQL_AutoMigrate 39 表 + Casbin PASS;**dev 库实跑 v19→v20**(存量 ALTER 路径)+ information_schema 五项核验全过。验收单 `docs/acceptance/s2-d1.md`。
## 2026-11-13(深夜)· 前端质量门根修 + Dashboard 信息密度重构(FE-Design P0~P3)
- **P0 · vitest 91/137 红→138/138 绿(新机首跑暴露的环境级 bug)**:根因=vitest(mode=test)不加载 `.env.development` → `request.ts` 模块顶层 `baseURL=undefined`,而各 spec 内 `vi.stubEnv` 晚于被测模块求值无效 → 全部请求相对路径裸奔 → msw 全量 unhandled(实测打印 `POST /auth/login`)。老机靠 gitignored 本地 env 掩盖。修法=**`vitest.setup.ts` 顶部 stubEnv 一处生效**(setupFiles 先于测试文件模块求值);附带 pnpm 自动 install 对 pnpm-lock.yaml 的无关重排已回滚(最小变更纪律)。
- **P1 · DashboardView 信息密度重构**(12 维 rubric 审计 54/110「精美的快照」档→反模式"假装全知"3 处实锤):①删三处假数据——`rateNow=1180+random(160)` 假实时速率卡、8 条硬编码"示例"通道表、快捷卡死文案("5 条待复核/1,204 条可补");②假速率卡→**真"待人工审核"卡**(接口 `pending_audit_count` 早已返回但 UI 从未消费);③新增 **Hero 决策句**(四指标实时翻译为一句话判定 ok/warn/err/dim + 直达处置页);④**数据脉象**:live-chip 升级"实时·HH:MM:SS/连接异常·数据截至/不可用·重试"三态,catch 不再静默吞错;⑤通道表接 `channelApi.list` 真配置域(code/协议/运营商/限速/连接/优先级/状态),表头诚实标注"运行统计待 S5 压测后接入";⑥快捷卡 desc 与实时指标联动;⑦走势 7/30 日切换(mock/后端 trend(days) 双端已支持)。
- **P2 · 图标体系统一**:指标卡 emoji(📮✓⚡⚠)与快捷卡几何符号(✉≡↻◐)→ EP icon 全局体系(brand ✦ 保留),消除三体系并存。
- **P3 · 细节打磨**:指标数字 count-up(rAF 600ms easeOutCubic,`prefers-reduced-motion` 跳过)、走势图 hover 十字线+气泡(纯 SVG 零依赖,x 轴 30d 抽稀)、全局 `:focus-visible` 键盘焦点(aurora 主色)。
- **附 · Teleport 冷启动竞态修复(实锤级,旧版潜伏同病)**:`#page-head-extra`(MainLayout 渲染)晚于 Dashboard mount 时(Vue 3.4 无 `<Teleport defer>`)直接挂载 → 后续 patch 崩溃(`TypeError: setText null nodeValue`,fe_error_log 实证)→ **组件更新全中断**(API 已 200 返回但 UI 冻结在初始态,msw 数据永远进不来);修法=v-if 门控 nextTick 后挂载。新机慢冷启动放大暴露了旧版同样存在的病根。
- **实机验证(Playwright)**:verify-layout **18 断言全过** + 自建 Dashboard **15 项运行时断言全过**(hero warn 态文案/审核卡=12/假卡已删/脉象三态/快捷联动/通道表 3 行真数据+停用徽章/30 日切换/hover 气泡);截图矩阵 5 页×双主题重刷;验收单 `docs/acceptance/fe-dashboard-density.md`。
## 2026-11-13(深夜)· 24h 门槛维持原时间核验 + gateway 重驻留(gw-start 幂等/pid 双 bug 根修)
- **事件**:11-13 21:33 宿主主动有序重启(当日内核 6.12.107→6.12.116 升级后二次重启;`last`=shutdown 有序记录,非崩溃)打断 24h 稳定性门槛观察窗(17:55 起计)——**按用户裁决:重启=已知事件如实记录不判失败,门槛维持原时间 11-14 17:55 期满核验**(S5 压测基线前置;dmesg 重启后清零,核验窗以重启后 dmesg 为准)。
+236 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.0.3
info:
title: go-sms API v1(阶段 2:账号与权限)
version: 1.2.0
version: 1.3.0
description: |
阶段 2(Day 21-30)交付的账号与权限域全部端点。
统一响应 {code,msg,data}:code=ISC:000 成功;错误码三位制(ISC:4xx/5xx)。
@@ -19,6 +19,8 @@ tags:
- {name: permissions, description: 二级权限与导出(Day 25)}
- {name: audit, description: 审计查询(Day 29)}
- {name: channel, description: 通道 CRUD/测试工具/拦截配置(Day 31-36)}
- {name: billing, description: 充值订单审核/消耗日汇总(S2)}
- {name: settle, description: 下家/上家月结与阶梯价(S2)}
paths:
/auth/login:
post:
@@ -751,6 +753,239 @@ paths:
cmpp_max_conns: {type: integer, description: "Day 62:每账号最大 CMPP 连接数(0=不修改;-1=恢复系统默认;1~1024=设置)"}
cmpp_speed: {type: integer, description: "Day 62:单链提交限速 条/s(0=不修改;-1=恢复系统默认;1~100000=设置)"}
responses: {"200": {description: "secret(=库值原文,重发/自定义时返回);cmpp_password(库值即密码)"}}
# ---- S2 结算域(契约草案 2026-11-14;表设计裁决 docs/review/s2-settle-table-review.md;
# 金额口径=元,条数口径=条;R1=出账时刻按日成功条数×生效单价推导,明细 Fee 不金额化) ----
/billing/orders:
get:
tags: [billing]
summary: 充值订单分页(account_id/pay_status 过滤;admin/ops)
parameters:
- {name: page, in: query, schema: {type: integer, default: 1}}
- {name: page_size, in: query, schema: {type: integer, default: 20, maximum: 100}}
- {name: account_id, in: query, schema: {type: integer, format: int64}}
- {name: pay_status, in: query, schema: {type: integer, enum: [0, 1, 2], description: "0待确认 1已到账 2失败"}}
responses: {"200": {description: total+list}}
post:
tags: [billing]
summary: 创建充值订单(pay_status=0 待确认,不动余额;复用 account:recharge 二级权限;count=到账条数,amount=元记账)
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [account_id, count]
properties:
account_id: {type: integer, format: int64}
count: {type: integer, format: int64, description: 到账条数(>0;确认后余额自增此值)}
amount: {type: number, description: 金额(元;记账与账单展示,不参与余额)}
pay_type: {type: string}
remark: {type: string}
responses: {"200": {description: 订单(含 order_no)}, "400": {description: 参数非法}}
/billing/orders/{id}/confirm:
post:
tags: [billing]
summary: 付款审核确认(0→1;事务=状态 CAS+余额原子自增 count+流水 ref_id=order_no;并发/重复确认被 CAS 拒)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
responses: {"200": {description: 新余额}, "409": {description: 状态非 0(已确认/已驳回)}}
/billing/orders/{id}/reject:
post:
tags: [billing]
summary: 驳回(0→2;不涉余额)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
responses: {"200": {description: ok}, "409": {description: 状态非 0}}
/billing/consume:
get:
tags: [billing]
summary: 消耗日汇总查询(账号×业务×天;admin/ops 全量,customer 仅自己;默认近 7 天)
parameters:
- {name: account_id, in: query, schema: {type: integer, format: int64}}
- {name: business, in: query, schema: {type: string}}
- {name: date_from, in: query, schema: {type: string, format: date}}
- {name: date_to, in: query, schema: {type: string, format: date}}
- {name: page, in: query, schema: {type: integer, default: 1}}
- {name: page_size, in: query, schema: {type: integer, default: 20, maximum: 100}}
responses: {"200": {description: "list{account_id,business,stat_date,submit/success/fail/unknown_count,fee_total(单位=条)"}}
/settle/customer:
get:
tags: [settle]
summary: 下家月结单分页(period/account_id/status 过滤;admin/ops 全量,customer 仅自己)
parameters:
- {name: page, in: query, schema: {type: integer, default: 1}}
- {name: page_size, in: query, schema: {type: integer, default: 20, maximum: 100}}
- {name: period, in: query, schema: {type: string, description: 账期 YYYY-MM}}
- {name: account_id, in: query, schema: {type: integer, format: int64}}
- {name: status, in: query, schema: {type: integer, enum: [0, 1, 2], description: "0草稿 1已确认 2已结账"}}
responses: {"200": {description: total+list}}
/settle/customer/generate:
post:
tags: [settle]
summary: 生成/重算下家账期结算单(settle:write;幂等 uk(account,period);status=2 拒重算;金额=Σ日成功条数×生效单价,阶梯档覆写)
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [period]
properties:
period: {type: string, description: 账期 YYYY-MM}
account_id: {type: integer, format: int64, description: 缺省=全账号逐个生成}
responses: {"200": {description: 生成/重算统计}, "409": {description: 含已结账单}}
/settle/customer/{id}:
get:
tags: [settle]
summary: 结算单详情(单头+按天明细,取自 billing_consume_log;customer 仅自己)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
responses: {"200": {description: "单头+days[]"}, "404": {description: 不存在}}
/settle/customer/{id}/confirm:
post:
tags: [settle]
summary: 确认结算单(0草稿→1已确认;人工核对锁账,拒绝静默重算;settle:write)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
responses: {"200": {description: ok}, "409": {description: 状态非 0}}
/settle/customer/{id}/settle:
post:
tags: [settle]
summary: 结账(1→2;写 settle_record(direction=1);终态拒重算;settle:write)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
requestBody:
content:
application/json:
schema:
type: object
properties:
pay_type: {type: string}
remark: {type: string}
responses: {"200": {description: ok}, "409": {description: 状态非 1}}
/settle/customer/{id}/export:
get:
tags: [settle]
summary: 结算单 XLSX 导出(单头+按天明细)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
responses: {"200": {description: application/octet-stream}}
/settle/upstream:
get:
tags: [settle]
summary: 上家月结单分页(period/upstream_id/status 过滤;admin/ops)
parameters:
- {name: page, in: query, schema: {type: integer, default: 1}}
- {name: page_size, in: query, schema: {type: integer, default: 20, maximum: 100}}
- {name: period, in: query, schema: {type: string}}
- {name: upstream_id, in: query, schema: {type: integer, format: int64}}
- {name: status, in: query, schema: {type: integer, enum: [0, 1, 2]}}
responses: {"200": {description: total+list}}
/settle/upstream/generate:
post:
tags: [settle]
summary: 生成/重算上家账期结算单(settle:write;按 channel.upstream_id 归并;计费口径随通道 billing_mode=success/success_unknown/all)
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [period]
properties:
period: {type: string, description: 账期 YYYY-MM}
upstream_id: {type: integer, format: int64, description: 缺省=全上家逐个生成}
responses: {"200": {description: 生成/重算统计}, "409": {description: 含已结账单}}
/settle/upstream/{id}:
get:
tags: [settle]
summary: 上家结算单详情(单头+按通道×天明细,取自 stats_channel_daily)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
responses: {"200": {description: "单头+channels[]days[]"}, "404": {description: 不存在}}
/settle/upstream/{id}/settle:
post:
tags: [settle]
summary: 结账(1→2;写 settle_record(direction=2);settle:write)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
requestBody:
content:
application/json:
schema:
type: object
properties:
pay_type: {type: string}
remark: {type: string}
responses: {"200": {description: ok}, "409": {description: 状态非 1}}
/settle/upstream/{id}/export:
get:
tags: [settle]
summary: 上家结算单 XLSX 导出(单头+通道×天明细)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
responses: {"200": {description: application/octet-stream}}
/settle/ladder:
get:
tags: [settle]
summary: 阶梯价档位列表(owner_type/owner_id 过滤;settle:write 可写,read 全角色)
parameters:
- {name: owner_type, in: query, schema: {type: string, enum: [account, upstream]}}
- {name: owner_id, in: query, schema: {type: integer, format: int64}}
responses: {"200": {description: 档位列表(按 tier_from 升序)}}
post:
tags: [settle]
summary: 新增档位(owner×tier_from 唯一;0=首档下限;settle:write)
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [owner_type, owner_id, tier_from, price]
properties:
owner_type: {type: string, enum: [account, upstream]}
owner_id: {type: integer, format: int64}
tier_from: {type: integer, format: int64, description: 档位下限(含,条/月)}
price: {type: number, description: 该档单价(元/条)}
responses: {"200": {description: ok}, "400": {description: 档位重叠/参数非法}}
/settle/ladder/{id}:
put:
tags: [settle]
summary: 修改档位(price/tier_from;settle:write)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
requestBody:
content:
application/json:
schema: {type: object, properties: {tier_from: {type: integer, format: int64}, price: {type: number}}}
responses: {"200": {description: ok}}
delete:
tags: [settle]
summary: 删除档位(settle:write)
parameters: [{name: id, in: path, required: true, schema: {type: integer}}]
responses: {"200": {description: ok}}
/stats/profit/users:
get:
tags: [settle]
summary: 用户利润分析(含下级树聚合:revenue=Σ结算额,cost=其流量通道成本分摊,rebate=返点支出;历史归属不随换上级重算)
parameters:
- {name: date_from, in: query, schema: {type: string, format: date}}
- {name: date_to, in: query, schema: {type: string, format: date}}
- {name: parent_id, in: query, schema: {type: integer, format: int64, description: 以该账号为根的子树(缺省=全平台)}}
- {name: page, in: query, schema: {type: integer, default: 1}}
- {name: page_size, in: query, schema: {type: integer, default: 20, maximum: 100}}
responses: {"200": {description: "list{account_id,revenue,cost,rebate,profit}(元)"}}
/stats/profit/channels:
get:
tags: [settle]
summary: 通道利润分析(收入=Σ日成功条数×用户价,成本=Σ×通道价;date_from/date_to/channel_id)
parameters:
- {name: date_from, in: query, schema: {type: string, format: date}}
- {name: date_to, in: query, schema: {type: string, format: date}}
- {name: channel_id, in: query, schema: {type: integer, format: int64}}
- {name: page, in: query, schema: {type: integer, default: 1}}
- {name: page_size, in: query, schema: {type: integer, default: 20, maximum: 100}}
responses: {"200": {description: "list{channel_id,upstream_id,success_count,revenue,cost,profit}(元)"}}
/ops/settle/aggregate:
post:
tags: [settle]
summary: 手动触发消耗日汇总回补(date 缺省=昨日;幂等 UPSERT;运维口径,admin)
requestBody:
content:
application/json:
schema: {type: object, properties: {date: {type: string, format: date, description: 可回补历史日期(明细热窗内)}}}
responses: {"200": {description: "落账行数(账号/通道两表)"}}
components:
securitySchemes:
bearerAuth: {type: http, scheme: bearer, bearerFormat: JWT}
+6
View File
@@ -31,6 +31,7 @@ import (
"go-sms/internal/service/report"
"go-sms/internal/service/router"
"go-sms/internal/service/send"
"go-sms/internal/service/settle"
"go-sms/internal/service/template"
"go-sms/internal/service/uplink"
"go-sms/internal/util"
@@ -233,10 +234,15 @@ func main() {
CMPPCfg: &cfg.Server.CMPP,
// 阶段5收尾(D28):/record/repush 域四端点
Pair: pairSvc,
// S2:结算域(D2=消耗日汇总;充值审核/月结/阶梯/利润随 D3~D5 追加)
Settle: settle.NewService(db),
})
// Day68:运营总览汇总刷新(回补 30 天+60s ticker 增量 UPSERT stats_daily;
// 幂等多实例无害,详见 stats_handler.go StartStatsRefresher)。
v1.StartStatsRefresher(db, a.Lg())
// S2-D2:消耗日汇总滚动重刷(回补 7 天+1h ticker 重刷近 4 天;72h 回执
// 窗内 UNKNOWN 会迁移,幂等 UPSERT 收敛;详见 service/settle/job.go)。
v1.StartSettleAggregateJob(db, cfg.Settle, a.Lg())
// Day 46:外部 HTTP API 提交(SMS_HTTP_1.6;/sms/api 独立协议域,MD5 验签+
// 双桶限流:全局 IP 桶(静态配置)+账号桶(动态 speed_limit);
+5
View File
@@ -101,3 +101,8 @@ rate_limit: # Redis 令牌桶分布式限流(Day 9)
balance: # 资金预扣模式(Day54 R1,评审 docs/review/r1-balance.md)
mode: redis # P1 压测(09-27):mysql→redis——行锁扣款(HDD 单行串行 ~140ms)把受理锁死在 30/s(实测 20:41-20:45);SubmitFast 快路径设计前提=Redis Lua(112μs);对账覆写 5min 兜底
reconcile_interval: 5m # 对账周期(评审约束 ≤5min;MySQL 流水重算覆写 Redis)
settle: # S2 结算域:消耗日汇总滚动重刷(72h 回执窗内 UNKNOWN 会迁移,昨日行非终值须滚动收敛;月结建议 T+4 后生成)
refresh_every: 1h # 重刷周期
refresh_days: 4 # 每轮重刷窗口天数(today-3..today)
backfill_days: 7 # 启动回补天数(明细热窗 5 天内余量)
+112
View File
@@ -0,0 +1,112 @@
# 前端质量门根修 + Dashboard 信息密度重构 人工验收单(2026-11-13 深夜)
> 范围:web/ 前端(FE-Design P0~P3)。设计基线 demo-c-aurora 的 tokens/EP 换肤/布局壳/31 业务页零改动。
## 一、变更清单
| # | 任务 | 文件 | 说明 |
|---|---|---|---|
| P0 | vitest 91/137 红 → **138/138 绿** | `web/vitest.setup.ts`(+7 行) | 根因:vitest(mode=test)不加载 `.env.development` → `request.ts` 顶层 `baseURL=undefined`,spec 内 `vi.stubEnv` 晚于模块求值无效 → msw 全量 unhandled(实测请求裸奔为 `POST /auth/login`);修法=setup 顶部 stubEnv(setupFiles 先于被测模块求值,一处生效)。老机靠 gitignored 本地 env 掩盖,新机首跑暴露 |
| P1 | Dashboard 信息密度重构 | `web/src/views/home/DashboardView.vue`(241→约 470 行重写) | 见下节 |
| P2 | 图标体系统一 | 同上 | 指标卡 emoji(📮✓⚡⚠)+快捷卡符号(✉≡↻◐)→ EP icon;brand ✦ 保留 |
| P3 | 细节打磨 | 同上 + `web/src/styles/shell.scss`(+6 行) | count-up(rAF 600ms/reduced-motion 跳过)、走势 hover 十字线+气泡(纯 SVG)、全局 `:focus-visible` |
| 附 | **Teleport 冷启动竞态修复** | 同上 | `#page-head-extra`(MainLayout 渲染)晚于 Dashboard mount 时(Vue 3.4 无 `<Teleport defer>`)直接挂载 → 后续 patch 崩溃(`TypeError: setText null nodeValue`,fe_error_log 实证 2 条)→ 组件更新全中断(数据已返回但 UI 冻结);修法=v-if 门控延后一拍(**该 bug 旧版同样存在**,新机慢冷启动放大暴露) |
## 二、P1 信息密度(12 维 rubric 审计 54/110「精美的快照」档 → 预计 ~78)
| 变更 | 维度 | 内容 |
|---|---|---|
| 删假数据×3 | D3 | `rateNow=1180+random(160)` 假速率卡、8 条硬编码"示例"通道表、快捷卡死文案("5 条待复核/1,204 条可补") |
| 假速率→真审核卡 | D3/D9 | 「实时速率」→「待人工审核」(接口 `pending_audit_count` 早已返回但 UI 从未消费;点击直跳 /audit) |
| Hero 决策句 | D2/D8 | 四指标实时翻译为一句话判定(ok/warn/err/dim 四态+左光条+直达处置页),数据不可用时诚实降级 |
| 数据脉象 | D10 | live-chip → 「实时·HH:MM:SS / 连接异常·数据截至 / 不可用·点击重试」三态;catch 不再静默吞错 |
| 通道表真数据 | D3/D4 | `channelApi.list` 配置域快照(code/协议/运营商/限速/连接/优先级/状态徽章),表头诚实标注"运行统计待 S5 压测后接入";失败显式重试态 |
| 快捷卡联动 | D9 | desc 接实时指标(12 条待审/3 个预警),热态 amber |
| 7/30 日切换 | D1/D11 | trend(days) mock/后端双端已支持;30d x 轴抽稀 |
## 三、质量门(前端四件 + 实机)
| 项 | 结果 | 证据 |
|---|---|---|
| eslint(--max-warnings 0) | ✅ RC=0 | /tmp/fe-lint3.log |
| vue-tsc --noEmit | ✅ RC=0 | /tmp/fe-tsc3.log |
| vitest | ✅ **138/138**(修复前 91 红) | /tmp/fe-test4.log |
| vite build | ✅ RC=0 | /tmp/fe-build3.log |
| verify-layout(18 断言) | ✅ 全过(Playwright 实渲染,mock 实例 :5174) | 唯一侧栏/双菜单/EP 壳零残留/收起 224→64/汉堡抽屉等 |
| Dashboard 运行时断言(15 项,自建脚本) | ✅ 全过 | hero warn 态+12 待审+3 预警文案、stat-audit=12、stat-speed 已删、脉象"实时·时刻"、快捷卡联动、通道表 3 行真数据+停用徽章、30 日切换、hover 气泡含提交/成功数 |
| 截图矩阵 | ✅ 5 页×双主题重刷 | web/shots/(home 修复后含真实数据态) |
| data-testid 兼容 | ✅ | 全保留(stat-speed 删除,tests/scripts grep 确认无引用) |
## 四、人工走查明细(协议 v3 · 本人执行,逐项勾选)
> 环境:`cd web && VITE_API_MODE=mock npx vite`(:5173,admin/admin123);real 走查另起默认 `.env.development`(:5173→proxy→:8080)。标 ★ 为自动化已覆盖、人工抽验即可;标 ☆ 为必须人眼/人手验证。
### A · Hero 决策句(D2/D8,新增件)
| # | 操作 | 预期 | 级 |
|---|---|---|---|
| A1 | mock 登录 → /home | amber 左光条 + Warning 图标:「今日需要关注:3 个账号余额低于预警线 · 12 条短信待人工审核」,副行「其余指标正常 · 回执成功率 98.3%」 | ★ |
| A2 | 点击 hero | 跳转 /audit(待审优先);Tab 聚焦时 hero 有 teal focus 描边,Enter 可跳 | ☆ |
| A3 | real 模式 /home | 按真实指标呈对应态:ok=teal「平台运行平稳…」/ err=红「回执成功率…低于 95%」 | ☆ |
### B · 四指标卡(P2 图标/P3 count-up)
| # | 操作 | 预期 | 级 |
|---|---|---|---|
| B1 | 刷新 /home 观察数字 | 今日提交从 0 滚动至 1,286,430(600ms,千分位);成功率滚至 98.3% | ☆ |
| B2 | 检查图标 | 四卡均为 EP icon(Promotion/CircleCheck/Bell/Wallet),**全页无 emoji** | ★ |
| B3 | 「待人工审核」卡 | mock=12 条、数值与铃铛 amber;点击整卡 → /audit | ★ |
| B4 | 「余额预警」卡 | mock=3 条、数值红;点击 → /account/list | ★ |
| B5 | 确认假卡已删 | 页面不存在「实时速率」卡(原 1180+random 假数据) | ★ |
| B6 | 系统「减少动态」开启后刷新 | 数字直接显示终值,无滚动 | ☆ |
### C · 数据脉象 chip(D10,page-head 右侧)
| # | 操作 | 预期 | 级 |
|---|---|---|---|
| C1 | 静置观察 | teal 脉动圆点 +「实时 · HH:MM:SS」;悬停出 title;**停留 >60s 时刻自动更新** | ☆ |
| C2 | 点击 chip | 立即刷新,时刻跳变 | ☆ |
| C3 | DevTools → Network Offline → 点 chip | 变 amber「连接异常 · 数据截至 HH:MM:SS」,旧数据保留不闪空;恢复网络后点击回 teal | ☆ |
| C4 | 保持 Offline 刷新整页 | chip 红「指标不可用 · 点击重试」+ hero 同步 err 态;恢复后点击重试回绿 | ☆ |
### D · 发送走势(P3 hover/7-30 日切换)
| # | 操作 | 预期 | 级 |
|---|---|---|---|
| D1 | 点「30 日」 | 图重载不崩溃;real 模式下 30 点、x 轴标签抽稀(≤8 个 + 「今日」恒显);mock 仅 7 点属正常(mock 数据源限制) | ★ |
| D2 | 鼠标在图上横移 | teal 虚线十字 + 放大圆点 + 玻璃气泡(日期 / 提交 x,xxx · 成功 x,xxx);气泡近右缘时自动左翻不裁切 | ★ |
| D3 | 移出图表 | 十字线与气泡消失 | ☆ |
### E · 快捷操作(D9 联动)
| # | 操作 | 预期 | 级 |
|---|---|---|---|
| E1 | 看「待人工审核」desc | mock:「12 条待审,点击进入审核中心」+ 图标底 amber;随 C3 断网联动显示 | ★ |
| E2 | 看「余额预警」desc | mock:「3 个账号低于预警线」 | ★ |
| E3 | 看「失败补推」desc | 诚实文案「按批次 / 手机号查询重推」(**无编造数字**) | ☆ |
| E4 | 四项逐一点击/Enter | 分别跳 /sms/batch、/audit、/record/repush、/account/list | ☆ |
### F · 通道配置快照(D3/D4 真数据)
| # | 操作 | 预期 | 级 |
|---|---|---|---|
| F1 | mock 表内容 | 3 行:CM-001 移动全国(CMPP·violet)/HX-201 联信HTTP(HTTP·warn)/DX-301 电信SGIP(SGIP)且状态=**停用红徽章**;运营商列「移动 / 联通 / 电信」映射正确 | ★ |
| F2 | 表头 small | 「N 条 · 配置域数据 · 运行统计待 S5 压测后接入」诚实标注;右上 ch-refresh 可刷新 | ★ |
| F3 | real 模式 | 与「通道配置」页列表一致(配置域字段);管理员视角可用 | ☆ |
| F4 | 停网关后点 ch-refresh | 显式「通道列表加载失败 · 重试」,重试链接可用 | ☆ |
| F5 | 窗口缩至 <1100px | 表格横向滚动,不挤压布局 | ☆ |
### G · 布局与主题回归(verify-layout 已覆盖,抽验)
| # | 操作 | 预期 | 级 |
|---|---|---|---|
| G1 | 侧栏收起/展开 | 224↔64;≤900px 汉堡抽屉正常 | ★ |
| G2 | 暗/亮主题切换 | hero 光条、amber warn、气泡、focus 描边在**亮色**下对比度均可读 | ☆ |
| G3 | brand 区 | 「✦ go-sms / AURORA CONSOLE」不变;菜单 icon 不变 | ★ |
| G4 | Tab 全键盘走查 | hero→指标卡→radio→刷新→快捷卡…,focus-visible teal 描边全程可见 | ☆ |
### H · 双模式与回归面
| # | 操作 | 预期 | 级 |
|---|---|---|---|
| H1 | mock 全流程 | A~G 全部在 mock 模式通过 | — |
| H2 | real 全流程 | 真网关登录后指标/通道/趋势为真实数;customer 角色登录 /home 无 JS 报错(后端按角色返回) | ☆ |
| H3 | 浏览器 Console | 全程无 error(fe_error_log 无新增 VueHandler 记录) | ☆ |
| H4 | 旁证回归 | account / channel / sms-batch / sms-downlink-detail 四页与旧版无差异(本次未改动,截图已重刷) | ☆ |
## 五、环境遗留(非本次范围,已知悉)
- pnpm-lock.yaml 曾被 pnpm 自动 install 重排 → 已 `git checkout` 回滚(最小变更纪律);**新机跑 pnpm 命令会自动 install 且可能改 lockfile,建议后续统一 `pnpm install --frozen-lockfile`**。
- Playwright 浏览器新机首装:官方 CDN 停滞 → `PLAYWRIGHT_DOWNLOAD_HOST=https://cdn.npmmirror.com/binaries/playwright` 镜像 + apt 系统库(libnspr4/libnss3 等)。
+2 -1
View File
@@ -11,7 +11,8 @@
| 3 | storage 命名归一(b499b66) | ✅ | minio.go→s3.go/S3Store/NewS3(RustFS Phase C 收口) |
| 4 | audit_mode=2 文案校准 | ✅ | 「2自动拒绝」→「2自动审核(黑词命中拒/未命中过)」对齐 audit.ModeAuto 实义;后端 2 处+openapi 1 处+测试措辞;account/audit -race 绿 |
| 5 | gofmt 存量清零(e9b70ea) | ✅ | POC 遗留 20 文件全清;`gofmt -l` 全仓零输出 |
| 6 | 24h 稳定性门槛 | ⏳ **在途(维持原时间)** | 11-13 17:55 起计,**期满=11-14 17:55 不变**;期内 21:33 宿主主动有序重启(当日内核升级 6.12.116 后二次重启,`last`=有序 shutdown 非崩溃)=**已知事件如实记录,不判失败**(dmesg 已随重启清零,核验以重启后为准);九中间件 restart policy 自愈全 healthy,gateway 重驻(:8080,md5 比对一致);核验口径=dmesg 崩溃 0+容器重启 0+gateway 驻留,回填终判 |
| 6 | 24h 稳定性门槛 | ✅ **终判通过(2026-11-14 18:02 期满核验)** | 11-13 17:55 起计,期满 11-14 17:55;期内 21:33 宿主主动有序重启(内核升级,`last`=有序 shutdown 非崩溃)=已知事件不判失败。**期满核验三项全绿**:①dmesg 崩溃计数(segfault/sigill/error 25)=0(重启清零后全窗零新增);②九中间件 Up 20 hours 全 healthy(自愈拉起后窗内零重启);③gateway 驻留同 PID 53153(11-13 22:15 重驻起连续 19h47m)+/health ok+md5 比对一致(ecf71db6…)。**S5 压测基线前置资格确认** |
| — | ↑期满前基线预检(S2-D1 顺带,09:57) | 📌 对照留痕 | dmesg 崩溃计数(segfault/sigill/error 25)=**0**;九容器 **Up 12 hours** 全 healthy(窗内零重启);gateway 驻留 PID 53153 etime 11:42:01(昨晚重驻以来连续)。17:55 终验以此为对照 → 三项维持,终判通过(见上行) |
## 二、S1 泳道出口判定(对齐《重建计划》S1 行:「B 层逐域搬运改造+迁移链落地;验收=全包等价 -race 绿」)
+45
View File
@@ -0,0 +1,45 @@
# S2-D1 表设计评审 + 迁移 v20 + 契约草案 人工验收单(2026-11-14)
> 前置:S1 泳道收官(s1-b-closeout.md,24h 门槛在途 11-14 17:55 期满回填)。
> 本单覆盖 S2 结算域 D1:六项表设计裁决定稿 + v20_settle_domain 落地 + openapi 契约草案。
## 一、交付物
| # | 任务 | 结果 | 证据 |
|---|---|---|---|
| 1 | **表设计评审纪要**(六项裁决 R1~R6) | ✅ | `docs/review/s2-settle-table-review.md`;R1 计价模型=出账时刻计价(用户 2026-11-14 拍板:明细 Fee 保持片数、send 域零改动) |
| 2 | **迁移 v20_settle_domain** | ✅ | migrations.go 末块:billing_consume_log +unknown_count/updated_at;account_user +rebate_rate;DROP stats_user_daily(R2 单一事实源);新表 settle_ladder;casbin 补 ops settle:write / customer settle:read(NOT EXISTS 逐条守卫) |
| 3 | **实体同步** | ✅ | entity/billing.go(补列+SettleLadder+SettleCustomer 状态注释对齐 0草稿/1已确认/2已结账);account.go(RebateRate);system.go(StatsUserDaily 删除留裁决注记);base.go All() 39 实体 |
| 4 | **openapi 契约草案 v1.3.0** | ✅ | 20 个新端点(billing 5/settle 15:充值订单审核/消耗查询/下家/上家月结/阶梯/利润/手动汇总);js-yaml 解析通过(84 paths);版本 1.2.0→1.3.0 |
| 5 | **迁移测试更新** | ✅ | base_test.go:末七窗口 v13..v19→v14..v20,终版断言 v20,新增 v20 五项断言;v13 断言随窗口右移移除(注记留痕) |
## 二、门禁(七件套后端件)
| 项 | 结果 |
|---|---|
| go vet ./... | ✅ RC=0 |
| go test -race ./...(全量) | ✅ 全绿(回填于本单尾部) |
| golangci-lint v2.1.6 | ✅ 0 issues |
| 迁移单测(sqlite 末七两遍幂等) | ✅ TestMigrations_IdempotentAndVersioned 含 v20 断言通过 |
| openapi YAML 解析 | ✅ js-yaml 84 paths |
| gen-dict/-check | ✅ 未新增 x-isc-dict,dict.ts 无需再生成 |
## 三、设计要点留痕
1. **不触碰已收官 send 域**(R1):计价全部收拢 D4 出账引擎 settle/price.go(PriceAt 时间线回溯+阶梯落档);条→元换算全链单点(R6)。
2. **v20 加列走显式 SQL+HasColumn 守卫、空库走 HasTable 守卫 AutoMigrate 整表**——glebarez SQLite 下 entity 加字段触发表 diff 重建抹索引(v16/v17 教训,三条路径收敛:全量新库 v0 直含/存量库 ALTER/末七窗口空库建表)。
3. **零新增聚合索引**:通道日汇总复用 v16 `idx_detail_channel_created(channel_id, created_at)`。
4. **init_schema.sql 不动**(Day11 基线参考,权威=migrate 链,v16/v17 演进均未回写,维持惯例)。
5. **stats_channel_daily 零 schema 变更**(unknown_count/cost_total 原有;grain=通道×天,不加 business——通道价格体系不分业务,视频走独立通道)。
6. **casbin 策略随 v20 逐条 NOT EXISTS 守卫种入**(v5 的 n>0 整体跳过守卫不适用于增量)。
## 四、验收结论
**S2-D1 通过。** D2(消耗日汇总引擎)开工前置=本单归档+CHANGELOG+进度回填。
## 五、附:真库验证(dev MySQL 13306,2026-11-14)
- `cmd/migrate version` v19_longsms_pending → `up` → **v20_settle_domain**(存量库 ALTER 路径实测通过);
- information_schema 核验:billing_consume_log unknown_count/updated_at 两列 ✓、account_user.rebate_rate ✓、settle_ladder 建表 ✓、stats_user_daily 已 DROP ✓、casbin_rule 新增 ops settle:write / customer settle:read ✓;
- 集成测试:TestMySQL_AutoMigrate 39 表 PASS;Casbin 集成 PASS(新策略不破坏 enforcer 加载);
- `go test -race ./...` 全量 38 包 ok,零 FAIL。
+42
View File
@@ -0,0 +1,42 @@
# S2-D2 消耗日汇总引擎 人工验收单(2026-11-14)
> 前置:s2-d1.md(表设计+v20+契约)。本单覆盖 D2:settle 域首批业务代码——
> 消耗日汇总引擎(结算域事实源)+ 两端点 + 后台滚动重刷 job。
## 一、交付物
| # | 任务 | 结果 | 证据 |
|---|---|---|---|
| 1 | **settle/consume.go**(聚合引擎) | ✅ | `AggregateDay`:账号×业务→billing_consume_log、通道→stats_channel_daily,一条 GROUP BY(计 SUM(status=N) 计数+Σfee 条)+OnConflict UPSERT(复合 uk 覆盖更新);`[lo,hi)` 半开窗规避 date() 方言差;cost_total 不写(R1);`ListConsume` 分页/过滤/时间窗按天归一(零点行不被带时刻参数误滤) |
| 2 | **settle/job.go**(滚动重刷 job) | ✅ | **对 D1 计划的关键修正**:单日 T+1 落账会在 72h 回执窗内失真(UNKNOWN→成功迁移),改为**周期重刷近 4 天**滚动收敛;启动回补 7 天;配置零值兜底(1h/4/7);失败 Warn 不中断+errors 计数器,幂等下轮自愈 |
| 3 | **settle_handler.go**(两端点) | ✅ | `GET /billing/consume`(JWT+customer/group 强制收窄自身,越权带参覆盖不报错)+ `POST /ops/settle/aggregate`(settle:write 手动回补);D3~D5 端点随任务在本文件追加 |
| 4 | **装配** | ✅ | Deps.Settle 字段+registerSettleRoutes;`v1.StartSettleAggregateJob`(照 StartStatsRefresher v1 层包装模式);gateway main 挂载于 StatsRefresher 之后;config.Settle 段(1h/4/7)+config.dev.yaml 注释口径;metrics 两件(`go_sms_settle_aggregate_rows_total{kind}`/`errors_total`) |
| 5 | **单测** | ✅ | consume_test.go 4 件(正确性多账号×双业务×五状态逐行断言/幂等+跨天边界/**UNKNOWN 状态迁移重刷收敛**/查询过滤分页)+ settle_handler_test.go 2 件(admin 全量 vs customer 收窄带参越权/手动回补落账+坏日期 4xx) |
## 二、门禁(七件套后端件)
| 项 | 结果 |
|---|---|
| go vet ./... | ✅ RC=0 |
| go test -race ./...(全量) | ✅ **39 包 ok 零 FAIL**(新增 settle 包) |
| golangci-lint v2.1.6 | ✅ 0 issues |
| 集成 | ✅ 沿用 schema/casbin(D1 已过;D2 无新集成面,真库验证见 §三) |
## 三、dev 实机验证(真 MySQL,2026-11-14)
1. **部署串行铁律**:make gw-stop→gw-start 三轮(重驻/状态迁移验证/清理后),每轮 /health ok+**md5 比对一致**(8fd2dfbc…)。
2. **端到端落账**:SQL 直插 3 条今日明细(账号 1×2:成功+未知/账号 100×1 成功,通道 1)→启动回补自动聚合 → billing_consume_log 2 行(1:sms 2/1/0/1/fee3.0;100:sms 1/1/0/0/fee2.5)+ stats_channel_daily 1 行(3/2/1/cost_total=0)——**逐列与 sqlite 单测期望一致**;metrics rows{account}=2/{channel}=1。
3. **滚动收敛实证**:UPDATE 明细 status 4→2 → 重启重刷 → 账号 1 行 **success 1→2/unknown 1→0**——72h 回执窗迁移收敛语义在真库闭环。
4. **指标暴露**:/metrics 出现 go_sms_settle_aggregate_errors_total=0(HELP/TYPE 正常)。
5. **清理**:测试明细 3 条+两表当日行全删(避免僵尸汇总行——热窗内明细不删的边界已文档化),最终干净重驻。
## 四、口径与边界留痕
- **滚动重刷窗 4 天**=72h 回执窗+当天增量;月结建议 T+4 后生成(D4 文档化;generate 幂等重算兜底);
- 汇总行不随明细删除回退(热窗内明细不删;S4 分区清退后历史行冻结);
- 通道维度不含 business/Σfee(通道价格体系不分业务;上家账单按 billing_mode 条数口径);
- job 为 ticker 型(照 StatsRefresher),cronx 保留给已有 alarm/健康巡检用途。
## 五、验收结论
**S2-D2 通过。** D3(充值审核流)开工前置=本单归档+CHANGELOG+回填+提交。
+52
View File
@@ -0,0 +1,52 @@
# S2 结算域·表设计评审纪要(D1,2026-11-14)
> 评审输入:《Go-sms-重建计划.md》S2 行(5 工作日,D 层结算域后端全量,出口=结算单测+对账差异=0)/
> 《Go-sms-需求分析.md》§2.6 计费与结算(下家结算·上家结算·消耗日志·充值日志·利润分析,P1)/
> 《Go-sms-重建设计规范.md》性能三律与幂等三锚 / 代码实证(结算 5 表实体自 v0 已建且业务代码零使用、
> StatsUserDaily/StatsChannelDaily 同为零写入方空壳、明细 Fee=片数非金额、v16 已建 idx_detail_channel_created)。
## 一、六项裁决
| # | 决策点 | 裁决 | 依据 |
|---|---|---|---|
| **R1** | 计价模型 | **出账时刻计价**:明细 Fee 保持片数语义(send 域零改动);结算金额=Σ(日成功条数×生效单价),按 AccountPrice/ChannelPrice 时间线(EffectiveAt≤当日取最近)+阶梯档推导 | 用户 2026-11-14 拍板。与需求「分时单价与结算联动」一致;不触碰已收官域;调价可追溯;Fee≡片数口径(Day70)不动摇 |
| **R2** | 消耗事实源 | **billing_consume_log(账号×业务×天)+ stats_channel_daily(通道×天)为事实源;stats_user_daily 废弃**(v20 DROP,实体删除,All() 移除) | 两表同粒度双空壳;单一事实源纪律,双写必漂移;表名即域归属 |
| **R3** | 充值双通道 | **保留** `/accounts/:id/recharge` 即时到账(语义=已确认付款快捷入账)+ **新增** BillingOrder 审核流(0待→1到账/2失败;confirm=状态 CAS+余额自增 count+流水 ref_id=order_no 同事务) | 兼容存量 API 与权限测试;「付款审核确认」为需求 §2.6 明示项 |
| **R4** | 返点模型 | account_user.rebate_rate decimal(5,4)(v20 加列;小数表示 0.1200=12%,0=无返点);返点额=**直线下级**当月结算金额×rate;**历史不重算**(换上级只影响未来) | 树+Path 基座已备;先落地单级分成,层级分成留扩展 |
| **R5** | 阶梯载体 | 新表 **settle_ladder**(owner_type=account/upstream × owner_id × tier_from 唯一;tier_from=档位下限含,0=首档;出账按月成功总量落档覆写时间线价) | 独立表可审计可单测(「阶梯结算单测」为显式验收项);不塞 JSON |
| **R6** | 单位口径 | 余额/预扣/明细 Fee/fee_total=**条**;BillingOrder.Count=条、Amount=元;结算单/利润/单价=**元**;条→元换算**只发生在出账引擎**(settle/price.go)一处 | 消除 balance(条)与 decimal(元)的隐性错位;单点换算单点审计 |
## 二、v20_settle_domain 迁移范围(已实现)
1. billing_consume_log 补 `unknown_count INT`(上家 success_unknown 口径依赖)+ `updated_at DATETIME`(UPSERT 重跑痕迹);
2. account_user 补 `rebate_rate DECIMAL(5,4)`;
3. DROP stats_user_daily(空库路径 v0 已不再建它,DROP IF EXISTS 双方言幂等);
4. 新表 settle_ladder;
5. casbin 补策略:ops settle:write / customer settle:read(逐条 NOT EXISTS 守卫;单块重放路径 HasTable 守卫)。
加列走显式 SQL+HasColumn 守卫、空库走 HasTable 守卫 AutoMigrate 整表(v16/v17 教训:glebarez 下 entity 加字段触发表 diff 重建抹索引)。
**不需要**新聚合索引:通道维度日汇总复用 v16 `idx_detail_channel_created(channel_id, created_at)`。
**不改** init_schema.sql(Day11 基线参考、权威=migrate 链,v16/v17 演进均未回写,维持惯例)。
`stats_channel_daily` 零 schema 变更(unknown_count/cost_total 原有;grain=通道×天,不加 business——通道价格体系本身不分业务,视频走独立通道)。
## 三、状态机与语义定稿
- **充值订单**:pay_status 0待确认→1已到账/2失败;confirm 事务=UPDATE ... WHERE pay_status=0(行数=0 即 409)+balance+=count 原子自增+流水(ref_id=order_no);驳回不涉余额。
- **结算单(下家/上家同构)**:status 0草稿→1已确认(人工锁账,拒静默重算)→2已结账(写 settle_record,终态);generate 幂等=uk(account|upstream, period)+OnConflict 更新重算,status=2 拒。
- **上家计费口径**:按通道 `billing_mode`——success(仅成功)/success_unknown(成功+未知)/all(全部提交);UNKNOWN 72h 窗语义(部分段事实送达)与 success_unknown 口径天然对齐。
- **日汇总 job**:T+1 01:05 核算昨日+启动回补 7 天,幂等 UPSERT(明细热窗 5 天→月结必须走日汇总,job 必须在明细出窗前落账——整域地基,D2 最先做)。
## 四、任务映射(D2-D5)
| 任务 | 落点 |
|---|---|
| D2 消耗日汇总引擎 | settle/consume.go+job.go(照 StartStatsRefresher 幂等模式)+/billing/consume+/ops/settle/aggregate+Settle 配置段+job 指标 |
| D3 充值审核流 | settle/recharge.go+/billing/orders 族(R3 事务语义) |
| D4 出账引擎+阶梯 | settle/price.go(PriceAt+阶梯落档,R1/R6 唯一换算点)+bill.go+/settle 族(生成/确认/结账/导出) |
| D5 利润/返点/对账 | profit.go(树聚合,R4)+reconcile.go+cmd/reconcile settle-check(三方 diff=0=S2 出口) |
## 五、遗留与显式不承诺
- est_balance(通道估算余额 2h 刷新,需求 §5.3)语义依赖「校正余额」录入通道,本期字段保留不实现,验收单如实标注;
- 层级返点(多级分成)、月结自动生成调度(手动 generate 先行)留后续;
- 阶梯与时间线价并存时:**有阶梯档则整月单价按落档价覆写**(不做分档混合计价)——单测覆盖边界(恰好落档/跨档/无阶梯回退)。
+8
View File
@@ -29,6 +29,7 @@ import (
"go-sms/internal/service/report"
"go-sms/internal/service/router"
"go-sms/internal/service/send"
"go-sms/internal/service/settle"
"go-sms/internal/service/template"
)
@@ -64,6 +65,9 @@ type Deps struct {
// CMPPCfg Day 62:CMPP 服务端配置(系统默认配额+端口;GET api-config 的
// cmpp_access 块数据源;nil=CMPP 未启用,响应不带该块)。
CMPPCfg *config.CMPPServer
// Settle S2:结算域(消耗日汇总查询/手动回补;充值订单/月结/阶梯/利润
// 随 D3~D5 追加;nil=不注册,前端 404 优于半可用)。
Settle *settle.Service
}
// Register 注册 v1 路由组。
@@ -189,6 +193,10 @@ func Register(rg *gin.RouterGroup, deps Deps) {
if deps.DB != nil {
registerStatsRoutes(protected, deps.DB)
}
// S2:结算域(D2 消耗日汇总两端点;D3~D5 端点随任务追加,见 settle_handler.go)。
if deps.Settle != nil {
registerSettleRoutes(protected, deps)
}
// 阶段5收尾(D28):回执重推域四端点(回执分页/重推受理/挂起明细/手动配对;
// 服务依赖 Billing/PushSink,装配见 cmd/gateway)。
if deps.Pair != nil {
+114
View File
@@ -0,0 +1,114 @@
// settle_handler.go S2:结算域端点。D2 先挂两件——消耗日汇总查询(/billing/
// consume)与手动回补(/ops/settle/aggregate);D3(充值订单审核族)/D4(月结
// 单/阶梯/导出)/D5(利润/对账)随任务推进在本文件追加,契约见 openapi v1.3.0。
package v1
import (
"strconv"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"gorm.io/gorm"
"go-sms/internal/config"
"go-sms/internal/middleware"
errs "go-sms/internal/pkg/errors"
"go-sms/internal/pkg/response"
"go-sms/internal/service/settle"
)
// settleConsumeDefaultDays 消耗查询缺省窗口(近 7 天,对齐 stats trend 口径)。
const settleConsumeDefaultDays = 7
func registerSettleRoutes(protected *gin.RouterGroup, deps Deps) {
h := &settleHandler{svc: deps.Settle}
// 消耗日汇总查询:JWT 即可(admin/ops/service 全量;group/customer 仅自己,
// scope 收窄在 handler 内做——与 stats 域同口径,casbin customer settle:read
// 策略为 v20 所种,细分资源门按需后挂)。
protected.GET("/billing/consume", h.consumeList)
// 手动触发回补(运维口径;settle:write)。
protected.POST("/ops/settle/aggregate",
middleware.RequirePermission(deps.Perm, "settle", "write"), h.aggregate)
}
// StartSettleAggregateJob v1 层装配入口(照 StartStatsRefresher 模式,仅
// gateway 调用;测试/迁移工具不启)。
func StartSettleAggregateJob(db *gorm.DB, cfg config.Settle, log *zap.Logger) {
settle.StartAggregateJob(db, cfg.RefreshEvery, cfg.RefreshDays, cfg.BackfillDays, log)
}
type settleHandler struct{ svc *settle.Service }
// consumeList GET /billing/consume:账号×业务×天 消耗事实源查询。
func (h *settleHandler) consumeList(c *gin.Context) {
claims := statsClaims(c) // protected 组内恒在;复用 stats 域提取器
q := settle.ConsumeQuery{Page: 1, PageSize: 20}
if v, err := strconv.ParseInt(c.Query("account_id"), 10, 64); err == nil && v > 0 {
q.AccountID = v
}
q.Business = c.Query("business")
now := time.Now()
q.To = now
q.From = now.AddDate(0, 0, -(settleConsumeDefaultDays - 1))
if s := c.Query("date_from"); s != "" {
d, err := time.ParseInLocation("2006-01-02", s, time.Local)
if err != nil {
response.Error(c, errs.InvalidParam.WithMsg("date_from 须为 YYYY-MM-DD"))
return
}
q.From = d
}
if s := c.Query("date_to"); s != "" {
d, err := time.ParseInLocation("2006-01-02", s, time.Local)
if err != nil {
response.Error(c, errs.InvalidParam.WithMsg("date_to 须为 YYYY-MM-DD"))
return
}
q.To = d
}
if v, err := strconv.Atoi(c.Query("page")); err == nil && v > 0 {
q.Page = v
}
if v, err := strconv.Atoi(c.Query("page_size")); err == nil && v > 0 {
q.PageSize = v
}
// 非平台角色强制收窄到自身账号(带参越权请求直接覆盖,不报错——stats 同口径)。
if claims != nil && !statsIsPlatform(c) {
q.AccountID = claims.AccountID
}
list, total, err := h.svc.ListConsume(c.Request.Context(), q)
if err != nil {
bizResp(c, err)
return
}
response.Success(c, gin.H{"total": total, "list": list})
}
// aggregate POST /ops/settle/aggregate:date 缺省=昨日;幂等 UPSERT 可重入,
// 返回两表落账行数(只回补单日——历史区间回补走重启 job 的 backfill 或逐日调用)。
func (h *settleHandler) aggregate(c *gin.Context) {
var req struct {
Date string `json:"date"`
}
_ = c.ShouldBindJSON(&req)
day := time.Now().AddDate(0, 0, -1)
if req.Date != "" {
d, err := time.ParseInLocation("2006-01-02", req.Date, time.Local)
if err != nil {
response.Error(c, errs.InvalidParam.WithMsg("date 须为 YYYY-MM-DD"))
return
}
day = d
}
accountRows, channelRows, err := h.svc.AggregateDay(c.Request.Context(), day)
if err != nil {
bizResp(c, err)
return
}
response.Success(c, gin.H{
"day": day.Format("2006-01-02"),
"account_rows": accountRows,
"channel_rows": channelRows,
})
}
+157
View File
@@ -0,0 +1,157 @@
package v1
// settle_handler_test.go S2-D2:消耗日汇总两端点——customer scope 强制收窄
// (带参越权请求覆盖不报错,stats 同口径)+手动回补落账断言。
// gin TestMode + sqlite;claims 由中间件注入模拟(stats_handler_test 同款)。
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/middleware"
"go-sms/internal/model/entity"
"go-sms/internal/service/settle"
)
// newSettleRouter 种子:账号 1/100 今日各 1 条成功明细(通道 1);返回注入器。
func newSettleRouter(t *testing.T) (*gin.Engine, *gorm.DB, func(*middleware.Claims)) {
t.Helper()
gin.SetMode(gin.TestMode)
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if s, e := db.DB(); e == nil {
s.SetMaxOpenConns(1)
}
if err := db.AutoMigrate(&entity.MessageDetail{}, &entity.BillingConsumeLog{},
&entity.StatsChannelDaily{}); err != nil {
t.Fatal(err)
}
now := time.Now()
details := []entity.MessageDetail{
{SnowflakeModel: entity.SnowflakeModel{ID: 9100000001, CreatedAt: now},
TaskID: 800001, AccountID: 1, ChannelID: 1, Mobile: "13000000001",
Content: "t", Status: 2, Business: "sms", Fee: 1.5},
{SnowflakeModel: entity.SnowflakeModel{ID: 9100000002, CreatedAt: now},
TaskID: 800002, AccountID: 100, ChannelID: 1, Mobile: "13000000002",
Content: "t", Status: 2, Business: "sms", Fee: 2.5},
}
if err := db.Create(&details).Error; err != nil {
t.Fatal(err)
}
rg := gin.New()
api := rg.Group("/api/v1")
var claims *middleware.Claims
api.Use(func(c *gin.Context) {
if claims != nil {
c.Set(middleware.ContextKeyClaims, claims)
}
})
registerSettleRoutes(api, Deps{Settle: settle.NewService(db)})
return rg, db, func(cl *middleware.Claims) { claims = cl }
}
// TestSettleConsume_AdminSeesAll admin 全量;customer 强制收窄(带参越权覆盖)。
func TestSettleConsume_Scope(t *testing.T) {
rg, db, setClaims := newSettleRouter(t)
// 预落账(查询读事实源,不直查明细)。
svc := settle.NewService(db)
if _, _, err := svc.AggregateDay(t.Context(), time.Now()); err != nil {
t.Fatal(err)
}
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
w := httptest.NewRecorder()
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/billing/consume", nil))
if w.Code != 200 {
t.Fatalf("admin status=%d body=%s", w.Code, w.Body.String())
}
var res struct {
Data struct {
Total int64 `json:"total"`
List []entity.BillingConsumeLog `json:"list"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
t.Fatal(err)
}
if res.Data.Total != 2 {
t.Fatalf("admin 应见全量 2 行,got %d", res.Data.Total)
}
// customer 带参越权(account_id=1):应被覆盖为自身 100。
setClaims(&middleware.Claims{AccountID: 100, Username: "cust", Roles: []string{"customer"}})
w = httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/billing/consume?account_id=1", nil)
rg.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("customer status=%d body=%s", w.Code, w.Body.String())
}
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
t.Fatal(err)
}
if res.Data.Total != 1 || len(res.Data.List) != 1 || res.Data.List[0].AccountID != 100 {
t.Fatalf("customer 应强制收窄到自身 100: total=%d list=%v", res.Data.Total, res.Data.List)
}
}
// TestSettleAggregate_Manual 手动回补:返回行数+落库断言;坏日期 4xx。
func TestSettleAggregate_Manual(t *testing.T) {
rg, db, setClaims := newSettleRouter(t)
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
w := httptest.NewRecorder()
rg.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/ops/settle/aggregate", nil))
if w.Code != 200 {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
var res struct {
Data struct {
Day string `json:"day"`
AccountRows int64 `json:"account_rows"`
ChannelRows int64 `json:"channel_rows"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
t.Fatal(err)
}
// 缺省=昨日:种子明细是今天 → 0 行也合法;显式补今天断言 2/1。
w = httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/ops/settle/aggregate",
strings.NewReader(`{"date":"`+time.Now().Format("2006-01-02")+`"}`))
req.Header.Set("Content-Type", "application/json")
rg.ServeHTTP(w, req)
if w.Code != 200 {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
t.Fatal(err)
}
if res.Data.AccountRows != 2 || res.Data.ChannelRows != 1 {
t.Fatalf("今日回补应 account_rows=2/channel_rows=1: %+v", res.Data)
}
var n int64
db.Model(&entity.BillingConsumeLog{}).Count(&n)
if n != 2 {
t.Fatalf("billing_consume_log 落账=%d 期望 2", n)
}
// 坏日期参数。
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/api/v1/ops/settle/aggregate",
strings.NewReader(`{"date":"2026/11/14"}`))
req.Header.Set("Content-Type", "application/json")
rg.ServeHTTP(w, req)
if w.Code == 200 {
t.Fatalf("坏日期应 4xx,got %d body=%s", w.Code, w.Body.String())
}
}
+10
View File
@@ -25,6 +25,16 @@ type Config struct {
RateLimit RateLimit `mapstructure:"rate_limit"`
HotReload HotReload `mapstructure:"hot_reload"`
Balance Balance `mapstructure:"balance"`
Settle Settle `mapstructure:"settle"`
}
// Settle 结算域配置(S2):消耗日汇总滚动重刷模型——周期重刷近 N 天
// (默认 4 天:72h 回执窗内明细状态会迁移 UNKNOWN→成功/失败,昨日行非终值,
// 须滚动收敛;月结建议 T+4 后生成)。零值兜底见 service/settle/job.go。
type Settle struct {
RefreshEvery time.Duration `mapstructure:"refresh_every"` // 重刷周期(默认 1h)
RefreshDays int `mapstructure:"refresh_days"` // 每轮重刷天数窗(默认 4=today-3..today)
BackfillDays int `mapstructure:"backfill_days"` // 启动回补天数(默认 7,明细热窗 5 天内余量)
}
// Balance 资金预扣模式(Day54 R1,评审 docs/review/r1-balance.md):
+1
View File
@@ -18,6 +18,7 @@ type AccountUser struct {
IPBind string `gorm:"size:256" json:"ip_bind"`
Balance int64 `json:"balance"`
CreditBalance int64 `json:"credit_balance"`
RebateRate float64 `gorm:"type:decimal(5,4);default:0" json:"rebate_rate"` // v20:代理返点率(小数,0.1200=12%;0=无返点;上级对直线下级结算额的分成)
SvcTeam string `gorm:"size:64" json:"svc_team"`
ExpiredAt *time.Time `json:"expired_at"`
LastLoginAt *time.Time `json:"last_login_at"`
+2 -2
View File
@@ -46,8 +46,8 @@ func All() []any {
// 计费与结算(5)
&BillingOrder{}, &BillingConsumeLog{}, &SettleCustomer{}, &SettleUpstream{},
&SettleRecord{},
// 统计与运维(8)
&StatsUserDaily{}, &StatsChannelDaily{}, &SystemConfig{}, &SystemAlertRule{},
// 统计与运维(7)
&StatsChannelDaily{}, &SystemConfig{}, &SystemAlertRule{},
&SystemLoginLog{}, &SystemOperateLog{}, &SystemErrorCode{}, &FeErrorLog{},
}
}
+24 -5
View File
@@ -19,7 +19,9 @@ type BillingOrder struct {
func (BillingOrder) TableName() string { return "billing_order" }
// BillingConsumeLog 消耗日志(按账号/业务/天)。
// BillingConsumeLog 消耗日志(按账号/业务/天)——S2 起为结算域消耗事实源
// (R2 裁决:stats_user_daily 同粒度双空壳废弃,单一事实源归本表);
// 日汇总 job T+1 凌晨幂等 UPSERT(明细热窗仅 5 天,月结必须走本表)。
type BillingConsumeLog struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"`
AccountID int64 `gorm:"uniqueIndex:uk_account_date,priority:1" json:"account_id"`
@@ -28,21 +30,24 @@ type BillingConsumeLog struct {
SubmitCount int `json:"submit_count"`
SuccessCount int `json:"success_count"`
FailCount int `json:"fail_count"`
FeeTotal float64 `gorm:"type:decimal(12,4)" json:"fee_total"`
UnknownCount int `json:"unknown_count"` // v20:未知(72h 窗后仍 UNKNOWN)——上家 success_unknown 口径依赖
FeeTotal float64 `gorm:"type:decimal(12,4)" json:"fee_total"` // 单位=条(=Σ明细 fee,片数口径 Day70)
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` // v20:UPSERT 重跑痕迹
}
func (BillingConsumeLog) TableName() string { return "billing_consume_log" }
// SettleCustomer 下家(客户)月度结算单。
// SettleCustomer 下家(客户)月度结算单——金额=Σ(日成功条数×生效单价),
// 出账时刻按价格时间线推导(R1 裁决:明细 Fee 保持片数,不在受理侧金额化)。
type SettleCustomer struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"`
SettleNo string `gorm:"size:32" json:"settle_no"`
AccountID int64 `gorm:"uniqueIndex:uk_account_period,priority:1" json:"account_id"`
Period string `gorm:"size:7;uniqueIndex:uk_account_period,priority:2;index:idx_period" json:"period"`
SuccessCount int64 `json:"success_count"`
Amount float64 `gorm:"type:decimal(12,2)" json:"amount"`
Status int8 `gorm:"default:0" json:"status"`
Amount float64 `gorm:"type:decimal(12,2)" json:"amount"` // 应收(元)
Status int8 `gorm:"default:0" json:"status"` // 0草稿 1已确认 2已结账(已结拒重算)
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}
@@ -76,3 +81,17 @@ type SettleRecord struct {
}
func (SettleRecord) TableName() string { return "settle_record" }
// SettleLadder 阶梯价档位(S2·R5:出账时按月成功总量落档,档内单价覆写
// 时间线价;tier_from=档位下限(含),0=首档,上一档与下一档的 from 界定区间;
// owner_type=account(下家应收)/upstream(上家成本)两类锚点各自配档)。
type SettleLadder struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"`
OwnerType string `gorm:"size:8;uniqueIndex:uk_owner_tier,priority:1" json:"owner_type"` // account/upstream
OwnerID int64 `gorm:"uniqueIndex:uk_owner_tier,priority:2" json:"owner_id"`
TierFrom int64 `gorm:"uniqueIndex:uk_owner_tier,priority:3" json:"tier_from"` // 档位下限(含,条)
Price float64 `gorm:"type:decimal(10,4)" json:"price"` // 该档单价(元/条)
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}
func (SettleLadder) TableName() string { return "settle_ladder" }
+3 -14
View File
@@ -2,20 +2,9 @@ package entity
import "time"
// StatsUserDaily 用户日统计(偶数整点刷新)。
type StatsUserDaily struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"`
AccountID int64 `gorm:"uniqueIndex:uk_account_date,priority:1" json:"account_id"`
StatDate time.Time `gorm:"type:date;uniqueIndex:uk_account_date,priority:2;index:idx_date" json:"stat_date"`
SubmitCount int `json:"submit_count"`
SuccessCount int `json:"success_count"`
FailCount int `json:"fail_count"`
UnknownCount int `json:"unknown_count"`
FeeTotal float64 `gorm:"type:decimal(12,4)" json:"fee_total"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}
func (StatsUserDaily) TableName() string { return "stats_user_daily" }
// (S2·R2 裁决)StatsUserDaily 用户日统计已废弃:与 billing_consume_log
// 同粒度双空壳,消耗事实源统一归 billing_consume_log(账号×业务×天),
// 表由迁移 v20 DROP;用户侧统计查询走 billing_consume_log API。
// StatsChannelDaily 通道日统计(含估算余额)。
type StatsChannelDaily struct {
+19
View File
@@ -75,6 +75,14 @@ var (
// ReportRecheckTotal pending 后新事务复查结果({result}: finalized=补刀
// 终态/still_pending=真未到齐;双盲竞态健康度=finalized 占比)。
ReportRecheckTotal *prometheus.CounterVec
// SettleAggregateRows 结算域消耗日汇总落账行数(scope: account=billing_
// consume_log / channel=stats_channel_daily;幂等 UPSERT 重刷亦计入,
// 单调累计供观测 job 活性,S5 基线期再评估是否细化)。
SettleAggregateRows *prometheus.CounterVec
// SettleAggregateErrors 消耗日汇总执行失败次数(失败 Warn 不中断,
// 幂等下轮自愈;持续增长=真故障信号)。
SettleAggregateErrors prometheus.Counter
)
var registry = prometheus.NewRegistry()
@@ -171,6 +179,16 @@ func init() {
Help: "pending 后新事务复查结果(result: finalized=补刀终态/still_pending=真未到齐)",
}, []string{LabelKind})
SettleAggregateRows = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "go_sms_settle_aggregate_rows_total",
Help: "结算域消耗日汇总落账行数(scope: account/channel;UPSERT 重刷亦计入,S2)",
}, []string{LabelKind})
SettleAggregateErrors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "go_sms_settle_aggregate_errors_total",
Help: "消耗日汇总执行失败次数(幂等下轮自愈,持续增长=真故障,S2)",
})
registry.MustRegister(
HTTPRequestsTotal, HTTPRequestDuration, HTTPRequestsInFlight,
SMSSubmitTotal, SMSReportTotal, KafkaProducerMessages,
@@ -179,6 +197,7 @@ func init() {
LongSmsMergedTotal, LongSmsDegradeTotal, LongSmsDupFragTotal,
LongSmsExpireFailTotal,
ReportPendingTotal, ReportRecheckTotal, ReportRequeueTotal,
SettleAggregateRows, SettleAggregateErrors,
)
// Go 运行时与进程指标
registry.MustRegister(
+28 -16
View File
@@ -29,8 +29,8 @@ func TestMigrations_IdempotentAndVersioned(t *testing.T) {
seen[mig.ID] = true
last = mig
}
if last == nil || last.ID != "v19_longsms_pending" {
t.Fatalf("终版迁移应为 v19_longsms_pending,实际 %v", last)
if last == nil || last.ID != "v20_settle_domain" {
t.Fatalf("终版迁移应为 v20_settle_domain,实际 %v", last)
}
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
@@ -42,31 +42,28 @@ func TestMigrations_IdempotentAndVersioned(t *testing.T) {
}
opts := gormigrate.DefaultOptions
opts.TableName = "schema_migrations"
// 注册末七迁移(现 v13..v19;历史 v10/V11 含 MessageTask AutoMigrate,gleberez
// sqlite 索引不查重,双块连跑撞 idx_account_time——同 v1+v6 已知方言缺口;v13/v14
// 各建各表、v15 AutoMigrate 加列、v16/v17 空库守卫补建 detail 后加查询索引、
// v18/v19 新表 AutoMigrate,单块两遍覆盖幂等)。
// 注册末七迁移(现 v14..v20;历史 v10/V11 含 MessageTask AutoMigrate,gleberez
// sqlite 索引不查重,双块连跑撞 idx_account_time——同 v1+v6 已知方言缺口;
// v14 各建各表、v15 AutoMigrate 加列、v16/v17/v20 空库守卫补建表后加列/索引、
// v18/v19 新表 AutoMigrate,v20 另含 DROP IF EXISTS 与 casbin HasTable 守卫,
// 单块两遍覆盖幂等)。
migs := Migrations()
gm := gormigrate.New(db.Session(&gorm.Session{Logger: logger.Discard}), opts, migs[len(migs)-7:])
if err := gm.Migrate(); err != nil {
t.Fatalf("v13..v19 首遍失败: %v", err)
t.Fatalf("v14..v20 首遍失败: %v", err)
}
if err := gm.Migrate(); err != nil {
t.Fatalf("v13..v19 二遍不幂等: %v", err)
t.Fatalf("v14..v20 二遍不幂等: %v", err)
}
v, err := CurrentMigrationVersion(db)
if err != nil {
t.Fatalf("查版本失败: %v", err)
}
if v == nil || *v != "v19_longsms_pending" {
t.Fatalf("版本应为 v19_longsms_pending,实际 %v", v)
}
if !db.Migrator().HasTable(&entity.MessageReportSeg{}) {
t.Fatal("v13 后应存在 message_report_seg 表")
}
if !db.Migrator().HasColumn(&entity.MessageReportSeg{}, "PkTotal") {
t.Fatal("v13 后应存在 pk_total 列(段级配对键)")
if v == nil || *v != "v20_settle_domain" {
t.Fatalf("版本应为 v20_settle_domain,实际 %v", v)
}
// (v13 断言随窗口右移移除:message_report_seg/pk_total 由 v13 建,
// 现窗口 v14..v20 不含 v13;全量链路覆盖仍由 dev MySQL 实库验证。)
// Day 62:v15 后 account_config 应有账号级 CMPP 配额两列。
if !db.Migrator().HasColumn(&entity.AccountConfig{}, "CmppMaxConns") ||
!db.Migrator().HasColumn(&entity.AccountConfig{}, "CmppSpeed") {
@@ -85,6 +82,21 @@ func TestMigrations_IdempotentAndVersioned(t *testing.T) {
if !db.Migrator().HasIndex(&entity.MessageDetail{}, "idx_business_created") {
t.Fatal("v17 后应存在 idx_business_created 索引")
}
// S2:v20 后 billing_consume_log 应有 unknown_count/updated_at 列,
// account_user 应有 rebate_rate 列,settle_ladder 建表且 stats_user_daily 废弃。
if !db.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UnknownCount") ||
!db.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UpdatedAt") {
t.Fatal("v20 后 billing_consume_log 应有 unknown_count/updated_at 列")
}
if !db.Migrator().HasColumn(&entity.AccountUser{}, "RebateRate") {
t.Fatal("v20 后 account_user 应有 rebate_rate 列")
}
if !db.Migrator().HasTable(&entity.SettleLadder{}) {
t.Fatal("v20 后应存在 settle_ladder 表")
}
if db.Migrator().HasTable("stats_user_daily") {
t.Fatal("v20 后 stats_user_daily 应已 DROP(R2 单一事实源裁决)")
}
}
// newTestDB 内存 SQLite + 自动建表。
+74
View File
@@ -393,6 +393,80 @@ func Migrations() []*gormigrate.Migration {
return nil // 表可手工 DROP,回滚为空操作
},
},
{
// S2(结算域 D 层)表基线,详见 docs/review/s2-settle-table-review.md:
// ①billing_consume_log 补 unknown_count/updated_at——消耗事实源
// (R2:stats_user_daily 废弃),幂等 UPSERT 重跑需更新痕迹;
// ②account_user 补 rebate_rate——代理返点率(R4,小数表示);
// ③DROP stats_user_daily——同粒度双空壳,单一事实源归 billing_
// consume_log;空库路径 v0 已不再建它,DROP IF EXISTS 双方言幂等;
// ④新表 settle_ladder——阶梯价档位(R5,出账时按月成功总量落档);
// ⑤casbin 补结算域策略(ops settle:write / customer settle:read,
// 逐条 NOT EXISTS 守卫;末段迁移单块重放路径无 casbin_rule 表,
// HasTable 守卫跳过,全量链路种入)。
// 加列走显式 SQL 不走 AutoMigrate——glebarez SQLite 下 entity 加
// 字段触发表 diff 重建会抹既有索引(v16/v17 教训);空库守卫分支
// AutoMigrate 整表无此风险(表本不存在)。
ID: "v20_settle_domain",
Migrate: func(tx *gorm.DB) error {
if !tx.Migrator().HasTable(&entity.BillingConsumeLog{}) { // 空库守卫(同 v16/v17)
if err := tx.AutoMigrate(&entity.BillingConsumeLog{}); err != nil {
return err
}
}
if !tx.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UnknownCount") {
if err := tx.Exec("ALTER TABLE billing_consume_log ADD COLUMN unknown_count INT NOT NULL DEFAULT 0").Error; err != nil {
return err
}
}
if !tx.Migrator().HasColumn(&entity.BillingConsumeLog{}, "UpdatedAt") {
if err := tx.Exec("ALTER TABLE billing_consume_log ADD COLUMN updated_at DATETIME NULL DEFAULT NULL").Error; err != nil {
return err
}
}
if !tx.Migrator().HasTable(&entity.AccountUser{}) { // 空库守卫
if err := tx.AutoMigrate(&entity.AccountUser{}); err != nil {
return err
}
}
if !tx.Migrator().HasColumn(&entity.AccountUser{}, "RebateRate") {
if err := tx.Exec("ALTER TABLE account_user ADD COLUMN rebate_rate DECIMAL(5,4) NOT NULL DEFAULT 0").Error; err != nil {
return err
}
}
if err := tx.Exec("DROP TABLE IF EXISTS stats_user_daily").Error; err != nil {
return err
}
if !tx.Migrator().HasTable(&entity.SettleLadder{}) { // 新表,AutoMigrate 安全(同 v18/v19)
if err := tx.AutoMigrate(&entity.SettleLadder{}); err != nil {
return err
}
}
if tx.Migrator().HasTable(&casbinRule{}) { // v5 才建 casbin_rule
policies := []casbinRule{
{Ptype: "p", V0: "ops", V1: "settle", V2: "write"},
{Ptype: "p", V0: "customer", V1: "settle", V2: "read"}, // 客户查自己账单,scope 在 handler 侧过滤
}
for _, p := range policies {
var n int64
if err := tx.Model(&casbinRule{}).
Where("ptype = ? AND v0 = ? AND v1 = ? AND v2 = ?", p.Ptype, p.V0, p.V1, p.V2).
Count(&n).Error; err != nil {
return err
}
if n == 0 {
if err := tx.Create(&p).Error; err != nil {
return err
}
}
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return nil // 列/表/策略可手工重建或清除,回滚为空操作(v16~v19 惯例)
},
},
}
}
+1 -1
View File
@@ -1,3 +1,3 @@
// Package service 业务服务实现层(账号/通道/发送/路由/审核/计费/统计/结算等)。
// 阶段 2 起逐步填充。
// 阶段 2 起逐步填充;S2 起新增 settle 域(消耗日汇总/充值审核/月结/阶梯/利润/对账)。
package service
+180
View File
@@ -0,0 +1,180 @@
// consume.go S2-D2:消耗日汇总引擎——结算域事实源(T+1 思路的滚动重刷修正版)。
//
// 模型(评审 docs/review/s2-settle-table-review.md §三 + D2 修正):
// - 明细热窗仅 5 天,月结绝不能扫明细——billing_consume_log(账号×业务×天)
// 与 stats_channel_daily(通道×天)是结算域唯一消耗事实源(R2);
// - 72h 回执窗内明细状态会迁移(UNKNOWN→成功/失败,Day69/71),昨日行非
// 终值——单日一次性落账会失真,改为周期滚动重刷近 N 天幂等 UPSERT 收敛;
// - 口径:submit=COUNT(*) 全部;success/fail/unknown=SUM(status=N);
// fee_total=Σfee(条,Day70 片数口径);cost_total/est_balance 不写
// (R1:金额出账时刻推导,单一事实源纪律)。
// - 边界:某账号当日明细为 0 则不产生行(热窗内明细不删,无脏残留场景);
// 数据清退(S4 分区)后的历史行冻结,重刷窗不覆盖即可。
package settle
import (
"context"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"go-sms/internal/model/entity"
)
// Service 结算域服务(D2 消耗日汇总;D3~D5 逐步扩展充值审核/出账/利润/对账)。
type Service struct{ db *gorm.DB }
// NewService 构造(仅 db 依赖,照 account.Service 极简口径)。
func NewService(db *gorm.DB) *Service { return &Service{db: db} }
// accountAggRow 账号维度聚合扫描 DTO(COUNT/SUM 扫 int64 再转实体 int)。
type accountAggRow struct {
AccountID int64
Business string
SubmitCount int64
SuccessCount int64
FailCount int64
UnknownCount int64
FeeTotal float64
}
// channelAggRow 通道维度聚合扫描 DTO(无 Σfee——R1 出账按条数×价推导,
// 通道侧无需费用列,cost_total 保持 0)。
type channelAggRow struct {
ChannelID int64
SubmitCount int64
SuccessCount int64
FailCount int64
UnknownCount int64
}
// AggregateDay 单日消耗汇总(幂等 UPSERT,滚动重刷安全):
// 账号×业务 → billing_consume_log(uk account_id+business+stat_date 覆盖更新);
// 通道 → stats_channel_daily(uk channel_id+stat_date)。
// [lo,hi) 半开时间窗规避 date() 方言差;SUM(status=N) MySQL/SQLite 双方言
// 布尔求和(stats_handler 同款)。返回两表落账行数(供指标/手动回补响应)。
func (s *Service) AggregateDay(ctx context.Context, day time.Time) (accountRows, channelRows int64, err error) {
lo := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, day.Location())
hi := lo.AddDate(0, 0, 1)
// ① 账号×业务维度(GROUP BY 聚合一条 SQL;日汇总 job 一天数次,
// 非请求路径——性能三律约束的是业务查询页,此处窗口扫描可接受,
// S5 压测后如需再优化为覆盖索引三 COUNT)。
var accountAggs []accountAggRow
if err = s.db.WithContext(ctx).Table("message_detail").
Select("account_id, business, COUNT(*) AS submit_count, "+
"COALESCE(SUM(status = 2), 0) AS success_count, "+
"COALESCE(SUM(status = 3), 0) AS fail_count, "+
"COALESCE(SUM(status = 4), 0) AS unknown_count, "+
"COALESCE(SUM(fee), 0) AS fee_total").
Where("created_at >= ? AND created_at < ?", lo, hi).
Group("account_id, business").
Scan(&accountAggs).Error; err != nil {
return 0, 0, err
}
for _, r := range accountAggs {
row := entity.BillingConsumeLog{
AccountID: r.AccountID,
Business: r.Business,
StatDate: lo,
SubmitCount: int(r.SubmitCount),
SuccessCount: int(r.SuccessCount),
FailCount: int(r.FailCount),
UnknownCount: int(r.UnknownCount),
FeeTotal: r.FeeTotal,
}
if err = s.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{
{Name: "account_id"}, {Name: "business"}, {Name: "stat_date"},
},
DoUpdates: clause.AssignmentColumns([]string{
"submit_count", "success_count", "fail_count",
"unknown_count", "fee_total", "updated_at",
}),
}).Create(&row).Error; err != nil {
return accountRows, channelRows, err
}
accountRows++
}
// ② 通道维度(grain=通道×天,不加 business——通道价格体系不分业务,R2 评审;
// 不聚合 Σfee——上家账单按 billing_mode 条数口径,cost_total 保持 0,R1)。
var channelAggs []channelAggRow
if err = s.db.WithContext(ctx).Table("message_detail").
Select("channel_id, COUNT(*) AS submit_count, "+
"COALESCE(SUM(status = 2), 0) AS success_count, "+
"COALESCE(SUM(status = 3), 0) AS fail_count, "+
"COALESCE(SUM(status = 4), 0) AS unknown_count").
Where("created_at >= ? AND created_at < ?", lo, hi).
Group("channel_id").
Scan(&channelAggs).Error; err != nil {
return accountRows, channelRows, err
}
for _, r := range channelAggs {
row := entity.StatsChannelDaily{
ChannelID: r.ChannelID,
StatDate: lo,
SubmitCount: int(r.SubmitCount),
SuccessCount: int(r.SuccessCount),
FailCount: int(r.FailCount),
UnknownCount: int(r.UnknownCount),
}
if err = s.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "channel_id"}, {Name: "stat_date"}},
DoUpdates: clause.AssignmentColumns([]string{
"submit_count", "success_count", "fail_count",
"unknown_count", "updated_at",
}),
}).Create(&row).Error; err != nil {
return accountRows, channelRows, err
}
channelRows++
}
return accountRows, channelRows, nil
}
// ConsumeQuery 消耗日汇总查询条件(To 按天闭区间,service 内转半开窗)。
type ConsumeQuery struct {
AccountID int64 // 0=全部;customer scope 由 handler 强制注入
Business string // ""=全部
From time.Time // 闭区间起(零值=不限)
To time.Time // 闭区间止(零值=不限)
Page int // 1 起
PageSize int // 默认 20,上限 100(handler 兜底)
}
// ListConsume 分页查询消耗日汇总(按 stat_date 倒序,新数据在前)。
func (s *Service) ListConsume(ctx context.Context, q ConsumeQuery) ([]entity.BillingConsumeLog, int64, error) {
db := s.db.WithContext(ctx).Model(&entity.BillingConsumeLog{})
if q.AccountID > 0 {
db = db.Where("account_id = ?", q.AccountID)
}
if q.Business != "" {
db = db.Where("business = ?", q.Business)
}
if !q.From.IsZero() {
// 按天归一(stat_date 恒为当日零点,带时刻参数会把今天的行误滤)。
f := time.Date(q.From.Year(), q.From.Month(), q.From.Day(), 0, 0, 0, 0, q.From.Location())
db = db.Where("stat_date >= ?", f)
}
if !q.To.IsZero() {
t := time.Date(q.To.Year(), q.To.Month(), q.To.Day(), 0, 0, 0, 0, q.To.Location())
db = db.Where("stat_date < ?", t.AddDate(0, 0, 1)) // 闭区间转半开(按天)
}
var total int64
if err := db.Count(&total).Error; err != nil {
return nil, 0, err
}
if q.Page <= 0 {
q.Page = 1
}
if q.PageSize <= 0 || q.PageSize > 100 {
q.PageSize = 20
}
var list []entity.BillingConsumeLog
err := db.Order("stat_date DESC, account_id, business").
Limit(q.PageSize).Offset((q.Page - 1) * q.PageSize).
Find(&list).Error
return list, total, err
}
+219
View File
@@ -0,0 +1,219 @@
package settle
// consume_test.go S2-D2:消耗日汇总引擎单测(sqlite,glebarez)——聚合正确性/
// 幂等重跑/跨天边界/UNKNOWN 状态迁移重刷收敛(滚动重刷核心语义)/查询过滤。
// handler 端点(customer scope 收窄+手动回补)在 api 层 settle_handler_test.go。
import (
"context"
"math"
"testing"
"time"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"go-sms/internal/model/entity"
)
// newConsumeDB 内存库 + message_detail/billing_consume_log/stats_channel_daily。
func newConsumeDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if s, e := db.DB(); e == nil {
s.SetMaxOpenConns(1) // sqlite :memory: 多连接=多个空库
}
if err := db.AutoMigrate(&entity.MessageDetail{}, &entity.BillingConsumeLog{},
&entity.StatsChannelDaily{}); err != nil {
t.Fatal(err)
}
return db
}
// mkDetail 种一条明细(id 雪花由调用方递增保证唯一)。
func mkDetail(id, accountID, channelID int64, business string, status int8, fee float64, created time.Time) entity.MessageDetail {
return entity.MessageDetail{
SnowflakeModel: entity.SnowflakeModel{ID: id, CreatedAt: created},
TaskID: 800000 + id, AccountID: accountID, ChannelID: channelID,
Mobile: "13000001111", Content: "t", Status: status, Business: business, Fee: fee,
}
}
func feq(a, b float64) bool { return math.Abs(a-b) < 1e-9 }
func TestAggregateDay_Correctness(t *testing.T) {
db := newConsumeDB(t)
now := time.Now()
details := []entity.MessageDetail{
// 账号 1 · sms:2 成功(fee 1.5×2)+1 失败+1 未知+1 拦截 → submit5/succ2/fail1/unk1/fee 6.5
mkDetail(1, 1, 1, "sms", 2, 1.5, now), mkDetail(2, 1, 1, "sms", 2, 1.5, now),
mkDetail(3, 1, 1, "sms", 3, 1.0, now), mkDetail(4, 1, 1, "sms", 4, 1.0, now),
mkDetail(5, 1, 1, "sms", 5, 1.5, now),
// 账号 1 · video:1 成功 → submit1/succ1/fee 2.0
mkDetail(6, 1, 2, "video", 2, 2.0, now),
// 账号 100 · sms:1 成功 → submit1/succ1/fee 3.0
mkDetail(7, 100, 2, "sms", 2, 3.0, now),
}
if err := db.Create(&details).Error; err != nil {
t.Fatal(err)
}
svc := NewService(db)
a, ch, err := svc.AggregateDay(context.Background(), now)
if err != nil {
t.Fatal(err)
}
if a != 3 || ch != 2 {
t.Fatalf("落账行数 account=%d(期望3) channel=%d(期望2)", a, ch)
}
var logs []entity.BillingConsumeLog
if err := db.Order("account_id, business").Find(&logs).Error; err != nil {
t.Fatal(err)
}
if len(logs) != 3 {
t.Fatalf("billing_consume_log 行数=%d 期望 3", len(logs))
}
check := func(l entity.BillingConsumeLog, accountID int64, business string, submit, succ, fail, unknown int, fee float64) {
t.Helper()
if l.AccountID != accountID || l.Business != business {
t.Fatalf("行归属错: got account=%d business=%s", l.AccountID, l.Business)
}
if l.SubmitCount != submit || l.SuccessCount != succ || l.FailCount != fail || l.UnknownCount != unknown {
t.Fatalf("账号 %d %s 计数错: submit=%d succ=%d fail=%d unk=%d (期望 %d/%d/%d/%d)",
accountID, business, l.SubmitCount, l.SuccessCount, l.FailCount, l.UnknownCount, submit, succ, fail, unknown)
}
if !feq(l.FeeTotal, fee) {
t.Fatalf("账号 %d %s fee_total=%v 期望 %v", accountID, business, l.FeeTotal, fee)
}
}
check(logs[0], 1, "sms", 5, 2, 1, 1, 6.5)
check(logs[1], 1, "video", 1, 1, 0, 0, 2.0)
check(logs[2], 100, "sms", 1, 1, 0, 0, 3.0)
var chans []entity.StatsChannelDaily
if err := db.Order("channel_id").Find(&chans).Error; err != nil || len(chans) != 2 {
t.Fatalf("stats_channel_daily 行数=%d err=%v 期望 2", len(chans), err)
}
if chans[0].ChannelID != 1 || chans[0].SubmitCount != 5 || chans[0].SuccessCount != 2 ||
chans[0].FailCount != 1 || chans[0].UnknownCount != 1 {
t.Fatalf("通道 1 计数错: %+v", chans[0])
}
if chans[1].ChannelID != 2 || chans[1].SubmitCount != 2 || chans[1].SuccessCount != 2 {
t.Fatalf("通道 2 计数错: %+v", chans[1])
}
if chans[0].CostTotal != 0 {
t.Fatalf("cost_total 应保持 0(R1 出账计价),got %v", chans[0].CostTotal)
}
}
func TestAggregateDay_IdempotentAndBoundary(t *testing.T) {
db := newConsumeDB(t)
now := time.Now()
yesterday := now.AddDate(0, 0, -1)
details := []entity.MessageDetail{
mkDetail(1, 1, 1, "sms", 2, 2.0, now),
mkDetail(2, 1, 1, "sms", 3, 2.0, now),
mkDetail(3, 1, 1, "sms", 2, 2.0, yesterday), // 次日窗口外
}
if err := db.Create(&details).Error; err != nil {
t.Fatal(err)
}
svc := NewService(db)
for i := 0; i < 2; i++ { // 两遍幂等
a, ch, err := svc.AggregateDay(context.Background(), now)
if err != nil {
t.Fatal(err)
}
if a != 1 || ch != 1 {
t.Fatalf("第 %d 遍落账 account=%d channel=%d 期望 1/1", i+1, a, ch)
}
}
var n int64
db.Model(&entity.BillingConsumeLog{}).Count(&n)
if n != 1 {
t.Fatalf("幂等重跑后行数=%d 期望 1", n)
}
var l entity.BillingConsumeLog
db.First(&l)
if l.SubmitCount != 2 || l.SuccessCount != 1 || l.FailCount != 1 {
t.Fatalf("跨天边界泄漏(应只含今天): %+v", l)
}
if !feq(l.FeeTotal, 4.0) {
t.Fatalf("fee_total=%v 期望 4.0", l.FeeTotal)
}
}
func TestAggregateDay_StateMigration(t *testing.T) {
// 滚动重刷核心语义:72h 回执窗内 UNKNOWN→成功迁移后,重跑即覆盖收敛。
db := newConsumeDB(t)
now := time.Now()
if err := db.Create(&[]entity.MessageDetail{
mkDetail(1, 1, 1, "sms", 4, 1.0, now), // 先 UNKNOWN
}).Error; err != nil {
t.Fatal(err)
}
svc := NewService(db)
if _, _, err := svc.AggregateDay(context.Background(), now); err != nil {
t.Fatal(err)
}
var l entity.BillingConsumeLog
db.First(&l)
if l.UnknownCount != 1 || l.SuccessCount != 0 {
t.Fatalf("首跑应 unknown=1: %+v", l)
}
// 回执到达:状态迁移为成功,重刷收敛。
if err := db.Model(&entity.MessageDetail{}).Where("id = ?", int64(1)).
Update("status", 2).Error; err != nil {
t.Fatal(err)
}
if _, _, err := svc.AggregateDay(context.Background(), now); err != nil {
t.Fatal(err)
}
db.First(&l)
if l.UnknownCount != 0 || l.SuccessCount != 1 {
t.Fatalf("重刷后应 success=1/unknown=0: %+v", l)
}
}
func TestListConsume_Filters(t *testing.T) {
db := newConsumeDB(t)
now := time.Now()
if err := db.Create(&[]entity.BillingConsumeLog{
{AccountID: 1, Business: "sms", StatDate: now, SubmitCount: 5, SuccessCount: 5},
{AccountID: 1, Business: "video", StatDate: now, SubmitCount: 1, SuccessCount: 1},
{AccountID: 100, Business: "sms", StatDate: now.AddDate(0, 0, -3), SubmitCount: 2, SuccessCount: 2},
{AccountID: 100, Business: "sms", StatDate: now.AddDate(0, 0, -10), SubmitCount: 9, SuccessCount: 9},
}).Error; err != nil {
t.Fatal(err)
}
svc := NewService(db)
// 全量(默认排序 stat_date DESC)。
list, total, err := svc.ListConsume(context.Background(), ConsumeQuery{})
if err != nil || total != 4 || len(list) != 4 {
t.Fatalf("全量 total=%d len=%d err=%v", total, len(list), err)
}
// 账号过滤。
_, total, err = svc.ListConsume(context.Background(), ConsumeQuery{AccountID: 1})
if err != nil || total != 2 {
t.Fatalf("账号过滤 total=%d err=%v", total, err)
}
// 业务过滤。
_, total, err = svc.ListConsume(context.Background(), ConsumeQuery{Business: "video"})
if err != nil || total != 1 {
t.Fatalf("业务过滤 total=%d err=%v", total, err)
}
// 时间窗(近 7 天闭区间:今 2 行+3 天前 1 行;零点归一语义)。
_, total, err = svc.ListConsume(context.Background(), ConsumeQuery{
From: now.AddDate(0, 0, -6), To: now,
})
if err != nil || total != 3 {
t.Fatalf("时间窗 total=%d err=%v(期望 3)", total, err)
}
// 分页。
list, total, err = svc.ListConsume(context.Background(), ConsumeQuery{Page: 2, PageSize: 3})
if err != nil || total != 4 || len(list) != 1 {
t.Fatalf("分页 total=%d len=%d err=%v", total, len(list), err)
}
}
+65
View File
@@ -0,0 +1,65 @@
// job.go S2-D2:消耗日汇总后台 job(照 StartStatsRefresher 幂等模式;仅 gateway
// 装配调用,测试/迁移工具不启)。
//
// 滚动重刷模型(D2 对 D1 计划的修正,理由见 consume.go 头注):启动回补
// BackfillDays 天(不阻塞启动)→ 周期 RefreshEvery 重刷近 RefreshDays 天
// (默认 4 天=72h 回执窗+当天增量,UNKNOWN 状态迁移靠重刷收敛)。幂等
// UPSERT——多实例/重复跑无害;失败 Warn 不中断,下轮自愈。
package settle
import (
"context"
"time"
"go.uber.org/zap"
"gorm.io/gorm"
"go-sms/internal/pkg/metrics"
)
// StartAggregateJob 启动消耗日汇总 job(goroutine 内自兜底配置零值;
// cfg 三参<=0 时分别取 1h / 4 天 / 7 天,见 config.Settle 注释)。
func StartAggregateJob(db *gorm.DB, refreshEvery time.Duration, refreshDays, backfillDays int, log *zap.Logger) {
if refreshEvery <= 0 {
refreshEvery = time.Hour
}
if refreshDays <= 0 {
refreshDays = 4
}
if backfillDays <= 0 {
backfillDays = 7
}
svc := NewService(db)
go func() {
for i := backfillDays - 1; i >= 0; i-- {
aggregateOneDay(svc, time.Now().AddDate(0, 0, -i), log)
}
if log != nil {
log.Info("settle_backfill_done", zap.Int("days", backfillDays))
}
ticker := time.NewTicker(refreshEvery)
defer ticker.Stop()
for range ticker.C {
now := time.Now()
for i := refreshDays - 1; i >= 0; i-- {
aggregateOneDay(svc, now.AddDate(0, 0, -i), log)
}
}
}()
}
// aggregateOneDay 单日落账 + 指标埋点(失败不返回错误——job 壳内消化,
// 错误计数器持续增长即真故障信号,runbook 口径)。
func aggregateOneDay(svc *Service, day time.Time, log *zap.Logger) {
accountRows, channelRows, err := svc.AggregateDay(context.Background(), day)
if err != nil {
metrics.SettleAggregateErrors.Inc()
if log != nil {
log.Warn("settle_aggregate_failed",
zap.String("day", day.Format("2006-01-02")), zap.Error(err))
}
return
}
metrics.SettleAggregateRows.WithLabelValues("account").Add(float64(accountRows))
metrics.SettleAggregateRows.WithLabelValues("channel").Add(float64(channelRows))
}
+7 -8
View File
@@ -1,13 +1,12 @@
# 当前工作上下文(最近更新:2026-11-12)
# 当前工作上下文(最近更新:2026-11-14)
## 当前状态快照(2026-11-13 夜,**S1 泳道收官**)
## 当前状态快照(2026-11-14 傍晚,**S2-D2 收官**)
- **仓库**:main 已推 Gitea(origin=192.168.5.27:24401/Tory/go-sms-V2);S1 全程 28 提交(2a6a66f→661eedd)+S3 前置 c205f017(views 31 页补齐+网关端口归位 :8080+FE 工具链 node20.19/pnpm12.18);每日 bundle+push 双轨。
- **S1 出口全绿**:B 层 12 域+结构改造三件(send 拆包 facade/channel 拆 pool/router 空壳消除)+dayNN 清零+lint 0+**全仓 -race 38 包 RC=0**+集成七件+gateway 驻留冒烟;迁移链 v1~v19 落地。
- **send 三子包**(0550f2a):submit(受理+事件/状态契约族)/consume/dispatch;facade.go 40 符号别名门面,调用方零改动;依赖 consume→{submit,dispatch}、dispatch→submit 单向。
- **中间件**:9/9 healthy(MySQL 10G SSD 基线/kafka compose 化/rustfs);gateway :8081 驻留。
- **在途**:24h 稳定性门槛 **维持原时间核验:11-13 17:55 起计 → 11-14 17:55 期满回填 s1-b-closeout.md**(S5 压测基线前置);期内 21:33 宿主主动有序重启(内核升级日二次重启)=已知事件不判失败,九中间件 restart policy 自愈全 healthy,gateway 重驻 :8080(md5 比对一致)。
- **下一步=S2 结算域**(5 工作日,D 层新做):开工前置=研读《需求分析》结算章节+表设计评审先行(整域 0% 起点);随后 S3 前端(views 31 页+FE-6+node 工具链)。
- **仓库**:main 已推 Gitea(origin=192.168.5.27:24401/Tory/go-sms-V2);每日 bundle+push 双轨。
- **S2 进度 2/5**:D1 ✅(表设计六裁决+v20+openapi v1.3.0)/ **D2 ✅(消耗日汇总引擎)**——settle/consume.go+job.go+两端点;**滚动重刷模型**(1h 重刷近 4 天,修正单日 T+1 的 72h UNKNOWN 迁移失真;月结建议 T+4 后生成);-race 39 包/lint 0/真 MySQL 端到端+收敛实证(success 1→2/unknown 1→0);gateway 已驻新二进制(md5 一致)。
- **24h 稳定性门槛 ✅ 终判通过**(18:02 三项全绿;S1 完全闭环,S5 压测前置确认)。
- **六项裁决速查**:R1 出账时刻计价(明细 Fee=片数不动,send 域零改动;金额=Σ日成功条数×生效单价,时间线+阶梯在 D4 settle/price.go 单点推导)/R2 消耗事实源=billing_consume_log(账号×业务×天)+stats_channel_daily(通道×天,已由 D2 job 落账)/R3 充值双通道/R4 rebate_rate 单级返点历史不重算/R5 settle_ladder(owner×tier_from)/R6 条/元换算只在出账引擎。
- **下一步=S2-D3 充值审核流**:settle/recharge.go+`/billing/orders` 族四端点(创建 pay_status=0 不动余额/confirm=状态 CAS+余额自增 count+流水 ref_id=order_no 同事务/驳回/列表);R3 双通道语义(即时充值保留);并发 confirm -race 只入账一次为验收点。随后 D4 出账+阶梯(显式验收:阶梯结算单测)/D5 利润返点+三方对账(S2 出口 diff=0)。
- 归档仓(只读):/data/poc-archive/repos/go-sms.git(poc-final=5e09a4cc)。
- **本会话运维教训**:①`pkill/pgrep -f` 自匹配(铁律:`[x]` 括号技巧);②大镜像单窗>体积÷带宽;③du 无 sudo 静默失败误诊;④sed 换行/sed 误伤方法名(重构期优先编辑器工具);⑤Go 工具忽略 `_` 前缀文件;⑥集成测试需 `sg docker` 包裹(docker 组未重登);⑦**Makefile recipe 的 `exit 0` 只退出当前行 shell 不终止目标**(幂等短路须 if/else 递归 `$(MAKE)` 子目标);⑧**管道 `| tail -N` 截首行误导诊断**(gw-start"玄学 NOMATCH"两轮误诊实为 THEN 分支已生效,排查须看全量输出)。
+4 -1
View File
@@ -11,7 +11,10 @@
| S1-B D1 中间件+基线 | compose SSD 参数生效/Kafka compose 化/迁移链 v1~v19 落地/集成六件绿/首份快照/24h 门槛起计 | ✅ 2026-11-13(minio 镜像遗留) |
| S1-B B 层搬运 P1 | 12 域+双入口全落位(两阶段等价法);channel P2 拆 pool 完成;lint 27→0;全仓 -race 36 包绿 | ✅ 2026-11-13 |
| S1-B 收尾项 | send P2 拆三子包(0550f2a,facade 门面)/dayNN 19 文件改名/storage 归一/文案校准/gofmt 清零 | ✅ 2026-11-13 夜(**S1 泳道收官**) |
| 观察项 | 24h 稳定性门槛(维持原时间:11-13 17:55 起计;期内 21:33 宿主主动重启=已知事件不判失败)期满核验 11-14 17:55 → s1-b-closeout.md 回填 | ⏳ 在途 |
| S2-D1 表设计+v20+契约 | 六项裁决(R1 出账时刻计价/R2 事实源统一/R3 充值双通道/R4 返点/R5 阶梯表/R6 口径)+v20_settle_domain+openapi v1.3.0(+20 端点)+dev 库实跑 v20 | ✅ 2026-11-14(评审纪要 docs/review/s2-settle-table-review.md;验收单 s2-d1.md) |
| S2-D2 消耗日汇总引擎 | settle/consume.go+job.go(**滚动重刷模型**:1h 重刷近 4 天,修正单日 T+1 的 72h 失真)+两端点+config/metrics/装配;sqlite 6 测试;真 MySQL 端到端+收敛实证 | ✅ 2026-11-14 傍晚(验收单 s2-d2.md) |
| S2-D3~D5 | D3 充值审核流/D4 出账+阶梯(显式验收:阶梯结算单测)/D5 利润返点+三方对账(diff=0=S2 出口) | ⬜ 排期中 |
| 观察项 | 24h 稳定性门槛(11-13 17:55 起计;期内 21:33 宿主主动重启=已知事件不判失败)期满核验 11-14 17:55 | ✅ 2026-11-14 18:02 终判通过(dmesg 0/零重启/驻留+md5 一致;S5 压测前置确认,S1 完全闭环) |
| S2~S5 | 结算域/前端收尾/C1C2+冷热/基线与灰度 | ⬜ 见《Go-sms-重建计划.md》 |
Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 195 KiB

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 179 KiB

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 202 KiB

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 130 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 202 KiB

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 KiB

After

Width:  |  Height:  |  Size: 113 KiB

+6
View File
@@ -202,6 +202,12 @@ html:not(.dark) .card:hover { box-shadow: 0 8px 28px rgba(13, 148, 136, 0.12); }
}
@media (min-width: 901px) { .nav-scrim { display: none; } }
/* ---- P3:全局键盘焦点可见性(只加强不重置;与 aurora 主色一致) ---- */
:focus-visible {
outline: 2px solid var(--gosms-primary);
outline-offset: 2px;
}
/* ============================================================
* 基础重置(原 index.scss 职责并入)
* ============================================================ */
+342 -104
View File
@@ -1,47 +1,68 @@
<template>
<div class="page-stack">
<!-- demo page-head live-chip(F:Teleport 至 MainLayout page-head 右侧扩展位) -->
<Teleport to="#page-head-extra">
<span class="live-chip" data-testid="live-chip"><i></i>实时刷新中</span>
<!-- D10 数据脉象:最后成功刷新时刻 + 失败显式降级(替代恒亮"实时刷新中"装饰)
Teleport 门控:目标 #page-head-extra 由 MainLayout 渲染,冷启动懒加载竞态下可能
晚于本组件 mount(Vue 3.4 无 <Teleport defer>),直接挂载会致后续 patch 崩溃
(实测 TypeError: setText null nodeValue → 组件更新全中断)——v-if 延后一拍。 -->
<Teleport v-if="teleportReady" to="#page-head-extra">
<button class="live-chip" :class="pulse.cls" data-testid="live-chip" :title="pulse.title" @click="loadAll">
<i></i>{{ pulse.text }}
</button>
</Teleport>
<!-- demo metrics:四指标卡(32px mono 发光 + delta 胶囊) -->
<!-- D2/D8 Hero 决策句:把今日四指标实时翻译为一句话判定,可点击直达处置页 -->
<section class="card hero" :class="[`hero--${hero.tone}`, { 'hero--go': !!hero.go }]" data-testid="hero-line"
:role="hero.go ? 'button' : undefined" :tabindex="hero.go ? 0 : undefined"
@click="hero.go && $router.push(hero.go)" @keydown.enter="hero.go && $router.push(hero.go)">
<span class="hero-ic"><el-icon :size="18"><component :is="hero.icon" /></el-icon></span>
<div class="hero-body">
<p class="hero-text">{{ hero.text }}</p>
<p v-if="hero.sub" class="hero-sub">{{ hero.sub }}</p>
</div>
<span v-if="hero.go" class="hero-arrow">→</span>
</section>
<!-- 四指标卡(P2:emoji→EP icon 统一;D3:假"实时速率"→真"待人工审核";P3:count-up) -->
<div class="metrics stagger">
<div class="card metric" data-testid="stat-today">
<div class="label"><span class="ic">📮</span>今日提交</div>
<div class="value">{{ summary ? fmtNum(summary.today_sent) : '—' }}</div>
<div class="label"><span class="ic"><el-icon :size="13"><Promotion /></el-icon></span>今日提交</div>
<div class="value">{{ todayUp }}</div>
<span class="delta" :class="sentDelta.cls" data-testid="stat-today-trend">{{ sentDelta.text }}</span>
</div>
<div class="card metric" data-testid="stat-rate">
<div class="label"><span class="ic">✓</span>回执成功率</div>
<div class="value">{{ pctVal }}<span class="unit">%</span></div>
<div class="label"><span class="ic"><el-icon :size="13"><CircleCheck /></el-icon></span>回执成功率</div>
<div class="value">{{ rateUp }}<span class="unit">%</span></div>
<span class="delta" :class="rateDelta.cls" data-testid="stat-rate-trend">{{ rateDelta.text }}</span>
</div>
<div class="card metric" data-testid="stat-speed">
<div class="label"><span class="ic">⚡</span>实时速率</div>
<div class="value">{{ fmtNum(rateNow) }}<span class="unit">条/分</span></div>
<span class="delta warn">◆ 高峰时段</span>
<div class="card metric metric--click" data-testid="stat-audit" @click="$router.push('/audit')">
<div class="label"><span class="ic" :class="{ 'ic--hot': pendingCount > 0 }"><el-icon :size="13"><Bell /></el-icon></span>待人工审核</div>
<div class="value" :class="{ 'value--warn': pendingCount > 0 }">{{ auditUp }}<span class="unit">条</span></div>
<span class="delta" :class="pendingCount > 0 ? 'down' : 'up'">{{ pendingCount > 0 ? '↓ 立即处理' : '↑ 无积压' }}</span>
</div>
<div class="card metric metric--click" data-testid="stat-balance" @click="$router.push('/account/list')">
<div class="label"><span class="ic">⚠</span>余额预警</div>
<div class="value" :class="{ 'value--alert': alertCount > 0 }">{{ summary ? fmtNum(alertCount) : '—' }}<span class="unit">条</span></div>
<div class="label"><span class="ic"><el-icon :size="13"><Wallet /></el-icon></span>余额预警</div>
<div class="value" :class="{ 'value--alert': alertCount > 0 }">{{ alertUp }}<span class="unit">条</span></div>
<span class="delta" :class="alertCount > 0 ? 'down' : 'up'">{{ alertCount > 0 ? '↓ 低于预警线,点击处理' : '↑ 余额充足' }}</span>
</div>
</div>
<!-- demo duo:七日走势 + 快捷操作 -->
<!-- duo:发送走势(7/30 日切换)+ 快捷操作(desc 与实时指标联动) -->
<div class="duo">
<div class="card">
<div class="card-head">
七日提交走势
<small>近 7 日 · 单位:条</small>
<el-button circle size="small" aria-label="手动刷新统计数据" data-testid="dash-refresh" @click="load">
发送走势
<el-radio-group v-model="trendDays" size="small" data-testid="trend-range" @change="loadTrend">
<el-radio-button :label="7">7 日</el-radio-button>
<el-radio-button :label="30">30 日</el-radio-button>
</el-radio-group>
<small>{{ trendDays }} 日 · 单位:条</small>
<el-button circle size="small" aria-label="手动刷新统计数据" data-testid="dash-refresh" @click="loadAll">
<el-icon><Refresh /></el-icon>
</el-button>
</div>
<el-skeleton v-if="trendLoading" :rows="4" animated data-testid="trend-skeleton" />
<svg v-else-if="trend.length" viewBox="0 0 640 200" class="trend-svg" role="img"
aria-label="近七日提交量走势" preserveAspectRatio="none" data-testid="trend-chart">
:aria-label="`近${trendDays}日提交量走势`" preserveAspectRatio="none" data-testid="trend-chart">
<defs>
<linearGradient id="gosmsFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="var(--gosms-grad-from)" stop-opacity="0.3" />
@@ -60,10 +81,24 @@
<path :d="areaPath" fill="url(#gosmsFill)" />
<path :d="sentPath" fill="none" stroke="url(#gosmsStroke)" stroke-width="2.5" class="trend-line" />
<g fill="var(--gosms-primary)">
<circle v-for="(p, i) in trend" :key="i" :cx="px(i)" :cy="py(p.sent)" r="4" />
<circle v-for="(p, i) in trend" :key="i" :cx="px(i)" :cy="py(p.sent)" :r="trend.length > 14 ? 2.5 : 4" />
</g>
<g font-size="10" fill="var(--gosms-text-muted)" font-family="IBM Plex Mono,monospace" text-anchor="middle">
<text v-for="(p, i) in trend" :key="i" :x="px(i)" y="192">{{ dateLabel(p.date, i) }}</text>
<template v-for="(p, i) in trend" :key="i">
<text v-if="showLabel(i)" :x="px(i)" y="192">{{ dateLabel(p.date, i) }}</text>
</template>
</g>
<!-- P3 hover 十字线 + 气泡(纯 SVG;透明 rect 承接事件) -->
<rect x="0" y="0" :width="W" height="200" fill="transparent" data-testid="trend-hit"
@mousemove="onTrendHover" @mouseleave="hoverIdx = -1" />
<g v-if="hoverIdx >= 0 && trend[hoverIdx]" data-testid="trend-tip">
<line :x1="px(hoverIdx)" y1="12" :x2="px(hoverIdx)" y2="190" class="trend-cursor" />
<circle :cx="px(hoverIdx)" :cy="py(trend[hoverIdx].sent)" r="5" fill="var(--gosms-primary)" />
<g class="trend-tip" :transform="`translate(${tipX},${tipY})`">
<rect x="0" y="0" width="168" height="44" rx="8" />
<text x="12" y="17" class="tip-date">{{ trend[hoverIdx].date }}</text>
<text x="12" y="34">提交 {{ fmtNum(trend[hoverIdx].sent) }} · 成功 {{ fmtNum(trend[hoverIdx].success) }}</text>
</g>
</g>
</svg>
<div v-else class="trend-empty">暂无趋势数据</div>
@@ -73,7 +108,7 @@
<div class="card-head">快捷操作</div>
<div class="quick-item" v-for="q in quick" :key="q.label" role="button" tabindex="0"
@click="$router.push(q.to)" @keydown.enter="$router.push(q.to)">
<span class="qic">{{ q.ic }}</span>
<span class="qic" :class="{ 'qic--hot': q.hot }"><el-icon :size="16"><component :is="q.icon" /></el-icon></span>
<div class="quick-body">
<div class="qt">{{ q.label }}</div>
<div class="qd">{{ q.desc }}</div>
@@ -83,107 +118,128 @@
</div>
</div>
<!-- demo 通道列表(静态示例照搬;后端接口接入后替换数据源) -->
<!-- D3/D4 通道表:真实配置域快照(channelApi.list);运行统计列诚实标注待接入 -->
<div class="card">
<div class="card-head">通道列表<small>{{ channels.length }} / 24 条 · 按今日提交排序 · 示例数据(后端接入中)</small></div>
<div class="ch-scroll">
<div class="card-head">
通道配置快照
<small>{{ channels.length }} 条 · 配置域数据 · 运行统计待 S5 压测后接入</small>
<el-button circle size="small" aria-label="刷新通道列表" data-testid="ch-refresh" @click="loadChannels">
<el-icon><Refresh /></el-icon>
</el-button>
</div>
<el-skeleton v-if="chLoading && !channels.length" :rows="3" animated />
<div v-else-if="channels.length" class="ch-scroll">
<table class="ch-table">
<thead>
<tr>
<th>通道</th><th>协议</th><th>运营商</th><th class="r">今日提交</th>
<th class="r">成功率</th><th class="r">余额(¥)</th><th>最近 ISC</th><th>状态</th>
<th>通道</th><th>协议</th><th>运营商</th>
<th class="r">限速/分</th><th class="r">连接</th><th class="r">优先级</th><th>状态</th>
</tr>
</thead>
<tbody>
<tr v-for="c in channels" :key="c.id">
<td><span class="mono dim">{{ c.id }}</span> <span class="mono">{{ c.name }}</span></td>
<td><span class="badge" :class="c.protoBadge">{{ c.proto }}</span></td>
<td>{{ c.operator }}</td>
<td class="r mono">{{ fmtNum(c.today) }}</td>
<td class="r">
<span class="rate-bar">
<span class="rb"><i :style="{ width: c.ratePct + '%' }" /></span>
<span class="pct">{{ c.ratePct }}%</span>
</span>
</td>
<td class="r mono" :class="{ 'text-danger': c.balanceRed }">{{ c.balance }}</td>
<td><span class="mono" :class="c.iscAmber ? 'text-amber' : 'dim'">ISC:{{ c.isc }}</span></td>
<td><span class="badge" :class="c.statusBadge">{{ c.status }}</span></td>
<td><span class="mono dim">{{ c.code }}</span> <span class="mono">{{ c.name }}</span></td>
<td><span class="badge" :class="protoBadge(c.protocol)">{{ protoLabel(c.protocol) }}</span></td>
<td>{{ carrierLabel(c.carrier) }}</td>
<td class="r mono">{{ fmtNum(c.speed) }}</td>
<td class="r mono">{{ c.conn_count }}</td>
<td class="r mono">{{ c.priority }}</td>
<td><span class="badge" :class="c.status === 1 ? 'ok' : 'err'">{{ c.status === 1 ? '启用' : '停用' }}</span></td>
</tr>
</tbody>
</table>
</div>
<div v-else-if="chFailed" class="ch-empty">
通道列表加载失败 · <el-button link type="primary" @click="loadChannels">重试</el-button>
</div>
<div v-else class="ch-empty">暂无通道配置</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
// P1 信息密度重构(2026-11-13):删除三处 demo 假数据(rateNow 随机速率/静态通道表/
// 快捷卡死文案),拆三条独立加载管线;P2 图标统一 EP;P3 count-up + 走势 hover。
// 设计基线 demo-c-aurora 的 token/卡片/徽章体系不变。
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Ref } from 'vue'
import { statsApi, type StatsSummary, type TrendPoint } from '@/api/stats'
import { fmtNum } from '@/utils/format'
import { channelApi, type Channel } from '@/api/channel'
import { fmtNum, fmtPct } from '@/utils/format'
// ===== demo 快捷操作(照搬文案/图标;路由指向现有页面) =====
const quick = [
{ ic: '✉', label: '新建下发任务', desc: '单发 / 群发 / 模板', to: '/sms/batch' },
{ ic: '≡', label: '通道健康巡检', desc: '5 条通道待复核', to: '/channel/list' },
{ ic: '↻', label: '失败补推', desc: '昨日 1,204 条可补', to: '/record/repush' },
{ ic: '◐', label: '余额预警设置', desc: '阈值 ¥5,000', to: '/account/list' },
] as const
// ===== demo 通道列表(静态示例;后端接口接入后替换) =====
interface ChannelRow {
id: string; name: string; proto: string; protoBadge: string; operator: string
today: number; ratePct: number; balance: string; balanceRed?: boolean
isc: string; iscAmber?: boolean; status: string; statusBadge: string
}
const channels: ChannelRow[] = [
{ id: 'CH-01', name: '华东移动专用', proto: 'CMPP', protoBadge: 'violet', operator: '移动', today: 2431057, ratePct: 98.9, balance: '184,200', isc: '000', status: '在线', statusBadge: 'ok' },
{ id: 'CH-02', name: '华南联通三网', proto: 'SMPP', protoBadge: 'ok', operator: '联通', today: 1876442, ratePct: 98.2, balance: '96,500', isc: '000', status: '在线', statusBadge: 'ok' },
{ id: 'CH-09', name: '营销批量通道', proto: 'HTTP', protoBadge: 'warn', operator: '三网', today: 1102366, ratePct: 96.8, balance: '58,900', isc: '000', status: '在线', statusBadge: 'ok' },
{ id: 'CH-07', name: '验证码专线', proto: 'CMPP', protoBadge: 'violet', operator: '三网', today: 987110, ratePct: 99.3, balance: '2,140', balanceRed: true, isc: '000', status: '低余额', statusBadge: 'warn' },
{ id: 'CH-11', name: '政企通知专列', proto: 'SMPP', protoBadge: 'ok', operator: '三网', today: 763905, ratePct: 99.0, balance: '203,500', isc: '000', status: '在线', statusBadge: 'ok' },
{ id: 'CH-05', name: '国际出海通道', proto: 'HTTP', protoBadge: 'warn', operator: '国际', today: 642308, ratePct: 97.4, balance: '12,080', isc: '429', iscAmber: true, status: '限流中', statusBadge: 'warn' },
{ id: 'CH-13', name: '港澳台通道', proto: 'HTTP', protoBadge: 'warn', operator: '港澳台', today: 198442, ratePct: 95.2, balance: '44,300', isc: '000', status: '已停用', statusBadge: 'err' },
{ id: 'CH-99', name: '测试沙箱通道', proto: 'CMPP', protoBadge: 'violet', operator: '沙箱', today: 1024, ratePct: 100, balance: '∞', isc: '000', status: '沙箱', statusBadge: 'ok' },
]
// ===== 数据加载(60s 自动刷新) =====
// ===== 数据状态(三管线独立,单点失败不连坐) =====
const summary = ref<StatsSummary | null>(null)
const trend = ref<TrendPoint[]>([])
const trendLoading = ref(true)
let timer: ReturnType<typeof setInterval> | null = null
const trendDays = ref<number>(7)
const channels = ref<Channel[]>([])
const chLoading = ref(true)
const chFailed = ref(false)
async function load() {
// D10 数据脉象:最后成功时刻 + 最近一次结果(失败显式,不再静默吞错)
const lastOk = ref<Date | null>(null)
const loadFailed = ref(false)
async function loadSummary() {
try {
const [s, t] = await Promise.all([statsApi.summary(), statsApi.trend(7)])
summary.value = s
trend.value = t
summary.value = await statsApi.summary()
lastOk.value = new Date()
loadFailed.value = false
} catch {
summary.value = summary.value ?? null // 容错:保留旧值,首载失败显示 —
loadFailed.value = true // 保留旧值继续展示,脉象同步降级为"数据截至"
}
}
async function loadTrend() {
trendLoading.value = true
try {
trend.value = await statsApi.trend(trendDays.value)
} catch {
trend.value = [] // 趋势失败 = 显式空态,不伪造数据
} finally {
trendLoading.value = false
}
}
async function loadChannels() {
chLoading.value = true
chFailed.value = false
try {
const p = await channelApi.list({ page: 1, page_size: 8 })
channels.value = p.list
} catch {
chFailed.value = true
} finally {
chLoading.value = false
}
}
function loadAll() {
void loadSummary()
void loadTrend()
void loadChannels()
}
// Teleport 门控(见模板注释):等 #page-head-extra 就绪后再挂载脉象 chip
const teleportReady = ref(false)
// 指标 60s 自动刷新;趋势/通道随挂载与手动刷新(低频数据不陪跑)
let timer: ReturnType<typeof setInterval> | null = null
onMounted(() => {
load()
timer = setInterval(load, 60_000)
void nextTick().then(() => { teleportReady.value = true })
loadAll()
timer = setInterval(loadSummary, 60_000)
})
onUnmounted(() => { if (timer) clearInterval(timer) })
// ===== demo 实时速率(占位微动,后端接口接入后替换) =====
const rateNow = ref(1247)
let rateTimer: ReturnType<typeof setInterval> | null = null
onMounted(() => {
rateTimer = setInterval(() => { rateNow.value = 1180 + Math.floor(Math.random() * 160) }, 1500)
})
onUnmounted(() => { if (rateTimer) clearInterval(rateTimer) })
// ===== 派生指标 =====
const pendingCount = computed(() => summary.value?.pending_audit_count ?? 0)
const alertCount = computed(() => summary.value?.balance_alert_count ?? 0)
// ===== 环比(demo delta:↑/↓ + 文案) =====
function pctChange(s: StatsSummary): number | null {
if (!s.yesterday_sent) return null
return ((s.today_sent - s.yesterday_sent) / s.yesterday_sent) * 100
}
const sentDelta = computed(() => {
if (!summary.value) return { cls: 'up', text: '↑ — 较昨日' }
const y = summary.value.yesterday_sent
if (!y) return { cls: 'up', text: '↑ — 较昨日' }
const d = ((summary.value.today_sent - y) / y) * 100
const d = pctChange(summary.value)
if (d == null) return { cls: 'up', text: '↑ — 较昨日' }
return d >= 0
? { cls: 'up', text: `↑ ${d.toFixed(1)}% 较昨日` }
: { cls: 'down', text: `↓ ${Math.abs(d).toFixed(1)}% 较昨日` }
@@ -195,17 +251,139 @@ const rateDelta = computed(() => {
? { cls: 'up', text: `↑ ${pp.toFixed(1)}pt` }
: { cls: 'down', text: `↓ ${Math.abs(pp).toFixed(1)}pt` }
})
const alertCount = computed(() => summary.value?.balance_alert_count ?? 0)
const pctVal = computed(() =>
summary.value ? (summary.value.success_rate * 100).toFixed(1) : '—')
// ===== demo 趋势 SVG 几何(640×200 · 网格 42/94/146 · 底线 190) =====
const W = 640
function px(i: number) {
const n = trend.value.length
return 20 + (i * (W - 40)) / Math.max(n - 1, 1)
// ===== D2/D8 Hero 决策句(ok 平稳 / warn 需关注 / err 异常 / dim 加载中) =====
function fmtDeltaPt(d: number): string {
const pt = d * 100
return `${pt >= 0 ? '+' : '−'}${Math.abs(pt).toFixed(1)}pt`
}
function py(v: number) {
const hero = computed(() => {
if (!summary.value && loadFailed.value) {
return { tone: 'err', icon: 'WarningFilled', text: '运营指标暂不可用', sub: '统计接口连接失败,可点击右上角脉象重试', go: '' }
}
if (!summary.value) {
return { tone: 'dim', icon: 'Loading', text: '正在拉取今日运营指标…', sub: '', go: '' }
}
const s = summary.value
const parts: string[] = []
if (s.balance_alert_count > 0) parts.push(`${s.balance_alert_count} 个账号余额低于预警线`)
if (s.pending_audit_count > 0) parts.push(`${s.pending_audit_count} 条短信待人工审核`)
if (parts.length) {
return {
tone: 'warn', icon: 'Warning',
text: `今日需要关注:${parts.join(' · ')}`,
sub: `其余指标正常 · 回执成功率 ${fmtPct(s.success_rate, 1)}`,
go: s.pending_audit_count > 0 ? '/audit' : '/account/list',
}
}
if (s.success_rate < 0.95 || s.success_rate_delta < 0) {
return {
tone: 'err', icon: 'CircleClose',
text: `回执成功率 ${fmtPct(s.success_rate, 1)}(环比 ${fmtDeltaPt(s.success_rate_delta)})`,
sub: '低于平稳阈值 95%,建议核查通道回执与限流',
go: '/channel',
}
}
const d = pctChange(s)
return {
tone: 'ok', icon: 'CircleCheck',
text: '平台运行平稳,无待处置事项',
sub: `成功率 ${fmtPct(s.success_rate, 1)}(环比 ${fmtDeltaPt(s.success_rate_delta)}) · 今日提交 ${fmtNum(s.today_sent)} 条${d == null ? '' : `(较昨日 ${d >= 0 ? '+' : '−'}${Math.abs(d).toFixed(1)}%)`}`,
go: '',
}
})
// ===== D10 脉象 chip 文案 =====
function clock(d: Date | null): string {
return d ? d.toTimeString().slice(0, 8) : ''
}
const pulse = computed(() => {
if (loadFailed.value && !summary.value) {
return { cls: 'dead', text: '指标不可用 · 点击重试', title: '统计接口失败且无历史数据可展示' }
}
if (loadFailed.value) {
return { cls: 'stale', text: `连接异常 · 数据截至 ${clock(lastOk.value)}`, title: '最近一次刷新失败,正在展示上次成功数据' }
}
if (!lastOk.value) return { cls: '', text: '连接中…', title: '' }
return { cls: '', text: `实时 · ${clock(lastOk.value)}`, title: '每 60 秒自动刷新,点击立即刷新' }
})
// ===== P3 数字 count-up(rAF 补间 600ms;prefers-reduced-motion 直接跳变) =====
const REDUCE_MOTION = typeof window !== 'undefined'
&& !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
function useCountUp(src: Ref<number | null>, format: (n: number) => string) {
const display = ref('—')
let raf = 0
let from = 0
const stop = () => { if (raf) cancelAnimationFrame(raf); raf = 0 }
watch(src, (to) => {
stop()
if (to == null || !Number.isFinite(to)) { display.value = '—'; return }
if (REDUCE_MOTION) { display.value = format(to); from = to; return }
const start = performance.now()
const a = from
const tick = (t: number) => {
const p = Math.min((t - start) / 600, 1)
const e = 1 - (1 - p) ** 3 // easeOutCubic
display.value = format(a + (to - a) * e)
if (p < 1) raf = requestAnimationFrame(tick)
else { from = to; raf = 0 }
}
raf = requestAnimationFrame(tick)
}, { immediate: true })
onUnmounted(stop)
return display
}
const todayUp = useCountUp(computed(() => summary.value?.today_sent ?? null), (n) => fmtNum(Math.round(n)))
const rateUp = useCountUp(
computed(() => (summary.value ? summary.value.success_rate * 100 : null)),
(n) => n.toFixed(1),
)
const auditUp = useCountUp(computed(() => summary.value?.pending_audit_count ?? null), (n) => String(Math.round(n)))
const alertUp = useCountUp(computed(() => summary.value?.balance_alert_count ?? null), (n) => String(Math.round(n)))
// ===== D9 快捷操作:desc 与实时指标联动(替换 demo 死文案) =====
const quick = computed(() => [
{ icon: 'EditPen', label: '新建下发任务', desc: '单发 / 群发 / 模板', to: '/sms/batch', hot: false },
{
icon: 'Stamp', label: '待人工审核', to: '/audit',
desc: summary.value
? (pendingCount.value > 0 ? `${pendingCount.value} 条待审,点击进入审核中心` : '当前无待审任务')
: '— 指标加载中',
hot: pendingCount.value > 0,
},
{ icon: 'RefreshRight', label: '失败补推', desc: '按批次 / 手机号查询重推', to: '/record/repush', hot: false },
{
icon: 'Wallet', label: '余额预警', to: '/account/list',
desc: summary.value
? (alertCount.value > 0 ? `${alertCount.value} 个账号低于预警线` : '全部账号余额充足')
: '— 指标加载中',
hot: alertCount.value > 0,
},
])
// ===== 通道表语义映射(配置域真数据;badge 色沿用 demo 语义) =====
const PROTO_META: Record<string, { label: string; badge: string }> = {
cmpp: { label: 'CMPP', badge: 'violet' },
smpp: { label: 'SMPP', badge: 'ok' },
http: { label: 'HTTP', badge: 'warn' },
sgip: { label: 'SGIP', badge: 'violet' },
}
function protoLabel(p: string): string { return PROTO_META[p]?.label ?? p.toUpperCase() }
function protoBadge(p: string): string { return PROTO_META[p]?.badge ?? 'warn' }
const CARRIER_META: Record<string, string> = { cmcc: '移动', cucc: '联通', ctcc: '电信' }
function carrierLabel(c?: string): string {
if (!c) return '—'
const parts = c.split(',').map((k) => CARRIER_META[k.trim()] ?? k.trim()).filter(Boolean)
return parts.join(' / ') || '—'
}
// ===== 走势 SVG 几何(640×200 · 网格 42/94/146 · 底线 190) =====
const W = 640
const stepX = computed(() => (W - 40) / Math.max(trend.value.length - 1, 1))
function px(i: number): number { return 20 + i * stepX.value }
function py(v: number): number {
const maxV = Math.max(...trend.value.map((p) => p.sent), 1)
return 180 - (v / maxV) * 130
}
@@ -216,26 +394,86 @@ const areaPath = computed(() => {
const last = trend.value.length - 1
return `${sentPath.value} L${px(last).toFixed(1)},190 L${px(0).toFixed(1)},190 Z`
})
function dateLabel(date: string, i: number) {
// x 轴 label 抽稀(≤8 个刻度;末位"今日"恒显)
const labelEvery = computed(() => Math.max(Math.ceil(trend.value.length / 7), 1))
function showLabel(i: number): boolean { return i % labelEvery.value === 0 || i === trend.value.length - 1 }
function dateLabel(date: string, i: number): string {
return i === trend.value.length - 1 ? '今日' : date.slice(5).replace('-', '/')
}
// ===== P3 走势 hover:十字线 + 气泡(纯 SVG,无第三方依赖) =====
const hoverIdx = ref(-1)
function onTrendHover(e: MouseEvent) {
const svg = (e.currentTarget as SVGElement).ownerSVGElement
if (!svg) return
const rect = svg.getBoundingClientRect()
const x = ((e.clientX - rect.left) / rect.width) * W
const i = Math.round((x - 20) / stepX.value)
hoverIdx.value = Math.min(Math.max(i, 0), trend.value.length - 1)
}
const tipX = computed(() => {
if (hoverIdx.value < 0) return 0
return px(hoverIdx.value) > W - 190 ? px(hoverIdx.value) - 180 : px(hoverIdx.value) + 12
})
const tipY = computed(() => {
const p = trend.value[hoverIdx.value]
return p ? Math.max(py(p.sent) - 58, 4) : 0
})
watch(trend, () => { hoverIdx.value = -1 })
</script>
<style scoped lang="scss">
/* demo 指标卡补充:预警红值 + 可点击态 */
/* ---- D2 hero 决策句:tone 左光条 + 图标容器色 + 可点击态 ---- */
.hero { display: flex; align-items: center; gap: 14px; padding: 14px 18px; }
.hero--ok { border-left: 3px solid var(--gosms-primary); }
.hero--warn { border-left: 3px solid var(--gosms-amber); }
.hero--err { border-left: 3px solid var(--gosms-red); }
.hero--dim { border-left: 3px solid var(--gosms-border-strong); }
.hero--go { cursor: pointer; }
.hero--go:hover { border-color: var(--gosms-border-glow); }
.hero-ic {
width: 36px; height: 36px; border-radius: 11px; flex-shrink: 0;
display: grid; place-items: center;
background: var(--gosms-primary-soft); color: var(--gosms-primary);
}
.hero--warn .hero-ic { background: rgba(251, 191, 36, 0.1); color: var(--gosms-amber); }
.hero--err .hero-ic { background: rgba(248, 113, 113, 0.1); color: var(--gosms-red); }
.hero--dim .hero-ic { background: var(--gosms-input-veil); color: var(--gosms-text-muted); }
.hero-body { min-width: 0; flex: 1; }
.hero-text { margin: 0; font-size: 14.5px; font-weight: 600; color: var(--gosms-text-bright); }
.hero-sub { margin: 3px 0 0; font-size: 11.5px; color: var(--gosms-text-muted); }
.hero-arrow { margin-left: auto; flex-shrink: 0; color: var(--gosms-primary); font-size: 16px; }
.hero--warn .hero-arrow { color: var(--gosms-amber); }
/* ---- P2 指标卡图标容器(emoji→EP icon 对齐)与热色 ---- */
.metric .ic { display: inline-flex; color: var(--gosms-text-muted); }
.metric .ic--hot { color: var(--gosms-amber); }
.metric--click { cursor: pointer; }
.value--warn { color: var(--gosms-amber) !important; }
.value--alert { color: var(--el-color-danger) !important; }
/* demo 趋势线:teal 光晕描边(trend-svg 尺寸走 demo-base) */
/* ---- P2 快捷卡图标热色(amber 呼应 hero warn) ---- */
.qic { color: var(--gosms-primary); }
.qic--hot { background: rgba(251, 191, 36, 0.1); color: var(--gosms-amber); }
/* ---- 走势:teal 光晕描边 + P3 hover 十字线/气泡 ---- */
.trend-line { filter: drop-shadow(0 0 6px rgba(45, 212, 191, 0.4)); }
.trend-cursor { stroke: var(--gosms-primary); stroke-width: 1; stroke-dasharray: 3 3; opacity: 0.7; }
.trend-tip rect { fill: var(--gosms-glass); stroke: var(--gosms-border); }
.trend-tip text { fill: var(--gosms-text); font-size: 11px; font-family: var(--gosms-font); }
.trend-tip .tip-date { fill: var(--gosms-text-bright); font-weight: 600; }
.trend-empty { padding: 40px 0; text-align: center; color: var(--gosms-text-muted); }
/* quick-item/qic/qt/qd/arrow 全套走 demo-base 原文,此处不再翻译 */
.quick-body { display: flex; flex-direction: column; min-width: 0; flex: 1; }
/* ---- D10 脉象 chip 降级态(基类 .live-chip 在 shell.scss;button 重置) ---- */
.live-chip { border: none; cursor: pointer; font-family: inherit; }
.live-chip.stale { color: var(--gosms-amber); background: rgba(251, 191, 36, 0.1); }
.live-chip.stale i { background: var(--gosms-amber); box-shadow: 0 0 8px rgba(251, 191, 36, 0.45); }
.live-chip.dead { color: var(--gosms-red); background: rgba(248, 113, 113, 0.1); }
.live-chip.dead i { background: var(--gosms-red); box-shadow: 0 0 8px rgba(248, 113, 113, 0.45); animation: none; }
/* 通道表横向滚动兜底(窄屏) */
/* ---- 通道表(配置域快照) ---- */
.ch-scroll { overflow-x: auto; }
.text-danger { color: var(--el-color-danger); }
.text-amber { color: var(--el-color-warning); }
.ch-empty { padding: 24px 0; text-align: center; color: var(--gosms-text-muted); }
.quick-body { display: flex; flex-direction: column; min-width: 0; flex: 1; }
:deep(.dim), .dim { color: var(--gosms-text-muted); }
</style>
+7
View File
@@ -1,2 +1,9 @@
// vitest 全局 setup:注册 msw node 服务(经 vite.config test.globals 生效)
// P0(2026-11-13):vitest mode=test 不加载 .env.development → request.ts 顶层
// baseURL=undefined → msw 全量 unhandled(91/137 红)。setupFiles 先于被测模块
// 求值,此处 stub 一处生效;各 spec 内重复 stubEnv 同值无害。
import { vi } from 'vitest'
vi.stubEnv('VITE_API_BASE_URL', 'http://localhost/api/v1')
import './tests/setup'