206 Commits
Author SHA1 Message Date
hectorzhao 001d5f2cbd fix: 修复 CMPP 协议字段容量与版本兼容性
CSS quality / css-quality (push) Has been cancelled
2026-09-20 15:49:37 +08:00
hectorzhao b24cd7c08d feat: 增加模板通道拒收策略并修复运营页面 2026-09-20 15:09:57 +08:00
hectorzhao c20c2246b2 fix: 固化长短信回执终态并隔离发送尝试归属 2026-09-18 13:20:03 +08:00
hectorzhao 1676cfe622 fix: 限制有效签名名称唯一并保留批量导入补资料 2026-09-17 16:49:58 +08:00
hectorzhao 5e4d644788 feat: 重构首页回执营业统计并增加企业返还金额
CSS quality / css-quality (push) Has been cancelled
2026-09-17 13:11:35 +08:00
hectorzhao 627fa7ec97 fix: 固定跨午夜日报刷新基准并补充验收记录 2026-09-17 11:14:21 +08:00
hectorzhao 572290308c fix: 修复上行归属并实现签名质量日报优化 2026-09-17 11:12:58 +08:00
hectorzhao 4eb7b16d12 docs: record test deployment and long-message completion acceptance
CSS quality / css-quality (push) Has been cancelled
2026-09-16 19:22:16 +08:00
hectorzhao 010ba32168 fix: register supplier response waiter before reader can consume reply
CSS quality / css-quality (push) Has been cancelled
2026-09-16 19:08:42 +08:00
hectorzhao a350aca883 fix: coordinate SMS completion and improve operations diagnostics
CSS quality / css-quality (push) Has been cancelled
2026-09-16 18:27:29 +08:00
hectorzhao a0209f93bc chore: rename product to 聆界短信平台 2026-09-16 11:31:45 +08:00
hectorzhao 86cb9aea36 docs: record HTTP integration acceptance and test deployment
CSS quality / css-quality (push) Has been cancelled
2026-09-15 17:42:28 +08:00
hectorzhao cbc4a03325 fix: exclude prose colons from drainage URL boundaries
CSS quality / css-quality (push) Has been cancelled
2026-09-15 16:52:30 +08:00
hectorzhao c781313de5 feat: add HTTP signature tools and fix independent HTTP send validation
CSS quality / css-quality (push) Has been cancelled
2026-09-15 15:58:29 +08:00
hectorzhao 18ecf8045f feat: simplify HTTP request signing and publish revised client guide
CSS quality / css-quality (push) Has been cancelled
2026-09-15 14:58:31 +08:00
hectorzhao bcb278be29 docs: record client fixes test deployment and acceptance boundaries
CSS quality / css-quality (push) Has been cancelled
2026-09-14 23:29:37 +08:00
hectorzhao 4665079ca3 fix: polish client templates docs dashboard and receipt display
CSS quality / css-quality (push) Has been cancelled
2026-09-14 22:53:34 +08:00
hectorzhao 7f9abe3da0 fix: enforce drainage uniqueness and carrier-specific reporting 2026-09-14 18:12:38 +08:00
hectorzhao ac6449028c docs: close HTTP API real simulator acceptance
CSS quality / css-quality (push) Has been cancelled
2026-09-14 15:53:22 +08:00
hectorzhao 97d1334423 fix: preserve fractional timestamp input compatibility
CSS quality / css-quality (push) Has been cancelled
2026-09-14 15:20:30 +08:00
hectorzhao a420d61b23 fix: validate HTTP dates IPv6 URLs and parser errors
CSS quality / css-quality (push) Has been cancelled
2026-09-14 15:15:58 +08:00
hectorzhao 92b112cc6e fix: honor Node all-address DNS lookup for HTTP webhooks
CSS quality / css-quality (push) Has been cancelled
2026-09-14 14:03:00 +08:00
hectorzhao 40c8e279f0 docs: close HTTP API test deployment with verification evidence
CSS quality / css-quality (push) Has been cancelled
2026-09-14 13:20:37 +08:00
hectorzhao 04e9f467ab docs: record HTTP remediation validation and test release handoff
CSS quality / css-quality (push) Has been cancelled
2026-09-14 13:02:16 +08:00
hectorzhao f0e843436c feat: remediate HTTP API reliability and developer documentation
CSS quality / css-quality (push) Has been cancelled
2026-09-14 12:48:10 +08:00
hectorzhao d13ca0713a docs: record channel sensitive words test deployment
CSS quality / css-quality (push) Has been cancelled
2026-09-10 16:11:13 +08:00
hectorzhao 8e4bc5a20e feat: filter SMS routes by channel sensitive words 2026-09-10 15:50:56 +08:00
hectorzhao 86947827cc docs: record drainage test deployment and recovery evidence 2026-09-10 14:06:54 +08:00
hectorzhao 0c3f820cc9 feat: enforce signature-scoped drainage authorization before SMS submission 2026-09-10 13:29:04 +08:00
hectorzhao 5bcdbb2a03 fix: correct operational statistics and form interactions 2026-09-09 23:15:42 +08:00
hectorzhao 6d63eb5452 docs: record test and preproduction release acceptance
CSS quality / css-quality (push) Has been cancelled
2026-09-08 23:17:11 +08:00
hectorzhao 809175b544 fix: enforce production React release builds
CSS quality / css-quality (push) Has been cancelled
2026-09-08 22:39:32 +08:00
hectorzhao 6816f56178 fix: harden notification polling and simplify pagination controls 2026-09-08 21:44:08 +08:00
hectorzhao ebb185b22b fix: prevent daily report refresh timeouts
CSS quality / css-quality (push) Has been cancelled
2026-09-08 17:16:43 +08:00
hectorzhao 2a9d03be2e fix: unify analytics and report pagination controls 2026-09-08 14:52:12 +08:00
hectorzhao 6d3c78330d docs: record test release and real operations acceptance 2026-09-08 13:41:49 +08:00
hectorzhao 2c228a94e1 fix: bound formatter memory and improve operations workflows 2026-09-08 12:46:15 +08:00
hectorzhao 50ae37242b docs: 记录夜间累计审核双环境发布与验收
CSS quality / css-quality (push) Has been cancelled
2026-09-07 23:26:27 +08:00
hectorzhao 633ba59775 feat: 按企业应用累计夜间短信并复用聚合审核
CSS quality / css-quality (push) Has been cancelled
2026-09-07 22:55:29 +08:00
hectorzhao e281ff853b fix: 修复WPS图片跨节点误配并定位损坏单元格 2026-09-07 15:17:09 +08:00
hectorzhao f885f0b907 docs: 记录规则管理双环境发布与验收结果
CSS quality / css-quality (push) Has been cancelled
2026-09-06 22:44:24 +08:00
hectorzhao e4f93f7193 feat: 优化整体兜底个性化规则管理交互
CSS quality / css-quality (push) Has been cancelled
2026-09-06 22:16:09 +08:00
hectorzhao 0e3424c4a7 docs: 补记验收文档推送认证重试结果
CSS quality / css-quality (push) Has been cancelled
2026-09-06 20:36:08 +08:00
hectorzhao c51255d407 docs: 记录监控配置修复发布与告警演示验收
CSS quality / css-quality (push) Has been cancelled
2026-09-06 20:34:37 +08:00
hectorzhao 4c210723cd fix: 修复监控纳管保存并移除运行概况最近记录
CSS quality / css-quality (push) Has been cancelled
2026-09-06 20:22:48 +08:00
hectorzhao f059674852 docs: 记录发送监控与报备通知测试发布验收
CSS quality / css-quality (push) Has been cancelled
2026-09-06 20:00:21 +08:00
hectorzhao 247fee6d6b fix: 完善监控页签与通知弹窗异步交互
CSS quality / css-quality (push) Has been cancelled
2026-09-06 19:46:08 +08:00
hectorzhao 457319e627 feat: 实现发送质量监控与报备状态消息通知
CSS quality / css-quality (push) Has been cancelled
2026-09-06 19:22:49 +08:00
hectorzhao 69e3d7368d feat: 简化通道组顺序调整并过滤不可选通道 2026-09-06 15:54:27 +08:00
hectorzhao bd920f76b0 feat: 新增报备任务提醒并调整预警分组 2026-09-06 15:36:14 +08:00
hectorzhao 442dda711d docs: 记录通道组双环境发布结果
CSS quality / css-quality (push) Has been cancelled
2026-09-05 23:34:18 +08:00
hectorzhao 1e05a643e5 feat: 优化通道组编辑交互 2026-09-05 22:55:09 +08:00
hectorzhao 839dba8d9b fix: 补齐签名导入待审通知并展示通道组成本 2026-09-05 21:22:18 +08:00
hectorzhao 15a1f9d8ed docs: 记录CSS门禁修复测试环境验收 2026-09-05 09:43:50 +08:00
hectorzhao ca1fc2847f fix: 收紧CSS所有权与历史兼容门禁 2026-09-05 09:33:34 +08:00
hectorzhao 64bfb9ad3d docs: 记录CSS治理测试环境发布结果
CSS quality / css-quality (push) Has been cancelled
2026-09-05 01:05:56 +08:00
hectorzhao 798e85c930 fix: 支持归档环境执行CSS门禁
CSS quality / css-quality (push) Has been cancelled
2026-09-05 00:48:59 +08:00
hectorzhao 458ddd97df refactor: 完成全局CSS模块化治理
CSS quality / css-quality (push) Has been cancelled
2026-09-05 00:45:05 +08:00
hectorzhao 1a7a7245a6 fix: 修复报备导入映射与审核跳转 2026-09-05 00:20:33 +08:00
hectorzhao 65082959c0 docs: 记录WPS异步解析测试发布 2026-09-04 23:25:57 +08:00
hectorzhao 5925cf493b feat: 异步解析大文件WPS报备资料 2026-09-04 22:51:07 +08:00
hectorzhao aaf96db2d0 docs: finalize import review delivery status 2026-09-04 20:40:39 +08:00
hectorzhao 857171ce9d docs: record import review flow validation 2026-09-04 20:40:03 +08:00
hectorzhao 41962e7a6e fix: approve imported signature identity fields 2026-09-04 20:24:08 +08:00
hectorzhao 0ec386e674 fix: keep report field pool cards fixed height 2026-09-04 18:31:36 +08:00
hectorzhao c88d172af6 docs: record WPS test deployment evidence 2026-09-04 18:15:25 +08:00
hectorzhao bb435fb0ac docs: record WPS test deployment status 2026-09-04 17:15:54 +08:00
hectorzhao fb39c8b606 feat: support WPS report material workbooks 2026-09-04 17:10:04 +08:00
hectorzhao 48d0363920 feat: enhance operations dashboard and reporting controls 2026-09-04 16:26:22 +08:00
hectorzhao bc18c7ff12 docs: record preproduction report workbench release 2026-09-03 20:59:21 +08:00
hectorzhao dada0d978b docs: record report status page deployment 2026-09-03 17:15:57 +08:00
hectorzhao fe3c6e5b58 fix: compact report status record table 2026-09-03 16:48:56 +08:00
hectorzhao 7b8a613afa docs: record report material test deployment 2026-09-03 13:15:42 +08:00
hectorzhao 4ff6ed0786 feat: refine report material workflow states 2026-09-03 12:50:33 +08:00
hectorzhao 55915ed826 fix: refresh pending report detail summary 2026-09-03 12:33:57 +08:00
hectorzhao b0016cfd8d docs: record report batch test deployment 2026-09-03 11:21:34 +08:00
hectorzhao dc201bf92e feat: redesign report batch workflow 2026-09-03 11:04:32 +08:00
hectorzhao a50aafb1ec fix: align report workbench page actions 2026-09-03 10:09:12 +08:00
hectorzhao 19bcca812b docs: record report field batch verification 2026-09-03 09:57:49 +08:00
hectorzhao 068b8047dd fix: keep absent brief SMS content empty 2026-09-03 09:37:24 +08:00
hectorzhao fe5b25a7e4 docs: record report brief test deployment 2026-09-02 19:08:55 +08:00
hectorzhao 7cb5dd376e feat: add channel report batch briefs 2026-09-02 18:29:05 +08:00
hectorzhao 2dff1be750 docs: record high-frequency test deployment 2026-09-02 17:10:48 +08:00
hectorzhao ad89e8fed7 feat: optimize signature workflows and high-frequency queries 2026-09-02 15:45:48 +08:00
hectorzhao 9b8196ecab feat: build reporting workbench workflow 2026-09-02 14:30:15 +08:00
hectorzhao 53d3668306 docs: record test enterprise signature deployment 2026-09-02 12:10:08 +08:00
hectorzhao cd824999f3 fix: restore carrier reporting status summaries 2026-09-02 10:27:29 +08:00
hectorzhao 9e34757d6f feat: densify enterprise signature management 2026-09-02 10:04:58 +08:00
hectorzhao 1f2dfb5caf fix: deduplicate filesystem mounts in monitoring 2026-08-31 23:39:24 +08:00
hectorzhao 12668cee87 docs: record preproduction release after data migration 2026-08-31 23:15:50 +08:00
hectorzhao 9a15d28da5 fix: preserve migrated storage guards during deployment 2026-08-31 23:01:35 +08:00
hectorzhao fd373d9708 docs: record six fixes test deployment verification 2026-08-31 12:31:05 +08:00
hectorzhao b0deef5e6e fix: align reporting fields queries and disk monitoring 2026-08-31 12:19:39 +08:00
hectorzhao 119d57772e docs: record preproduction split architecture upgrade 2026-08-30 22:02:42 +08:00
hectorzhao 1a5063a5d9 fix: ack protocol logs after complete flush 2026-08-30 21:54:33 +08:00
hectorzhao 67774509d9 docs: record preproduction drainage release 2026-08-30 21:19:55 +08:00
hectorzhao 4d526b83ab docs: record drainage UI test deployment 2026-08-28 18:04:19 +08:00
hectorzhao 5328bb09bf fix: accept scheme-less drainage URLs 2026-08-28 17:58:45 +08:00
hectorzhao c68ac7a3db feat: unify drainage targets and carrier status UI 2026-08-28 17:24:01 +08:00
hectorzhao 9ac41e9308 test: close remaining quality verification gaps 2026-08-28 16:27:00 +08:00
hectorzhao 3834d67a30 docs: record quality release evidence 2026-08-28 15:00:01 +08:00
hectorzhao 226527f1ce fix: align npm locks with test runtime 2026-08-28 14:41:51 +08:00
hectorzhao ad27acad7e refactor: strengthen client boundaries and quality gates 2026-08-28 14:26:58 +08:00
hectorzhao 3af145abe5 docs: record code quality remediation rollout 2026-08-28 12:23:17 +08:00
hectorzhao fc4a6a7afc fix: enforce strong hashes in maintenance tools 2026-08-28 12:00:55 +08:00
hectorzhao d85ff85999 chore: add rollback-safe password rollout window 2026-08-28 11:47:08 +08:00
hectorzhao 2744690f9f fix: harden tenant auth and quality gates 2026-08-28 11:44:16 +08:00
hectorzhao c3bf8af3e6 docs: record dashboard direct-text deployment 2026-08-28 10:35:13 +08:00
hectorzhao 0b84370270 fix: remove dashboard amount wrappers 2026-08-28 10:27:31 +08:00
hectorzhao 171c7d38e8 docs: record dashboard metrics deployment 2026-08-28 10:20:38 +08:00
hectorzhao a70e9e2c07 fix: align client dashboard metrics 2026-08-28 10:14:31 +08:00
hectorzhao 4d4c1f39d4 docs: record client billing test deployment 2026-08-28 09:44:57 +08:00
hectorzhao 5bd347e010 fix: normalize client billing presentation 2026-08-28 09:37:59 +08:00
hectorzhao 088d7aaacb docs: record amount and log-filter deployment 2026-08-27 20:11:09 +08:00
hectorzhao 33fa3709d9 fix: clarify client amounts and log date filters 2026-08-27 19:50:12 +08:00
hectorzhao ec721bf95a docs: record test deployment verification 2026-08-27 18:48:04 +08:00
hectorzhao 070a951e7c fix: allow explicit HTTP origin in test environments 2026-08-27 18:32:21 +08:00
hectorzhao 01cffa4758 feat: refine client status and review views 2026-08-27 17:32:05 +08:00
hectorzhao d6edb88b76 fix: recover gateway callbacks and client send flows 2026-08-27 14:30:02 +08:00
hectorzhao a280b4bb22 feat: densify sms records and improve uplink matching 2026-08-27 10:15:08 +08:00
hectorzhao 898471423f fix: hide deleted signatures and fit uplink table 2026-08-26 16:10:46 +08:00
hectorzhao 444c65288c docs: record preproduction monitoring repair 2026-08-26 14:44:25 +08:00
hectorzhao 5234812990 fix: escape node exporter unit filter 2026-08-26 14:41:52 +08:00
hectorzhao c769b60aaa fix: allow verified offline monitoring releases 2026-08-26 14:33:44 +08:00
hectorzhao b0bdb608c1 fix: support preproduction monitoring on arm64 2026-08-26 14:25:31 +08:00
hectorzhao b7ae1aa41a fix: restore channels after gateway restart 2026-08-26 14:04:44 +08:00
hectorzhao 8170f727a3 fix: default gateway callback batching off 2026-08-26 13:59:21 +08:00
hectorzhao 4a17df78b8 fix: audit submissions disabled after bind 2026-08-25 19:54:41 +08:00
hectorzhao 2a181777ad docs: record test environment send guard regressions 2026-08-25 19:38:17 +08:00
hectorzhao b1e297245c docs: record tenant batching capacity results 2026-08-25 18:10:37 +08:00
hectorzhao b5005f21d5 fix: make downstream connection events idempotent 2026-08-25 17:53:05 +08:00
hectorzhao 394949f9f6 fix: align api keepalive with gateway pool 2026-08-25 17:35:18 +08:00
hectorzhao 76e7c8c401 perf: batch inbound workflows by tenant 2026-08-25 17:11:55 +08:00
hectorzhao d3ceeb1e16 docs: diagnose paid single-tenant throughput ceiling 2026-08-25 16:38:59 +08:00
hectorzhao 9292352be1 perf: expand gateway capacity and prevent receipt replay 2026-08-25 16:08:30 +08:00
hectorzhao 761c123b65 perf: batch gateway submits and isolate callbacks 2026-08-25 11:39:59 +08:00
hectorzhao c6f11014d6 test: verify CMPP send guards and channel retry 2026-08-21 12:05:47 +08:00
hectorzhao 03f72c87de docs: record CMPP main flow regression 2026-08-21 11:40:26 +08:00
hectorzhao 2b5256d4a1 docs: record phase four paid stress results 2026-08-21 11:18:19 +08:00
hectorzhao 90345fba22 perf: coalesce batch progress refreshes 2026-08-21 11:07:20 +08:00
hectorzhao 3c6f1beed1 perf: collapse short submit result callbacks 2026-08-21 10:46:27 +08:00
hectorzhao fcf6d3e6b4 perf: remove paid result account lock contention 2026-08-21 10:40:28 +08:00
hectorzhao 487b5282a6 perf: batch paid CMPP accounting and weighted routes 2026-08-21 10:25:40 +08:00
hectorzhao 0176aa6952 docs: record CMPP phase three pressure results 2026-08-21 09:56:31 +08:00
hectorzhao 52028b9bbd perf: batch CMPP inbound workflow processing 2026-08-21 09:44:51 +08:00
hectorzhao 57192b7586 docs: record CMPP phase two pressure results 2026-08-20 19:13:46 +08:00
hectorzhao f4560479d3 fix: type CMPP inbox JSON parameters 2026-08-20 19:04:12 +08:00
hectorzhao 99fb346566 perf: merge CMPP inbox validation and persistence 2026-08-20 18:55:09 +08:00
hectorzhao 633e7a7055 docs(cmpp): record phase one capacity ceiling 2026-08-20 18:39:29 +08:00
hectorzhao 229a0b28fd perf(cmpp): reserve transport for inbound submit 2026-08-20 18:23:01 +08:00
hectorzhao 6708f1f7c5 perf(cmpp): isolate inbound transport capacity 2026-08-20 18:09:29 +08:00
hectorzhao 53073461e9 fix(cmpp): honor UTC inbox retry leases 2026-08-20 17:50:00 +08:00
hectorzhao 0b63bcd74e perf(cmpp): add durable inbound fast path 2026-08-20 17:34:45 +08:00
hectorzhao 26ef67fb6a docs(test): record v5 pressure and priority results 2026-08-20 16:26:44 +08:00
hectorzhao 14f993c1f8 perf(cmpp): reduce inbound database round trips 2026-08-20 15:29:45 +08:00
hectorzhao 67b760a599 perf(cmpp): decouple supplier result callbacks 2026-08-20 14:19:42 +08:00
hectorzhao 485af688d2 docs(cmpp): record V3 test pressure results 2026-08-20 12:34:08 +08:00
hectorzhao e9c73333b3 fix(cmpp): preserve inbound window after message registration 2026-08-20 12:08:49 +08:00
hectorzhao 0757a699ff perf(cmpp): process inbound submits within client window 2026-08-20 11:45:16 +08:00
hectorzhao b9a71fe0b9 perf(cmpp): instrument inbound flow and unbatch submit worker 2026-08-20 11:27:35 +08:00
hectorzhao c4f36fc50d docs: record monitoring read deployment 2026-08-16 15:11:52 +08:00
hectorzhao 482f7ac1ae feat: add monitoring alert read state 2026-08-16 15:04:26 +08:00
hectorzhao 79f5d3f215 docs: record monitoring test deployment 2026-08-14 18:05:19 +08:00
hectorzhao 2216d00d51 fix: preserve Prometheus rule group access 2026-08-14 18:02:42 +08:00
hectorzhao 0cd09441da fix: guard configurable monitoring ratios 2026-08-14 17:59:22 +08:00
hectorzhao 6ccc102830 feat: add configurable infrastructure alerts 2026-08-14 17:51:42 +08:00
hectorzhao 1ef4380422 feat: 完善服务监控与下游重投 2026-08-14 17:21:29 +08:00
hectorzhao d30d9ea4d0 feat: add Fail2ban security detection console 2026-08-14 10:58:18 +08:00
hectorzhao b78faa1aa2 feat: add Prometheus system monitoring 2026-08-14 10:10:28 +08:00
hectorzhao 96e475d60d docs: record downstream requeue release 2026-08-13 12:13:41 +08:00
hectorzhao 433b2ee56f feat: harden downstream requeue tasks 2026-08-13 12:05:57 +08:00
hectorzhao 67fee21616 feat: refine operations UI and transport limits 2026-08-13 10:42:59 +08:00
hectorzhao fb02cbcf39 docs: 记录签名质量热修复发布 2026-08-12 17:56:26 +08:00
hectorzhao 4c70978da4 fix: 修复未报备签名聚合查询 2026-08-12 17:53:30 +08:00
hectorzhao 16135e5a3e style: 更新运营商标签配色 2026-08-12 17:22:43 +08:00
hectorzhao 4994841709 feat: 增强下游重投与签名质量检测 2026-08-12 17:05:53 +08:00
hectorzhao 1d8d6701a6 docs: 记录通道界面优化部署 2026-08-12 13:25:26 +08:00
hectorzhao f350bf5ef3 feat: 优化通道运营商与金额展示 2026-08-12 13:16:25 +08:00
hectorzhao dc358798e9 docs: 记录签名热力图预发布结果 2026-08-12 11:57:25 +08:00
hectorzhao 0cd353450a feat: 优化签名热力图与金额展示 2026-08-12 11:41:47 +08:00
hectorzhao e64b5e23fe docs: record legacy signature migration deployment 2026-08-10 22:59:16 +08:00
hectorzhao 2ecb24cf8d feat: remove legacy signature confirmation 2026-08-10 22:40:13 +08:00
hectorzhao 827d8921a8 docs: record signature retirement deployment 2026-08-10 21:06:09 +08:00
hectorzhao 0eb27e4ac0 fix: wait for services during deployment 2026-08-10 21:00:18 +08:00
hectorzhao 55aa054005 feat: add carrier-aware signature retirement alerts 2026-08-10 20:54:05 +08:00
hectorzhao 232d1c22a3 revert: roll back signature quality period trends 2026-08-09 23:24:50 +08:00
hectorzhao e0c8f82bcf docs: record 35de17a2 preproduction deployment 2026-08-09 23:03:02 +08:00
hectorzhao 35de17a2d4 feat: add signature quality period trends 2026-08-09 22:54:32 +08:00
hectorzhao 608662a054 docs: record 78b839f4 preproduction deployment 2026-08-09 21:04:25 +08:00
hectorzhao 78b839f468 feat: refine template deletion and channel group filters 2026-08-09 20:54:52 +08:00
hectorzhao 482d332f49 docs: record 7804f64c preproduction deployment 2026-08-09 19:17:04 +08:00
hectorzhao 7804f64ced feat: support governed cascade deletion 2026-08-09 19:08:38 +08:00
hectorzhao 6add563ee8 docs: record preproduction deployment for 4724b9db 2026-08-09 15:11:15 +08:00
hectorzhao 4724b9db6a feat: improve operations diagnostics and channel management 2026-08-09 14:27:19 +08:00
hectorzhao 44352aeb2f docs: record RealeseV2.3 preproduction deployment 2026-08-06 11:32:32 +08:00
hectorzhao 8ad8e61793 release: prepare RealeseV2.3 2026-08-06 10:48:36 +08:00
hectorzhao 57b58f1c40 docs: record 530a65de preproduction release 2026-08-03 16:36:04 +08:00
hectorzhao 530a65de80 feat: integrate analytics and fragment receipt improvements 2026-08-03 15:34:41 +08:00
hectorzhao 3357ace7e1 docs: record 94e997ec preproduction release 2026-08-02 20:46:22 +08:00
hectorzhao 94e997ec4d fix: improve retry feedback and deletion stability 2026-08-02 20:39:49 +08:00
hectorzhao ecc3d7a504 docs: record 37ffce40 preproduction release 2026-07-31 23:51:50 +08:00
hectorzhao 37ffce40b2 docs: record successful workspace push 2026-07-31 22:57:39 +08:00
hectorzhao 4b9127e1ab docs: record remote authentication blocker 2026-07-31 22:28:31 +08:00
hectorzhao 461a65f810 docs: record ca4f591a validation and push scope 2026-07-31 22:26:08 +08:00
hectorzhao ca4f591a13 feat: add phone frequency controls and modularize codebase 2026-07-31 22:25:23 +08:00
hectorzhao 0af671b4ed docs: record c0a4317a preproduction release 2026-07-29 22:58:06 +08:00
837 changed files with 155579 additions and 39720 deletions
+28
View File
@@ -8,13 +8,31 @@ REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_URL=redis://127.0.0.1:6379
HTTP_API_MASTER_KEY=replace-with-at-least-32-random-characters
# Customer-facing HTTP API origin returned by the real backend and shown in copied integration parameters.
HTTP_API_PUBLIC_ORIGIN=https://api.example.com
# Keep false in production. Only isolated test environments without TLS may opt in to HTTP.
HTTP_API_ALLOW_INSECURE_ORIGIN=false
API_ENABLE_SEND_WORKER=true
API_SEND_WORKER_CONCURRENCY=50
API_WORKER_DATABASE_URL=
API_WORKER_METRICS_HOST=127.0.0.1
API_WORKER_METRICS_PORT=9465
CMPP_INBOUND_FAST_PATH_ENABLED=true
CMPP_INBOUND_WORKFLOW_WORKER_ENABLED=true
API_INBOUND_WORKFLOW_CONCURRENCY=32
API_INBOUND_WORKFLOW_BATCH_ENABLED=true
API_INBOUND_WORKFLOW_BATCH_SIZE=64
API_INBOUND_WORKFLOW_POLL_INTERVAL_MS=100
API_INBOUND_WORKFLOW_STALE_SECONDS=300
ADMIN_SESSION_IDLE_TIMEOUT_MS=3600000
CLIENT_SESSION_IDLE_TIMEOUT_MS=7200000
SESSION_LOCK_RECOVERY_MS=14400000
SESSION_ABSOLUTE_TIMEOUT_MS=43200000
SESSION_RECENT_AUTH_MS=1800000
# First-rollout safety only: both values must be set and the deadline must be within two hours.
# Omit them during normal operation so all password writes use scrypt.
PASSWORD_HASH_LEGACY_TRANSITION=false
PASSWORD_HASH_LEGACY_WRITE_UNTIL=
OPERATION_LOG_ARCHIVE_ENABLED=true
OPERATION_LOG_RETENTION_DAYS=180
OPERATION_LOG_ARCHIVE_BATCH_SIZE=1000
@@ -23,6 +41,9 @@ OPERATION_LOG_ARCHIVE_INTERVAL_MS=86400000
SMS_RECEIPT_TIMEOUT_SCAN_ENABLED=true
SMS_RECEIPT_TIMEOUT_HOURS=72
SMS_RECEIPT_TIMEOUT_SCAN_INTERVAL_MS=300000
# System monitoring reads only fixed queries from a loopback Prometheus instance.
PROMETHEUS_URL=http://127.0.0.1:9090
PROMETHEUS_QUERY_TIMEOUT_MS=5000
# Local HTTP development only. Production must use HTTPS and true.
SESSION_COOKIE_SECURE=false
MINIO_ENDPOINT=localhost:9000
@@ -37,4 +58,11 @@ GATEWAY_CMPP_VERSION=3.0
GATEWAY_CMPP_ADDR=127.0.0.1:7890
GATEWAY_CMPP_USER=900001
GATEWAY_CMPP_PASSWORD=888888
GATEWAY_SUBMIT_WORKER_CONCURRENCY=64
GATEWAY_SUBMIT_RESULT_STREAM=gateway.submit.results
GATEWAY_SUBMIT_RESULT_GROUP=cmpp-api-callback
GATEWAY_SUBMIT_RESULT_CONSUMER=gateway-1
GATEWAY_SUBMIT_RESULT_WORKER_CONCURRENCY=8
GATEWAY_CALLBACK_BATCH_ENABLED=false
GATEWAY_CMPP_INBOUND_MAX_CONCURRENCY=64
CMPP_DOWNSTREAM_ACK_TIMEOUT_SECONDS=30
+36
View File
@@ -0,0 +1,36 @@
name: CSS quality
on:
pull_request:
push:
branches: [main]
jobs:
css-quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- run: npm ci
- name: Resolve the complete change range
env:
EVENT_NAME: ${{ github.event_name }}
PR_BASE: ${{ github.event.pull_request.base.sha }}
PUSH_BEFORE: ${{ github.event.before }}
run: |
if [ "$EVENT_NAME" = pull_request ]; then
base=$(git merge-base "$PR_BASE" HEAD)
elif [ "$PUSH_BEFORE" = 0000000000000000000000000000000000000000 ]; then
base=$(git hash-object -t tree /dev/null)
else
git cat-file -e "$PUSH_BEFORE^{commit}"
base=$PUSH_BEFORE
fi
echo "QUALITY_BASE_REF=$base" >> "$GITHUB_ENV"
- name: Verify changed formatting and CSS ownership
run: npm run format:check && npm run style:check && npm run css:verify
+7
View File
@@ -12,8 +12,15 @@ yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
logs/
coverage/
gateway/gateway.exe
dump.rdb
*.tsbuildinfo
outputs/
tmp_*.py
tmp_*.ps1
tmp_*.sh
.DS_Store
Thumbs.db
+7
View File
@@ -0,0 +1,7 @@
node_modules
dist
coverage
api/dist
api/vendor
package-lock.json
docs
+5
View File
@@ -0,0 +1,5 @@
{
"printWidth": 120,
"singleQuote": true,
"trailingComma": "all"
}
+74
View File
@@ -0,0 +1,74 @@
{
"extends": ["stylelint-config-standard"],
"ignoreFiles": ["dist/**/*.css"],
"rules": {
"alpha-value-notation": null,
"color-function-notation": null,
"declaration-block-single-line-max-declarations": null,
"media-feature-range-notation": null,
"no-descending-specificity": null,
"selector-class-pattern": null
},
"overrides": [
{
"files": [
"src/apps/admin/channels/AdminChannelsPage.css",
"src/apps/admin/enterprise-applications/AdminEnterpriseApplicationsPage.css",
"src/apps/admin/security-detection/AdminSecurityDetectionPage.css",
"src/apps/admin/sms-records/AdminSmsRecordsPage.css",
"src/apps/admin/sms-task-progress/AdminSmsTaskProgressPage.css",
"src/apps/admin/system-monitoring/AdminSystemMonitoringPage.css",
"src/apps/client/ClientUsersPage.css",
"src/styles/admin.css",
"src/styles/client.css",
"src/styles/components.css",
"src/styles/domains/01-operations-dashboard.css",
"src/styles/domains/02-client-sending.css",
"src/styles/domains/03-client-records.css",
"src/styles/domains/04-signatures.css",
"src/styles/domains/05-templates.css",
"src/styles/domains/06-auth-enterprise.css",
"src/styles/domains/07-admin-operations.css",
"src/styles/domains/08-reporting.css",
"src/styles/domains/09-channels.css",
"src/styles/domains/10-signature-quality.css",
"src/styles/domains/11-deliveries-reporting.css",
"src/styles/domains/12-admin-configuration.css",
"src/styles/domains/13-client-signatures.css",
"src/styles/domains/14-responsive-requeue.css",
"src/styles/domains/index.css",
"src/styles/reset.css",
"src/styles/shell.css",
"src/styles/tokens.css"
],
"rules": {
"at-rule-empty-line-before": null,
"block-no-empty": null,
"color-function-alias-notation": null,
"color-hex-length": null,
"comment-empty-line-before": null,
"custom-property-pattern": null,
"declaration-block-no-redundant-longhand-properties": null,
"declaration-empty-line-before": null,
"declaration-property-value-keyword-no-deprecated": null,
"font-family-name-quotes": null,
"function-url-quotes": null,
"import-notation": null,
"keyframes-name-pattern": null,
"length-zero-no-unit": null,
"no-duplicate-selectors": null,
"number-max-precision": null,
"property-no-vendor-prefix": null,
"rule-empty-line-before": null,
"selector-attribute-quotes": null,
"selector-id-pattern": null,
"selector-not-notation": null,
"selector-pseudo-class-no-unknown": null,
"selector-type-no-unknown": null,
"shorthand-property-no-redundant-values": null,
"value-keyword-case": null,
"value-no-vendor-prefix": null
}
}
]
}
+44
View File
@@ -0,0 +1,44 @@
# 聆界短信平台仓库开发约束
本文件适用于整个仓库。进入子目录工作时,如果存在更具体的 `AGENTS.md`,还应同时遵守子目录规范。
## 开始工作前
- 先检查当前分支、最近提交、远端差异以及 staged、unstaged、untracked 文件。
- 保留其他会话和用户已有修改;禁止未经授权执行 reset、清理、覆盖、切分支、推送或部署。
- 功能事实必须以当前代码、真实 API、PostgreSQL、Redis、MinIO、Gateway 和目标环境为准,交接记录只作为线索。
- 不得发送、补发、重投或重新入队短信;不得擅自修改余额、通道或客户配置。
## CSS 任务强制阅读
凡新增、修改、迁移或审查 CSS,必须先完整阅读:
1. `docs/css-development-guidelines.md`
2. 涉及存量拆分时,再阅读 `docs/global-css-modularization-plan-20260904.md`
## CSS 所有权
- 设计变量归 `src/styles/tokens.css`
- 浏览器重置和标签基础规则归 `src/styles/reset.css`
- AppShell、侧栏、顶栏、导航和页面骨架归 `src/styles/shell.css`
- 跨业务复用且语义一致的公共组件样式归 `src/styles/components/`;迁移完成前的既有公共规则可继续位于明确登记的共享样式文件。
- 同一业务域多个页面共享的样式归业务域目录,并由业务域根类名限定。
- 只服务一个页面、弹窗或局部组件的样式必须放在其 TSX 同目录或对应业务目录,由所有者直接 import。
- `src/styles/global.css` 是存量兼容文件:只允许迁出、删除和保持视觉等价所必需的修正,不得新增页面或业务选择器。例外必须在变更说明中写明原因、影响范围和清理条件。
## CSS 禁止事项
- 禁止把新页面、新弹窗或新业务组件的选择器写入 `global.css`
- 禁止使用无业务根节点限定的标签选择器或短通用类名影响其他页面。
- 禁止通过新增 `!important`、提高 specificity 或依赖偶然加载顺序掩盖归属和级联问题;第三方不可控样式等例外必须记录原因、影响范围和移除条件。
- 禁止把公共组件样式建立在业务页面样式之上。
- 禁止对 `global.css` 执行整文件格式化,或在迁移提交中夹带视觉改版和无关重排。
- 禁止仅凭类名前缀批量移动选择器;必须同时核对 TSX 引用、其他 CSS 定义、媒体查询和真实 DOM。
## CSS 变更验收
- 提交前检查 staged diff,确保只包含本轮目标文件或精确 hunk。
- 运行与范围匹配的定向测试、前端全量测试、TypeScript、生产构建、仓库当前提供的格式和样式门禁以及 `git diff --check`;自动门禁尚未覆盖的项目按日常规范人工检查并记录。
- 页面级变更至少检查 1600×1000、1366×768 和 390×844;覆盖首次进入、刷新、跨路由切换及相关交互状态。
- 使用真实 API 和测试环境完成最终功能验收;构建成功、组件测试或隔离截图不能代替真实页面验收。
- 纯 CSS 拆分不得改变计算样式。发现差异时先恢复原级联关系,不得顺手调整设计。
+8
View File
@@ -9,4 +9,12 @@ module.exports = {
testMatch: ['**/*.spec.ts'],
moduleFileExtensions: ['ts', 'js', 'json'],
clearMocks: true,
coverageThreshold: {
global: {
statements: 59,
branches: 50,
functions: 60,
lines: 62,
},
},
};
+17
View File
@@ -0,0 +1,17 @@
const base = require('./jest.config.cjs');
module.exports = {
...base,
collectCoverageFrom: [
'src/auth/auth.service.ts',
'src/auth/session.service.ts',
'src/common/bounded-json-object.validator.ts',
'src/files/client-files.dto.ts',
'src/open-api/client-open-api.dto.ts',
'src/operations/client-operations.dto.ts',
'src/users/client-user.dto.ts',
],
coverageThreshold: {
global: { statements: 80, branches: 70, functions: 80, lines: 80 },
},
};
+178 -107
View File
@@ -12,7 +12,7 @@
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.1.28",
"@nestjs/swagger": "^11.2.3",
"@nestjs/swagger": "11.4.7",
"@prisma/adapter-pg": "^7.9.0",
"@prisma/client": "^7.9.0",
"brace-expansion": "file:vendor/brace-expansion-compat",
@@ -21,12 +21,15 @@
"class-validator": "^0.14.3",
"exceljs": "^4.4.0",
"ioredis": "^5.11.1",
"jszip": "^3.10.1",
"minio": "^8.0.7",
"pg": "^8.22.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2"
"rxjs": "^7.8.2",
"tldts": "^7.4.12"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/jest": "^30.0.0",
"@types/node": "^25.9.3",
"jest": "^30.4.2",
@@ -617,35 +620,38 @@
}
},
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
"integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
"version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz",
"integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.1",
"@emnapi/wasi-threads": "1.2.3",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
"integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
"version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
"integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz",
"integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"tslib": "^2.4.0"
}
@@ -732,30 +738,6 @@
"node": ">=8"
}
},
"node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
"integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
"dev": true,
"license": "MIT",
"dependencies": {
"sprintf-js": "~1.0.2"
}
},
"node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": {
"version": "3.15.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz",
"integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==",
"dev": true,
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
},
"bin": {
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/@istanbuljs/schema": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz",
@@ -1451,20 +1433,20 @@
}
},
"node_modules/@nestjs/swagger": {
"version": "11.4.5",
"resolved": "https://registry.npmjs.org/@nestjs/swagger/-/swagger-11.4.5.tgz",
"integrity": "sha512-lvndlJmWBVDOUT0uEtLi6sSpW1syK2/nbAlHBhiELBORMpJGe9+EiWAT9qHtB10jW91L2Jmlwkr0/lttsYZrig==",
"version": "11.4.7",
"resolved": "https://registry.npmjs.org/@nestjs/swagger/-/swagger-11.4.7.tgz",
"integrity": "sha512-QyDYnmfP4IRucgmtQxMqzgRBdWtjFoDp8eFvvgf92+3wdLCL+Q0xOFO1948j/ntW/Wi7qT2dyck6ka8ADzPWQQ==",
"license": "MIT",
"dependencies": {
"@microsoft/tsdoc": "0.16.0",
"@nestjs/mapped-types": "2.1.1",
"js-yaml": "4.3.0",
"js-yaml": "5.3.0",
"lodash": "4.18.1",
"path-to-regexp": "8.4.2",
"swagger-ui-dist": "5.32.8"
"swagger-ui-dist": "5.32.13"
},
"peerDependencies": {
"@fastify/static": "^8.0.0 || ^9.0.0",
"@fastify/static": "^8.0.0 || ^9.0.0 || ^10.0.0",
"@nestjs/common": "^11.0.1",
"@nestjs/core": "^11.0.1",
"class-transformer": "*",
@@ -2031,6 +2013,27 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/body-parser": {
"version": "1.19.6",
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
"integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/connect": "*",
"@types/node": "*"
}
},
"node_modules/@types/connect": {
"version": "3.4.38",
"resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
"integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/d3-array": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz",
@@ -2120,6 +2123,31 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/@types/express": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
"integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/body-parser": "*",
"@types/express-serve-static-core": "^5.0.0",
"@types/serve-static": "^2"
}
},
"node_modules/@types/express-serve-static-core": {
"version": "5.1.3",
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz",
"integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/qs": "*",
"@types/range-parser": "*",
"@types/send": "*"
}
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
@@ -2127,6 +2155,13 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/@types/http-errors": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",
"integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/istanbul-lib-coverage": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
@@ -2192,6 +2227,20 @@
"pg-types": "^2.2.0"
}
},
"node_modules/@types/qs": {
"version": "6.15.1",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",
"integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/range-parser": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",
"integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "19.2.17",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
@@ -2202,6 +2251,27 @@
"csstype": "^3.2.2"
}
},
"node_modules/@types/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",
"integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/serve-static": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",
"integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/http-errors": "*",
"@types/node": "*"
}
},
"node_modules/@types/stack-utils": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz",
@@ -2345,9 +2415,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2362,9 +2429,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2379,9 +2443,6 @@
"loong64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2396,9 +2457,6 @@
"loong64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2413,9 +2471,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2430,9 +2485,6 @@
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2447,9 +2499,6 @@
"riscv64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2464,9 +2513,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2481,9 +2527,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2498,9 +2541,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2540,6 +2580,40 @@
"node": ">=14.0.0"
}
},
"node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
"integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.1",
"tslib": "^2.4.0"
}
},
"node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/runtime": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
"integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
"integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@unrs/resolver-binding-win32-arm64-msvc": {
"version": "1.12.2",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.12.2.tgz",
@@ -3263,9 +3337,9 @@
},
"node_modules/brace-expansion-safe": {
"name": "brace-expansion",
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz",
"integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==",
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
@@ -4510,20 +4584,6 @@
"node": ">=8"
}
},
"node_modules/esprima": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
"dev": true,
"license": "BSD-2-Clause",
"bin": {
"esparse": "bin/esparse.js",
"esvalidate": "bin/esvalidate.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
@@ -4742,9 +4802,9 @@
"license": "MIT"
},
"node_modules/fast-uri": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz",
"integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==",
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
"integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
"devOptional": true,
"funding": [
{
@@ -6170,9 +6230,9 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
"funding": [
{
"type": "github",
@@ -8208,13 +8268,6 @@
"node": ">= 10.x"
}
},
"node_modules/sprintf-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/sqlstring": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
@@ -8520,9 +8573,9 @@
}
},
"node_modules/swagger-ui-dist": {
"version": "5.32.8",
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.32.8.tgz",
"integrity": "sha512-dgMdWXIgnI4zX4OPhKEdWnlDODbgm8W3AX0Ivn/BBqcUh6xZsBxhZMnvk6DJyRz1BTrj8dPxtarmEGgkz30oyA==",
"version": "5.32.13",
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.32.13.tgz",
"integrity": "sha512-qQobzb3DeC2LeK0j3E8812Ef4aIq1y9flJxvZkimkqUC/w4u7wS+yCc+VakqGJLweUUBrI24effhwo8OsAvNAw==",
"license": "Apache-2.0",
"dependencies": {
"@scarf/scarf": "=1.4.0"
@@ -8626,6 +8679,24 @@
"readable-stream": "3"
}
},
"node_modules/tldts": {
"version": "7.4.12",
"resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.12.tgz",
"integrity": "sha512-WylhSDKVeYnWXL3a+vKTaOxjnOeEGw938hImY8zoRWJjRRK/Jp1K+IihBzIONpUmW4e3WmXT6q5FW6vlESVZCA==",
"license": "MIT",
"dependencies": {
"tldts-core": "^7.4.12"
},
"bin": {
"tldts": "bin/cli.js"
}
},
"node_modules/tldts-core": {
"version": "7.4.12",
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.12.tgz",
"integrity": "sha512-nYNzS2WRf4QJmjzFFgAxLOBjyBxAGRbCy9PVBPaglcYyYajh40VBn+v5Ngr96ZMc7oM0+aCJdtQnNejvdBnXMQ==",
"license": "MIT"
},
"node_modules/tmp": {
"version": "0.2.7",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",
@@ -9523,10 +9594,10 @@
"node_modules/zip-stream/node_modules/minimatch/vendor/brace-expansion-compat": {},
"vendor/brace-expansion-compat": {
"name": "brace-expansion",
"version": "5.0.8-compat.1",
"version": "5.0.9-compat.1",
"license": "MIT",
"dependencies": {
"brace-expansion-safe": "npm:brace-expansion@5.0.8"
"brace-expansion-safe": "npm:brace-expansion@5.0.9"
}
}
}
+11 -3
View File
@@ -6,9 +6,12 @@
"scripts": {
"build": "tsc -p tsconfig.build.json",
"test": "jest --runInBand",
"test:coverage": "jest --runInBand --coverage",
"test:incremental-coverage": "jest --runInBand --coverage --config jest.incremental.config.cjs",
"test:watch": "jest --watch",
"start": "node dist/main.js",
"start:dev": "ts-node src/main.ts",
"start:report-material-worker": "node dist/report-material-analysis-worker.js",
"prisma:generate": "prisma generate",
"prisma:migrate:dev": "prisma migrate dev",
"prisma:migrate:deploy": "prisma migrate deploy"
@@ -18,7 +21,7 @@
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.1.28",
"@nestjs/swagger": "^11.2.3",
"@nestjs/swagger": "11.4.7",
"@prisma/adapter-pg": "^7.9.0",
"@prisma/client": "^7.9.0",
"bullmq": "^5.79.2",
@@ -27,12 +30,15 @@
"brace-expansion": "file:vendor/brace-expansion-compat",
"exceljs": "^4.4.0",
"ioredis": "^5.11.1",
"jszip": "^3.10.1",
"minio": "^8.0.7",
"pg": "^8.22.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2"
"rxjs": "^7.8.2",
"tldts": "^7.4.12"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/jest": "^30.0.0",
"@types/node": "^25.9.3",
"jest": "^30.4.2",
@@ -46,6 +52,8 @@
"exceljs": {
"uuid": "11.1.1"
},
"find-my-way": "9.7.0"
"find-my-way": "9.7.0",
"fast-uri": "3.1.5",
"js-yaml": "4.3.1"
}
}
+7 -3
View File
@@ -1,13 +1,17 @@
import { defineConfig } from 'prisma/config';
const databaseUrl = process.env.DATABASE_URL?.trim();
const allowDevelopmentDefault = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test';
if (!databaseUrl && !allowDevelopmentDefault) {
throw new Error('DATABASE_URL is required outside development and test environments');
}
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url:
process.env.DATABASE_URL ??
'postgresql://cmpp:cmpp_password@localhost:5432/cmpp_platform?schema=public',
url: databaseUrl ?? 'postgresql://cmpp:cmpp_password@localhost:5432/cmpp_platform?schema=public',
},
});
@@ -0,0 +1,131 @@
CREATE TABLE "PhoneFrequencyHit" (
"id" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"ruleId" TEXT,
"ruleCode" TEXT NOT NULL,
"ruleName" TEXT NOT NULL,
"phoneNumber" TEXT NOT NULL,
"thresholdValue" INTEGER NOT NULL,
"actualValue" INTEGER NOT NULL,
"windowStartedAt" TIMESTAMP(3) NOT NULL,
"windowEndsAt" TIMESTAMP(3) NOT NULL,
"generation" INTEGER NOT NULL DEFAULT 0,
"action" TEXT NOT NULL DEFAULT 'block',
"sourceType" TEXT,
"releasedAt" TIMESTAMP(3),
"releasedById" TEXT,
"releaseReason" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "PhoneFrequencyHit_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "PhoneFrequencyState" (
"id" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"ruleId" TEXT,
"ruleCode" TEXT NOT NULL,
"phoneNumber" TEXT NOT NULL,
"windowStartedAt" TIMESTAMP(3) NOT NULL,
"windowEndsAt" TIMESTAMP(3) NOT NULL,
"count" INTEGER NOT NULL DEFAULT 0,
"generation" INTEGER NOT NULL DEFAULT 0,
"activeHitId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "PhoneFrequencyState_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "PhoneFrequencyHit_applicationId_ruleCode_phoneNumber_windowStartedAt_generation_key"
ON "PhoneFrequencyHit"("applicationId", "ruleCode", "phoneNumber", "windowStartedAt", "generation");
CREATE INDEX "PhoneFrequencyHit_tenantId_applicationId_createdAt_idx"
ON "PhoneFrequencyHit"("tenantId", "applicationId", "createdAt");
CREATE INDEX "PhoneFrequencyHit_applicationId_phoneNumber_createdAt_idx"
ON "PhoneFrequencyHit"("applicationId", "phoneNumber", "createdAt");
CREATE INDEX "PhoneFrequencyHit_windowEndsAt_releasedAt_idx"
ON "PhoneFrequencyHit"("windowEndsAt", "releasedAt");
CREATE INDEX "PhoneFrequencyHit_ruleId_idx" ON "PhoneFrequencyHit"("ruleId");
CREATE INDEX "PhoneFrequencyHit_releasedById_idx" ON "PhoneFrequencyHit"("releasedById");
CREATE UNIQUE INDEX "PhoneFrequencyState_activeHitId_key" ON "PhoneFrequencyState"("activeHitId");
CREATE UNIQUE INDEX "PhoneFrequencyState_applicationId_ruleCode_phoneNumber_key"
ON "PhoneFrequencyState"("applicationId", "ruleCode", "phoneNumber");
CREATE INDEX "PhoneFrequencyState_tenantId_applicationId_windowEndsAt_idx"
ON "PhoneFrequencyState"("tenantId", "applicationId", "windowEndsAt");
CREATE INDEX "PhoneFrequencyState_ruleId_idx" ON "PhoneFrequencyState"("ruleId");
ALTER TABLE "PhoneFrequencyHit"
ADD CONSTRAINT "PhoneFrequencyHit_tenantId_fkey"
FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyHit"
ADD CONSTRAINT "PhoneFrequencyHit_applicationId_fkey"
FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyHit"
ADD CONSTRAINT "PhoneFrequencyHit_ruleId_fkey"
FOREIGN KEY ("ruleId") REFERENCES "RiskRule"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyHit"
ADD CONSTRAINT "PhoneFrequencyHit_releasedById_fkey"
FOREIGN KEY ("releasedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyState"
ADD CONSTRAINT "PhoneFrequencyState_tenantId_fkey"
FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyState"
ADD CONSTRAINT "PhoneFrequencyState_applicationId_fkey"
FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyState"
ADD CONSTRAINT "PhoneFrequencyState_ruleId_fkey"
FOREIGN KEY ("ruleId") REFERENCES "RiskRule"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyState"
ADD CONSTRAINT "PhoneFrequencyState_activeHitId_fkey"
FOREIGN KEY ("activeHitId") REFERENCES "PhoneFrequencyHit"("id") ON DELETE SET NULL ON UPDATE CASCADE;
INSERT INTO "RiskRule" (
"id", "tenantId", "applicationId", "code", "name", "description", "metric",
"thresholdValue", "action", "status", "priority", "config", "createdAt", "updatedAt"
)
SELECT
'default-phone-frequency-24h', NULL, NULL, 'PHONE_FREQUENCY_24H',
'单号码24小时发送频次', '同一企业应用下,单个号码在北京时间自然日内最多允许10条业务短信。',
'phoneFrequencyCount', 10, 'block', 'active', 40,
'{"periodSeconds":86400,"timeZone":"Asia/Shanghai","alignment":"fixed"}'::jsonb,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
WHERE NOT EXISTS (
SELECT 1 FROM "RiskRule"
WHERE "applicationId" IS NULL
AND "code" = 'PHONE_FREQUENCY_24H'
AND "status" <> 'deleted'
);
INSERT INTO "RiskRule" (
"id", "tenantId", "applicationId", "code", "name", "description", "metric",
"thresholdValue", "action", "status", "priority", "config", "createdAt", "updatedAt"
)
SELECT
'default-phone-frequency-5m', NULL, NULL, 'PHONE_FREQUENCY_5M',
'单号码5分钟发送频次', '同一企业应用下,单个号码在固定5分钟周期内最多允许5条业务短信。',
'phoneFrequencyCount', 5, 'block', 'active', 50,
'{"periodSeconds":300,"timeZone":"Asia/Shanghai","alignment":"fixed"}'::jsonb,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
WHERE NOT EXISTS (
SELECT 1 FROM "RiskRule"
WHERE "applicationId" IS NULL
AND "code" = 'PHONE_FREQUENCY_5M'
AND "status" <> 'deleted'
);
@@ -0,0 +1,34 @@
CREATE TABLE "PhoneFrequencyWhitelist" (
"id" TEXT NOT NULL,
"phoneNumber" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'active',
"reason" TEXT NOT NULL,
"remark" TEXT,
"createdById" TEXT NOT NULL,
"updatedById" TEXT NOT NULL,
"deletedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "PhoneFrequencyWhitelist_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "PhoneFrequencyWhitelist_phoneNumber_key"
ON "PhoneFrequencyWhitelist"("phoneNumber");
CREATE INDEX "PhoneFrequencyWhitelist_status_updatedAt_idx"
ON "PhoneFrequencyWhitelist"("status", "updatedAt");
CREATE INDEX "PhoneFrequencyWhitelist_createdById_idx"
ON "PhoneFrequencyWhitelist"("createdById");
CREATE INDEX "PhoneFrequencyWhitelist_updatedById_idx"
ON "PhoneFrequencyWhitelist"("updatedById");
ALTER TABLE "PhoneFrequencyWhitelist"
ADD CONSTRAINT "PhoneFrequencyWhitelist_createdById_fkey"
FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyWhitelist"
ADD CONSTRAINT "PhoneFrequencyWhitelist_updatedById_fkey"
FOREIGN KEY ("updatedById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,34 @@
CREATE TABLE "DrainageDetectionRule" (
"id" TEXT NOT NULL,
"code" TEXT NOT NULL,
"name" TEXT NOT NULL,
"category" TEXT NOT NULL,
"pattern" TEXT NOT NULL,
"flags" TEXT NOT NULL DEFAULT 'giu',
"priority" INTEGER NOT NULL DEFAULT 100,
"status" TEXT NOT NULL DEFAULT 'active',
"description" TEXT,
"version" INTEGER NOT NULL DEFAULT 1,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "DrainageDetectionRule_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "DrainageDetectionRule_code_key" ON "DrainageDetectionRule"("code");
CREATE INDEX "DrainageDetectionRule_status_priority_idx" ON "DrainageDetectionRule"("status", "priority");
ALTER TABLE "SmsMessageRecord"
ADD COLUMN "hasDrainageContent" BOOLEAN,
ADD COLUMN "drainageDetection" JSONB,
ADD COLUMN "drainageDetectionVersion" TEXT,
ADD COLUMN "drainageEvaluatedAt" TIMESTAMP(3);
CREATE INDEX "SmsMessageRecord_hasDrainageContent_queuedAt_idx"
ON "SmsMessageRecord"("hasDrainageContent", "queuedAt");
INSERT INTO "DrainageDetectionRule"
("id", "code", "name", "category", "pattern", "flags", "priority", "status", "description", "version", "updatedAt")
VALUES
('drainage-rule-url', 'URL', 'URL及裸域名', 'url', $regex$(?:https?:\/\/)?(?:www\.)?(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,24}|(?:\d{1,3}\.){3}\d{1,3})(?::\d{1,5})?(?:\/[^\s,;!?<>]*)?$regex$, 'giu', 10, 'active', '识别协议链接、裸域名、短链接及IP地址链接;邮箱区间由检测器排除', 1, CURRENT_TIMESTAMP),
('drainage-rule-mobile', 'MOBILE', '手机号码', 'mobile', $regex$(?:^|[^0-9])((?:\+?86)?1[3-9][0-9]{9})(?:$|[^0-9])$regex$, 'giu', 20, 'active', '规范化后识别+86、空格、短横线及中文标点拆分手机号', 1, CURRENT_TIMESTAMP),
('drainage-rule-landline', 'LANDLINE', '固定电话号码', 'landline', $regex$(?:^|[^0-9])((?:\+?86)?(?:\(0[0-9]{2,3}\)|0[0-9]{2,3})-?[0-9]{7,8}(?:(?:||ext)[0-9]{1,6})?)(?:$|[^0-9])$regex$, 'giu', 30, 'active', '识别区号括号、分隔符和分机号', 1, CURRENT_TIMESTAMP);
@@ -0,0 +1,23 @@
-- PostgreSQL standard-conforming strings preserve backslashes literally. The initial
-- seed used JavaScript-style escaping, so already-migrated databases need their three
-- built-in patterns normalized to the single backslashes expected by RegExp.
UPDATE "DrainageDetectionRule"
SET
"pattern" = $regex$(?:https?:\/\/)?(?:www\.)?(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,24}|(?:\d{1,3}\.){3}\d{1,3})(?::\d{1,5})?(?:\/[^\s,;!?<>]*)?$regex$,
"version" = "version" + 1,
"updatedAt" = CURRENT_TIMESTAMP
WHERE "code" = 'URL';
UPDATE "DrainageDetectionRule"
SET
"pattern" = $regex$(?:^|[^0-9])((?:\+?86)?1[3-9][0-9]{9})(?:$|[^0-9])$regex$,
"version" = "version" + 1,
"updatedAt" = CURRENT_TIMESTAMP
WHERE "code" = 'MOBILE';
UPDATE "DrainageDetectionRule"
SET
"pattern" = $regex$(?:^|[^0-9])((?:\+?86)?(?:\(0[0-9]{2,3}\)|0[0-9]{2,3})-?[0-9]{7,8}(?:(?:||ext)[0-9]{1,6})?)(?:$|[^0-9])$regex$,
"version" = "version" + 1,
"updatedAt" = CURRENT_TIMESTAMP
WHERE "code" = 'LANDLINE';
@@ -0,0 +1,12 @@
ALTER TABLE "SmsMessageRecord"
ADD COLUMN "cmppRegisteredDelivery" BOOLEAN,
ADD COLUMN "timeoutReceiptQueuedAt" TIMESTAMP(3);
ALTER TABLE "CmppInboundLongMessageSegment"
ADD COLUMN "registeredDelivery" BOOLEAN NOT NULL DEFAULT true;
-- Historical CMPP submissions were accepted before Registered_Delivery was
-- persisted. Preserve their existing receipt-enabled behavior.
UPDATE "SmsMessageRecord"
SET "cmppRegisteredDelivery" = true
WHERE "cmppSubmitSequenceId" IS NOT NULL;
@@ -0,0 +1,43 @@
CREATE TABLE "SmsReceiptAnomaly" (
"id" TEXT NOT NULL,
"anomalyKey" TEXT NOT NULL,
"tenantId" TEXT,
"applicationId" TEXT,
"channelId" TEXT,
"messageRecordId" TEXT,
"submitRecordId" TEXT,
"receiptRecordId" TEXT,
"anomalyType" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'pending',
"previousStatus" TEXT,
"incomingStatus" TEXT,
"rawStatus" TEXT,
"errorCode" TEXT,
"detail" JSONB,
"occurrenceCount" INTEGER NOT NULL DEFAULT 1,
"firstOccurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"lastOccurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"resolvedAt" TIMESTAMP(3),
"resolutionNote" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SmsReceiptAnomaly_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SmsReceiptAnomaly_anomalyKey_key" ON "SmsReceiptAnomaly"("anomalyKey");
CREATE INDEX "SmsReceiptAnomaly_status_lastOccurredAt_idx" ON "SmsReceiptAnomaly"("status", "lastOccurredAt");
CREATE INDEX "SmsReceiptAnomaly_lastOccurredAt_idx" ON "SmsReceiptAnomaly"("lastOccurredAt");
CREATE INDEX "SmsReceiptAnomaly_anomalyType_lastOccurredAt_idx" ON "SmsReceiptAnomaly"("anomalyType", "lastOccurredAt");
CREATE INDEX "SmsReceiptAnomaly_tenantId_status_lastOccurredAt_idx" ON "SmsReceiptAnomaly"("tenantId", "status", "lastOccurredAt");
CREATE INDEX "SmsReceiptAnomaly_applicationId_status_lastOccurredAt_idx" ON "SmsReceiptAnomaly"("applicationId", "status", "lastOccurredAt");
CREATE INDEX "SmsReceiptAnomaly_channelId_status_lastOccurredAt_idx" ON "SmsReceiptAnomaly"("channelId", "status", "lastOccurredAt");
CREATE INDEX "SmsReceiptAnomaly_messageRecordId_idx" ON "SmsReceiptAnomaly"("messageRecordId");
CREATE INDEX "SmsReceiptAnomaly_submitRecordId_idx" ON "SmsReceiptAnomaly"("submitRecordId");
ALTER TABLE "SmsReceiptAnomaly" ADD CONSTRAINT "SmsReceiptAnomaly_tenantId_fkey" FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "SmsReceiptAnomaly" ADD CONSTRAINT "SmsReceiptAnomaly_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "SmsReceiptAnomaly" ADD CONSTRAINT "SmsReceiptAnomaly_channelId_fkey" FOREIGN KEY ("channelId") REFERENCES "SmsChannel"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "SmsReceiptAnomaly" ADD CONSTRAINT "SmsReceiptAnomaly_messageRecordId_fkey" FOREIGN KEY ("messageRecordId") REFERENCES "SmsMessageRecord"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "SmsReceiptAnomaly" ADD CONSTRAINT "SmsReceiptAnomaly_submitRecordId_fkey" FOREIGN KEY ("submitRecordId") REFERENCES "SmsSubmitRecord"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "SmsReceiptAnomaly" ADD CONSTRAINT "SmsReceiptAnomaly_receiptRecordId_fkey" FOREIGN KEY ("receiptRecordId") REFERENCES "SmsReceiptRecord"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
ALTER TABLE "ProtocolInteractionLog"
ADD COLUMN "phoneNumber" TEXT;
@@ -0,0 +1,203 @@
ALTER TABLE "SmsChannel"
ADD COLUMN "carriers" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];
UPDATE "SmsChannel"
SET "carriers" = CASE
WHEN "carrier" = 'mobile' THEN ARRAY['mobile']::TEXT[]
WHEN "carrier" = 'unicom' THEN ARRAY['unicom']::TEXT[]
WHEN "carrier" = 'telecom' THEN ARRAY['telecom']::TEXT[]
WHEN "carrier" = 'all' THEN ARRAY['mobile', 'unicom', 'telecom']::TEXT[]
-- 旧页面和旧发送链对空/未知carrier一直按移动处理,迁移保持原业务语义且保证至少一项。
ELSE ARRAY['mobile']::TEXT[]
END;
ALTER TABLE "SmsChannel"
ADD CONSTRAINT "SmsChannel_carriers_supported_check"
CHECK (
cardinality("carriers") BETWEEN 1 AND 3
AND "carriers" <@ ARRAY['mobile', 'unicom', 'telecom']::TEXT[]
);
ALTER TABLE "ChannelSignatureReportTask"
ADD COLUMN "carrier" TEXT,
ADD COLUMN "approvedAt" TIMESTAMP(3),
ADD COLUMN "approvalScope" TEXT NOT NULL DEFAULT 'legacy_channel';
-- The current approved timestamp is reconstructed from the latest transition
-- into approved. updatedAt is deliberately not used because unrelated edits
-- can change it and would incorrectly restart the grace period.
UPDATE "ChannelSignatureReportTask" task
SET "approvedAt" = approved_record."approvedAt"
FROM (
SELECT "taskId", MAX("createdAt") AS "approvedAt"
FROM "ChannelSignatureReportRecord"
WHERE "statusAfter" = 'approved'
GROUP BY "taskId"
) approved_record
WHERE task.id = approved_record."taskId"
AND task.status = 'approved';
CREATE INDEX "ChannelSignatureReportTask_signatureId_channelId_carrier_idx"
ON "ChannelSignatureReportTask"("signatureId", "channelId", "carrier");
-- 旧索引把运营商排除在唯一维度外,会阻止同一签名/通道建立多运营商事实。
-- 拆成三类条件索引,在升级维度的同时继续保护历史任务和引流任务不重复。
DROP INDEX IF EXISTS "ChannelSignatureReportTask_target_key";
CREATE UNIQUE INDEX "ChannelSignatureReportTask_signature_channel_carrier_key"
ON "ChannelSignatureReportTask"("signatureId", "channelId", "carrier")
WHERE "reportType" = 'signature' AND "carrier" IS NOT NULL AND "drainageItemId" IS NULL;
CREATE UNIQUE INDEX "ChannelSignatureReportTask_legacy_signature_channel_key"
ON "ChannelSignatureReportTask"("signatureId", "channelId")
WHERE "reportType" = 'signature' AND "carrier" IS NULL AND "drainageItemId" IS NULL;
CREATE UNIQUE INDEX "ChannelSignatureReportTask_drainage_target_key"
ON "ChannelSignatureReportTask"("signatureId", "drainageItemId", "channelId")
WHERE "reportType" = 'drainage' AND "drainageItemId" IS NOT NULL;
CREATE TABLE "SignatureRetirementRule" (
"id" TEXT NOT NULL,
"ruleType" TEXT NOT NULL,
"targetId" TEXT,
"targetKey" TEXT NOT NULL DEFAULT '',
"enabled" BOOLEAN NOT NULL DEFAULT true,
"mobileWindowDays" INTEGER NOT NULL DEFAULT 30,
"mobileThreshold" INTEGER NOT NULL DEFAULT 1,
"unicomWindowDays" INTEGER NOT NULL DEFAULT 30,
"unicomThreshold" INTEGER NOT NULL DEFAULT 1,
"telecomWindowDays" INTEGER NOT NULL DEFAULT 30,
"telecomThreshold" INTEGER NOT NULL DEFAULT 1,
"messageTemplate" TEXT,
"version" INTEGER NOT NULL DEFAULT 1,
"createdById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SignatureRetirementRule_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SignatureRetirementRule_ruleType_targetKey_key" ON "SignatureRetirementRule"("ruleType", "targetKey");
CREATE INDEX "SignatureRetirementRule_ruleType_enabled_idx" ON "SignatureRetirementRule"("ruleType", "enabled");
CREATE TABLE "SignatureRetirementWebhook" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"platform" TEXT NOT NULL,
"urlEncrypted" TEXT NOT NULL,
"urlMasked" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'active',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SignatureRetirementWebhook_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "SignatureRetirementWebhook_status_createdAt_idx" ON "SignatureRetirementWebhook"("status", "createdAt");
CREATE TABLE "SignatureRetirementCycle" (
"id" TEXT NOT NULL,
"dimensionType" TEXT NOT NULL,
"signatureId" TEXT NOT NULL,
"channelId" TEXT,
"channelKey" TEXT NOT NULL DEFAULT '',
"carrier" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'open',
"startedOn" DATE NOT NULL,
"lastDetectedOn" DATE NOT NULL,
"resolvedOn" DATE,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SignatureRetirementCycle_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "SignatureRetirementCycle_dimension_status_idx" ON "SignatureRetirementCycle"("dimensionType", "signatureId", "channelKey", "carrier", "status");
CREATE INDEX "SignatureRetirementCycle_status_lastDetectedOn_idx" ON "SignatureRetirementCycle"("status", "lastDetectedOn");
-- 同一监控维度只能存在一个开放周期,数据库约束用于兜住并发检测实例。
CREATE UNIQUE INDEX "SignatureRetirementCycle_open_dimension_key"
ON "SignatureRetirementCycle"("dimensionType", "signatureId", "channelKey", "carrier")
WHERE "status" = 'open';
CREATE TABLE "SignatureRetirementDetection" (
"id" TEXT NOT NULL,
"detectionDate" DATE NOT NULL,
"dimensionType" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT,
"signatureId" TEXT NOT NULL,
"channelId" TEXT,
"channelKey" TEXT NOT NULL DEFAULT '',
"carrier" TEXT NOT NULL,
"windowDays" INTEGER NOT NULL,
"threshold" INTEGER NOT NULL,
"submittedAttempts" INTEGER NOT NULL DEFAULT 0,
"acceptedBusinessCount" INTEGER NOT NULL DEFAULT 0,
"deliveredBusinessCount" INTEGER NOT NULL DEFAULT 0,
"approvedAt" TIMESTAMP(3) NOT NULL,
"ruleId" TEXT,
"ruleVersion" INTEGER NOT NULL DEFAULT 1,
"status" TEXT NOT NULL,
"cycleId" TEXT,
"suppressed" BOOLEAN NOT NULL DEFAULT false,
"notificationTitle" TEXT,
"notificationContent" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SignatureRetirementDetection_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SignatureRetirementDetection_dimension_key" ON "SignatureRetirementDetection"("detectionDate", "dimensionType", "signatureId", "channelKey", "carrier");
CREATE INDEX "SignatureRetirementDetection_date_type_status_idx" ON "SignatureRetirementDetection"("detectionDate", "dimensionType", "status");
CREATE INDEX "SignatureRetirementDetection_signature_carrier_date_idx" ON "SignatureRetirementDetection"("signatureId", "carrier", "detectionDate");
CREATE INDEX "SignatureRetirementDetection_channel_carrier_date_idx" ON "SignatureRetirementDetection"("channelId", "carrier", "detectionDate");
CREATE TABLE "SignatureRetirementMessage" (
"id" TEXT NOT NULL,
"detectionId" TEXT NOT NULL,
"cycleId" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"title" TEXT NOT NULL,
"content" TEXT NOT NULL,
"isRead" BOOLEAN NOT NULL DEFAULT false,
"suppressed" BOOLEAN NOT NULL DEFAULT false,
"readAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SignatureRetirementMessage_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SignatureRetirementMessage_detectionId_key" ON "SignatureRetirementMessage"("detectionId");
CREATE INDEX "SignatureRetirementMessage_created_read_suppressed_idx" ON "SignatureRetirementMessage"("createdAt", "isRead", "suppressed");
CREATE INDEX "SignatureRetirementMessage_tenant_createdAt_idx" ON "SignatureRetirementMessage"("tenantId", "createdAt");
CREATE TABLE "SignatureRetirementSuppression" (
"id" TEXT NOT NULL,
"dimensionType" TEXT NOT NULL,
"signatureId" TEXT NOT NULL,
"channelId" TEXT,
"channelKey" TEXT NOT NULL DEFAULT '',
"carrier" TEXT NOT NULL,
"mode" TEXT NOT NULL,
"muteUntil" DATE,
"active" BOOLEAN NOT NULL DEFAULT true,
"reason" TEXT,
"operatorId" TEXT,
"cancelledAt" TIMESTAMP(3),
"cancelledById" TEXT,
"cancelReason" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SignatureRetirementSuppression_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SignatureRetirementSuppression_dimension_key" ON "SignatureRetirementSuppression"("dimensionType", "signatureId", "channelKey", "carrier");
CREATE INDEX "SignatureRetirementSuppression_active_muteUntil_idx" ON "SignatureRetirementSuppression"("active", "muteUntil");
CREATE TABLE "SignatureRetirementWebhookDelivery" (
"id" TEXT NOT NULL,
"detectionDate" DATE NOT NULL,
"webhookId" TEXT NOT NULL,
"groupKey" TEXT NOT NULL,
"payload" JSONB NOT NULL,
"status" TEXT NOT NULL DEFAULT 'pending',
"attemptCount" INTEGER NOT NULL DEFAULT 0,
"nextRetryAt" TIMESTAMP(3),
"lastHttpStatus" INTEGER,
"lastError" TEXT,
"deliveredAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SignatureRetirementWebhookDelivery_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SignatureRetirementWebhookDelivery_key" ON "SignatureRetirementWebhookDelivery"("webhookId", "detectionDate", "groupKey");
CREATE INDEX "SignatureRetirementWebhookDelivery_status_retry_idx" ON "SignatureRetirementWebhookDelivery"("status", "nextRetryAt");
@@ -0,0 +1,153 @@
-- 最终业务口径不再保留历史人工确认:旧通道级状态按通道能力一次性形成运营商级事实。
-- 已有运营商任务代表更新的事实,必须保留且不得被旧任务覆盖。
WITH legacy_targets AS (
SELECT
legacy.id AS "legacyId",
legacy."tenantId",
legacy."signatureId",
legacy."channelId",
legacy.status,
legacy.reason,
legacy."createdById",
supported.carrier
FROM "ChannelSignatureReportTask" legacy
JOIN "SmsChannel" channel ON channel.id = legacy."channelId"
CROSS JOIN LATERAL unnest(
CASE
WHEN cardinality(channel.carriers) > 0 THEN channel.carriers
WHEN channel.carrier = 'all' THEN ARRAY['mobile', 'unicom', 'telecom']::TEXT[]
WHEN channel.carrier IN ('mobile', 'unicom', 'telecom') THEN ARRAY[channel.carrier]::TEXT[]
ELSE ARRAY['mobile']::TEXT[]
END
) AS supported(carrier)
WHERE legacy."reportType" = 'signature'
AND legacy."drainageItemId" IS NULL
AND legacy.carrier IS NULL
AND legacy."approvalScope" = 'legacy_channel'
), inserted_tasks AS (
INSERT INTO "ChannelSignatureReportTask" (
id,
"tenantId",
"signatureId",
"channelId",
carrier,
"approvedAt",
"approvalScope",
"reportType",
"drainageItemId",
status,
reason,
"createdById",
"createdAt",
"updatedAt"
)
SELECT
'legacy-auto-' || md5(target."legacyId" || ':' || target.carrier),
target."tenantId",
target."signatureId",
target."channelId",
target.carrier,
CASE WHEN target.status = 'approved' THEN CURRENT_TIMESTAMP ELSE NULL END,
'carrier_specific',
'signature',
NULL,
target.status,
target.reason,
target."createdById",
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
FROM legacy_targets target
ON CONFLICT DO NOTHING
RETURNING id, "channelId", status
)
INSERT INTO "ChannelSignatureReportRecord" (
id,
"taskId",
"channelId",
action,
"statusBefore",
"statusAfter",
reason,
"operatorId",
"sourceEntry",
"createdAt"
)
SELECT
'legacy-auto-record-' || md5(task.id),
task.id,
task."channelId",
'legacy_carrier_auto_split',
NULL,
task.status,
'历史通道级任务按通道运营商能力自动转换',
NULL,
'migration',
CURRENT_TIMESTAMP
FROM inserted_tasks task
ON CONFLICT (id) DO NOTHING;
WITH legacy_targets AS (
SELECT
legacy.id AS "legacyId",
legacy."signatureId",
legacy."channelId",
supported.carrier
FROM "ChannelSignatureReportTask" legacy
JOIN "SmsChannel" channel ON channel.id = legacy."channelId"
CROSS JOIN LATERAL unnest(
CASE
WHEN cardinality(channel.carriers) > 0 THEN channel.carriers
WHEN channel.carrier = 'all' THEN ARRAY['mobile', 'unicom', 'telecom']::TEXT[]
WHEN channel.carrier IN ('mobile', 'unicom', 'telecom') THEN ARRAY[channel.carrier]::TEXT[]
ELSE ARRAY['mobile']::TEXT[]
END
) AS supported(carrier)
WHERE legacy."reportType" = 'signature'
AND legacy."drainageItemId" IS NULL
AND legacy.carrier IS NULL
AND legacy."approvalScope" = 'legacy_channel'
), completed_legacy AS (
SELECT target."legacyId"
FROM legacy_targets target
LEFT JOIN "ChannelSignatureReportTask" exact
ON exact."signatureId" = target."signatureId"
AND exact."channelId" = target."channelId"
AND exact."reportType" = 'signature'
AND exact."drainageItemId" IS NULL
AND exact.carrier = target.carrier
GROUP BY target."legacyId"
HAVING COUNT(DISTINCT target.carrier) = COUNT(DISTINCT exact.carrier)
), updated_legacy AS (
UPDATE "ChannelSignatureReportTask" legacy
SET "approvalScope" = 'legacy_split',
"updatedAt" = CURRENT_TIMESTAMP
FROM completed_legacy completed
WHERE legacy.id = completed."legacyId"
AND legacy."approvalScope" = 'legacy_channel'
RETURNING legacy.id, legacy."channelId", legacy.status
)
INSERT INTO "ChannelSignatureReportRecord" (
id,
"taskId",
"channelId",
action,
"statusBefore",
"statusAfter",
reason,
"operatorId",
"sourceEntry",
"createdAt"
)
SELECT
'legacy-split-record-' || md5(legacy.id),
legacy.id,
legacy."channelId",
'legacy_scope_auto_split',
legacy.status,
legacy.status,
'全部适用运营商已自动形成独立报备任务',
NULL,
'migration',
CURRENT_TIMESTAMP
FROM updated_legacy legacy
ON CONFLICT (id) DO NOTHING;
@@ -0,0 +1,57 @@
CREATE TABLE "DownstreamRequeueTask" (
"id" TEXT NOT NULL,
"taskNo" TEXT NOT NULL,
"tenantId" TEXT,
"applicationId" TEXT,
"status" TEXT NOT NULL DEFAULT 'queued',
"filterSnapshot" JSONB NOT NULL,
"snapshotAt" TIMESTAMP(3) NOT NULL,
"reason" TEXT NOT NULL,
"ratePerSecond" INTEGER NOT NULL DEFAULT 10,
"consecutiveFailureLimit" INTEGER NOT NULL DEFAULT 10,
"totalCount" INTEGER NOT NULL DEFAULT 0,
"successCount" INTEGER NOT NULL DEFAULT 0,
"failedCount" INTEGER NOT NULL DEFAULT 0,
"skippedCount" INTEGER NOT NULL DEFAULT 0,
"waitingCount" INTEGER NOT NULL DEFAULT 0,
"consecutiveFailures" INTEGER NOT NULL DEFAULT 0,
"lastError" TEXT,
"createdById" TEXT,
"startedAt" TIMESTAMP(3),
"pausedAt" TIMESTAMP(3),
"finishedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "DownstreamRequeueTask_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "DownstreamRequeueTaskItem" (
"id" TEXT NOT NULL,
"taskId" TEXT NOT NULL,
"deliveryId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'queued',
"previousStatus" TEXT NOT NULL,
"skipReason" TEXT,
"errorMessage" TEXT,
"claimedAt" TIMESTAMP(3),
"completedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "DownstreamRequeueTaskItem_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "DownstreamRequeueTask_taskNo_key" ON "DownstreamRequeueTask"("taskNo");
CREATE INDEX "DownstreamRequeueTask_status_createdAt_idx" ON "DownstreamRequeueTask"("status", "createdAt");
CREATE INDEX "DownstreamRequeueTask_applicationId_status_createdAt_idx" ON "DownstreamRequeueTask"("applicationId", "status", "createdAt");
CREATE INDEX "DownstreamRequeueTask_tenantId_createdAt_idx" ON "DownstreamRequeueTask"("tenantId", "createdAt");
CREATE UNIQUE INDEX "DownstreamRequeueTaskItem_taskId_deliveryId_key" ON "DownstreamRequeueTaskItem"("taskId", "deliveryId");
CREATE INDEX "DownstreamRequeueTaskItem_taskId_status_createdAt_idx" ON "DownstreamRequeueTaskItem"("taskId", "status", "createdAt");
CREATE INDEX "DownstreamRequeueTaskItem_applicationId_status_createdAt_idx" ON "DownstreamRequeueTaskItem"("applicationId", "status", "createdAt");
CREATE INDEX "DownstreamRequeueTaskItem_deliveryId_status_idx" ON "DownstreamRequeueTaskItem"("deliveryId", "status");
ALTER TABLE "DownstreamRequeueTask" ADD CONSTRAINT "DownstreamRequeueTask_tenantId_fkey" FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "DownstreamRequeueTask" ADD CONSTRAINT "DownstreamRequeueTask_applicationId_fkey" FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "DownstreamRequeueTask" ADD CONSTRAINT "DownstreamRequeueTask_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "DownstreamRequeueTaskItem" ADD CONSTRAINT "DownstreamRequeueTaskItem_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "DownstreamRequeueTask"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "DownstreamRequeueTaskItem" ADD CONSTRAINT "DownstreamRequeueTaskItem_deliveryId_fkey" FOREIGN KEY ("deliveryId") REFERENCES "CmppDownstreamDelivery"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,19 @@
ALTER TABLE "DownstreamRequeueTask"
ADD COLUMN "applicationFailures" JSONB NOT NULL DEFAULT '{}',
ADD COLUMN "scanLeaseOwner" TEXT,
ADD COLUMN "scanLeaseUntil" TIMESTAMP(3);
CREATE TABLE "DownstreamRequeueRateWindow" (
"id" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"windowStartedAt" TIMESTAMP(3) NOT NULL,
"consumed" INTEGER NOT NULL DEFAULT 0,
"updatedAt" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "DownstreamRequeueRateWindow_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "DownstreamRequeueRateWindow_applicationId_windowStartedAt_key"
ON "DownstreamRequeueRateWindow"("applicationId", "windowStartedAt");
CREATE INDEX "DownstreamRequeueRateWindow_windowStartedAt_idx"
ON "DownstreamRequeueRateWindow"("windowStartedAt");
@@ -0,0 +1,80 @@
CREATE TABLE "SecurityDetectionRule" (
"id" TEXT NOT NULL,
"code" TEXT NOT NULL,
"name" TEXT NOT NULL,
"sourceType" TEXT NOT NULL,
"enabled" BOOLEAN NOT NULL DEFAULT true,
"threshold" INTEGER NOT NULL,
"windowSeconds" INTEGER NOT NULL,
"cooldownSeconds" INTEGER NOT NULL,
"severity" TEXT NOT NULL,
"defaultBlockSeconds" INTEGER NOT NULL,
"maximumBlockSeconds" INTEGER NOT NULL,
"configVersion" INTEGER NOT NULL DEFAULT 1,
"effectiveVersion" INTEGER NOT NULL DEFAULT 0,
"applyStatus" TEXT NOT NULL DEFAULT 'pending',
"lastApplyError" TEXT,
"pendingConfig" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SecurityDetectionRule_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "SecurityDetectionEvent" (
"id" TEXT NOT NULL, "eventKey" TEXT NOT NULL, "ruleId" TEXT NOT NULL,
"sourceIp" TEXT NOT NULL, "sourcePort" INTEGER, "accountHash" TEXT,
"path" TEXT, "protocol" TEXT, "resultCode" TEXT, "evidence" JSONB,
"occurredAt" TIMESTAMP(3) NOT NULL, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SecurityDetectionEvent_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "SecurityAlert" (
"id" TEXT NOT NULL, "fingerprint" TEXT NOT NULL, "ruleId" TEXT NOT NULL,
"sourceIp" TEXT NOT NULL, "severity" TEXT NOT NULL, "status" TEXT NOT NULL DEFAULT 'open',
"eventCount" INTEGER NOT NULL DEFAULT 0, "windowStartedAt" TIMESTAMP(3) NOT NULL,
"firstOccurredAt" TIMESTAMP(3) NOT NULL, "lastOccurredAt" TIMESTAMP(3) NOT NULL,
"acknowledgedAt" TIMESTAMP(3), "acknowledgedById" TEXT, "ignoredAt" TIMESTAMP(3),
"ignoredById" TEXT, "ignoreReason" TEXT, "blockId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SecurityAlert_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "SecurityBlock" (
"id" TEXT NOT NULL, "operationKey" TEXT NOT NULL, "alertId" TEXT, "sourceIp" TEXT NOT NULL,
"executor" TEXT NOT NULL, "status" TEXT NOT NULL DEFAULT 'requested', "durationSeconds" INTEGER NOT NULL,
"reason" TEXT NOT NULL, "requestedById" TEXT NOT NULL, "requestedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"appliedAt" TIMESTAMP(3), "expiresAt" TIMESTAMP(3), "releasedAt" TIMESTAMP(3), "releasedById" TEXT,
"executorReference" TEXT, "lastError" TEXT, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL, CONSTRAINT "SecurityBlock_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "SecurityProtectedNetwork" (
"id" TEXT NOT NULL, "network" TEXT NOT NULL, "name" TEXT NOT NULL, "reason" TEXT NOT NULL,
"enabled" BOOLEAN NOT NULL DEFAULT true, "createdById" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SecurityProtectedNetwork_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SecurityDetectionRule_code_key" ON "SecurityDetectionRule"("code");
CREATE INDEX "SecurityDetectionRule_enabled_sourceType_idx" ON "SecurityDetectionRule"("enabled", "sourceType");
CREATE UNIQUE INDEX "SecurityDetectionEvent_eventKey_key" ON "SecurityDetectionEvent"("eventKey");
CREATE INDEX "SecurityDetectionEvent_ruleId_occurredAt_idx" ON "SecurityDetectionEvent"("ruleId", "occurredAt");
CREATE INDEX "SecurityDetectionEvent_sourceIp_occurredAt_idx" ON "SecurityDetectionEvent"("sourceIp", "occurredAt");
CREATE UNIQUE INDEX "SecurityAlert_fingerprint_key" ON "SecurityAlert"("fingerprint");
CREATE INDEX "SecurityAlert_status_severity_lastOccurredAt_idx" ON "SecurityAlert"("status", "severity", "lastOccurredAt");
CREATE INDEX "SecurityAlert_sourceIp_status_lastOccurredAt_idx" ON "SecurityAlert"("sourceIp", "status", "lastOccurredAt");
CREATE INDEX "SecurityAlert_ruleId_status_lastOccurredAt_idx" ON "SecurityAlert"("ruleId", "status", "lastOccurredAt");
CREATE UNIQUE INDEX "SecurityBlock_operationKey_key" ON "SecurityBlock"("operationKey");
CREATE INDEX "SecurityBlock_status_expiresAt_idx" ON "SecurityBlock"("status", "expiresAt");
CREATE INDEX "SecurityBlock_sourceIp_status_requestedAt_idx" ON "SecurityBlock"("sourceIp", "status", "requestedAt");
CREATE INDEX "SecurityBlock_alertId_idx" ON "SecurityBlock"("alertId");
CREATE UNIQUE INDEX "SecurityProtectedNetwork_network_key" ON "SecurityProtectedNetwork"("network");
CREATE INDEX "SecurityProtectedNetwork_enabled_createdAt_idx" ON "SecurityProtectedNetwork"("enabled", "createdAt");
ALTER TABLE "SecurityDetectionEvent" ADD CONSTRAINT "SecurityDetectionEvent_ruleId_fkey" FOREIGN KEY ("ruleId") REFERENCES "SecurityDetectionRule"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "SecurityAlert" ADD CONSTRAINT "SecurityAlert_ruleId_fkey" FOREIGN KEY ("ruleId") REFERENCES "SecurityDetectionRule"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
INSERT INTO "SecurityDetectionRule" ("id", "code", "name", "sourceType", "threshold", "windowSeconds", "cooldownSeconds", "severity", "defaultBlockSeconds", "maximumBlockSeconds", "configVersion", "effectiveVersion", "applyStatus", "updatedAt") VALUES
('sec_admin_login', 'admin_login_failure', '运营端登录失败', 'application', 8, 600, 900, 'medium', 3600, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP),
('sec_client_login', 'client_login_failure', '客户端登录失败', 'application', 8, 600, 900, 'medium', 3600, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP),
('sec_ssh_auth', 'ssh_auth_failure', 'SSH认证失败', 'fail2ban', 6, 600, 1800, 'high', 86400, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP),
('sec_cmpp_auth', 'cmpp_auth_failure', 'CMPP认证失败', 'gateway', 5, 300, 900, 'high', 3600, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP),
('sec_cmpp_abuse', 'cmpp_protocol_abuse', 'CMPP协议滥用', 'gateway', 20, 60, 900, 'critical', 3600, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP),
('sec_http_key', 'http_invalid_api_key', 'HTTP错误密钥', 'application', 10, 300, 900, 'high', 3600, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP),
('sec_http_sign', 'http_signature_failure', 'HTTP签名错误', 'application', 10, 300, 900, 'high', 3600, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP),
('sec_http_replay', 'http_replay_attempt', 'HTTP重放尝试', 'application', 3, 600, 1800, 'critical', 86400, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP),
('sec_http_scan', 'http_malicious_scan', 'HTTP恶意扫描', 'fail2ban', 20, 60, 900, 'high', 3600, 604800, 1, 1, 'effective', CURRENT_TIMESTAMP);
@@ -0,0 +1,23 @@
CREATE TABLE "InfrastructureAlertSetting" (
"id" TEXT NOT NULL DEFAULT 'global',
"configVersion" INTEGER NOT NULL DEFAULT 1,
"effectiveVersion" INTEGER NOT NULL DEFAULT 1,
"thresholds" JSONB NOT NULL,
"effectiveThresholds" JSONB NOT NULL,
"applyStatus" TEXT NOT NULL DEFAULT 'effective',
"lastError" TEXT,
"updatedById" TEXT,
"appliedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "InfrastructureAlertSetting_pkey" PRIMARY KEY ("id")
);
INSERT INTO "InfrastructureAlertSetting" (
"id", "thresholds", "effectiveThresholds", "appliedAt"
) VALUES (
'global',
'{"hostCpu":{"warning":80,"critical":90},"hostMemory":{"warning":85,"critical":95},"hostDisk":{"warning":80,"critical":90},"apiError":{"warning":1,"critical":5},"apiLatency":{"warning":1,"critical":3},"apiEventLoop":{"warning":0.2,"critical":1},"gatewayQueue":{"warning":30,"critical":120},"postgresConnections":{"warning":70,"critical":85},"redisMemory":{"warning":70,"critical":85},"minioCapacity":{"warning":80,"critical":90}}'::jsonb,
'{"hostCpu":{"warning":80,"critical":90},"hostMemory":{"warning":85,"critical":95},"hostDisk":{"warning":80,"critical":90},"apiError":{"warning":1,"critical":5},"apiLatency":{"warning":1,"critical":3},"apiEventLoop":{"warning":0.2,"critical":1},"gatewayQueue":{"warning":30,"critical":120},"postgresConnections":{"warning":70,"critical":85},"redisMemory":{"warning":70,"critical":85},"minioCapacity":{"warning":80,"critical":90}}'::jsonb,
CURRENT_TIMESTAMP
);
@@ -0,0 +1,17 @@
CREATE TABLE "InfrastructureAlertRead" (
"id" TEXT NOT NULL,
"fingerprint" TEXT NOT NULL,
"activeAt" TIMESTAMP(3) NOT NULL,
"userId" TEXT NOT NULL,
"readAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "InfrastructureAlertRead_pkey" PRIMARY KEY ("id"),
CONSTRAINT "InfrastructureAlertRead_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE UNIQUE INDEX "InfrastructureAlertRead_fingerprint_userId_key"
ON "InfrastructureAlertRead"("fingerprint", "userId");
CREATE INDEX "InfrastructureAlertRead_userId_readAt_idx"
ON "InfrastructureAlertRead"("userId", "readAt");
@@ -0,0 +1,6 @@
ALTER TABLE "SmsSubmitRecord"
ADD COLUMN "resultEventId" TEXT,
ADD COLUMN "resultProcessedAt" TIMESTAMP(3);
CREATE UNIQUE INDEX "SmsSubmitRecord_resultEventId_key"
ON "SmsSubmitRecord"("resultEventId");
@@ -0,0 +1,91 @@
CREATE TABLE "CmppInboundSubmissionInbox" (
"id" TEXT NOT NULL,
"requestKey" TEXT NOT NULL,
"payloadHash" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"queuePriority" TEXT NOT NULL DEFAULT 'normal',
"payload" JSONB NOT NULL,
"response" JSONB NOT NULL,
"status" TEXT NOT NULL DEFAULT 'pending',
"attempts" INTEGER NOT NULL DEFAULT 0,
"nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"lockedAt" TIMESTAMP(3),
"lockedBy" TEXT,
"lastError" TEXT,
"result" JSONB,
"completedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "CmppInboundSubmissionInbox_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "CmppInboundSubmissionInbox_requestKey_key"
ON "CmppInboundSubmissionInbox"("requestKey");
CREATE INDEX "CmppInboundSubmissionInbox_status_nextAttemptAt_createdAt_idx"
ON "CmppInboundSubmissionInbox"("status", "nextAttemptAt", "createdAt");
CREATE INDEX "CmppInboundSubmissionInbox_status_lockedAt_idx"
ON "CmppInboundSubmissionInbox"("status", "lockedAt");
CREATE INDEX "CmppInboundSubmissionInbox_applicationId_createdAt_idx"
ON "CmppInboundSubmissionInbox"("applicationId", "createdAt");
CREATE INDEX "CmppInboundSubmissionInbox_queuePriority_status_createdAt_idx"
ON "CmppInboundSubmissionInbox"("queuePriority", "status", "createdAt");
ALTER TABLE "CmppInboundSubmissionInbox"
ADD CONSTRAINT "CmppInboundSubmissionInbox_tenantId_fkey"
FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "CmppInboundSubmissionInbox"
ADD CONSTRAINT "CmppInboundSubmissionInbox_applicationId_fkey"
FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "SmsApplicationDailyReservation" (
"id" TEXT NOT NULL,
"reservationKey" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"usageDate" DATE NOT NULL,
"requestedCount" INTEGER NOT NULL,
"dailyLimit" INTEGER NOT NULL,
"usedCount" INTEGER,
"reserved" BOOLEAN NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SmsApplicationDailyReservation_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SmsApplicationDailyReservation_reservationKey_key"
ON "SmsApplicationDailyReservation"("reservationKey");
CREATE INDEX "SmsApplicationDailyReservation_applicationId_usageDate_idx"
ON "SmsApplicationDailyReservation"("applicationId", "usageDate");
CREATE INDEX "SmsApplicationDailyReservation_tenantId_createdAt_idx"
ON "SmsApplicationDailyReservation"("tenantId", "createdAt");
ALTER TABLE "SmsApplicationDailyReservation" ADD CONSTRAINT "SmsApplicationDailyReservation_tenantId_fkey"
FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "SmsApplicationDailyReservation" ADD CONSTRAINT "SmsApplicationDailyReservation_applicationId_fkey"
FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
CREATE TABLE "PhoneFrequencyReservation" (
"id" TEXT NOT NULL,
"reservationKey" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"result" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "PhoneFrequencyReservation_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "PhoneFrequencyReservation_reservationKey_key"
ON "PhoneFrequencyReservation"("reservationKey");
CREATE INDEX "PhoneFrequencyReservation_applicationId_createdAt_idx"
ON "PhoneFrequencyReservation"("applicationId", "createdAt");
CREATE INDEX "PhoneFrequencyReservation_tenantId_createdAt_idx"
ON "PhoneFrequencyReservation"("tenantId", "createdAt");
ALTER TABLE "PhoneFrequencyReservation" ADD CONSTRAINT "PhoneFrequencyReservation_tenantId_fkey"
FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "PhoneFrequencyReservation" ADD CONSTRAINT "PhoneFrequencyReservation_applicationId_fkey"
FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,29 @@
CREATE TABLE "GatewaySubmitOutbox" (
"id" TEXT NOT NULL,
"submitId" TEXT NOT NULL,
"messageRecordId" TEXT NOT NULL,
"channelId" TEXT NOT NULL,
"payload" JSONB NOT NULL,
"schemaVersion" TEXT NOT NULL DEFAULT 'v1',
"status" TEXT NOT NULL DEFAULT 'pending',
"attemptCount" INTEGER NOT NULL DEFAULT 0,
"nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"leaseOwner" TEXT,
"leaseExpiresAt" TIMESTAMP(3),
"streamEntryId" TEXT,
"publishedAt" TIMESTAMP(3),
"lastError" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "GatewaySubmitOutbox_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "GatewaySubmitOutbox_submitId_key"
ON "GatewaySubmitOutbox"("submitId");
CREATE INDEX "GatewaySubmitOutbox_pending_claim_idx"
ON "GatewaySubmitOutbox"("nextAttemptAt", "createdAt")
WHERE "status" IN ('pending', 'publishing');
CREATE INDEX "GatewaySubmitOutbox_messageRecordId_idx"
ON "GatewaySubmitOutbox"("messageRecordId");
@@ -0,0 +1,3 @@
ALTER TABLE "SmsUplinkMessage" ADD COLUMN "eventId" TEXT;
CREATE UNIQUE INDEX "SmsUplinkMessage_eventId_key" ON "SmsUplinkMessage"("eventId");
@@ -0,0 +1,2 @@
ALTER TABLE "SmsUplinkMessage"
ADD COLUMN "gatewayMessageId" TEXT;
@@ -0,0 +1,9 @@
ALTER TABLE "ReportMaterialImportBatch"
ADD COLUMN "progress" INTEGER NOT NULL DEFAULT 100,
ADD COLUMN "progressStage" TEXT,
ADD COLUMN "errorMessage" TEXT,
ADD COLUMN "startedAt" TIMESTAMP(3),
ADD COLUMN "heartbeatAt" TIMESTAMP(3);
CREATE INDEX "ReportMaterialImportBatch_status_heartbeatAt_idx"
ON "ReportMaterialImportBatch"("status", "heartbeatAt");
@@ -0,0 +1,110 @@
CREATE TABLE "ReportReadinessState" (
"objectKey" TEXT PRIMARY KEY, "mask" INTEGER NOT NULL, "armed" BOOLEAN NOT NULL,
"cycle" INTEGER NOT NULL DEFAULT 0, "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
);
CREATE TABLE "ReportNotificationHour" (
"id" TEXT PRIMARY KEY, "tenantId" TEXT NOT NULL, "tenantName" TEXT NOT NULL,
"hour" TIMESTAMP(3) NOT NULL, "revision" INTEGER NOT NULL DEFAULT 1,
"signatureCount" INTEGER NOT NULL DEFAULT 0, "drainageCount" INTEGER NOT NULL DEFAULT 0,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
UNIQUE ("tenantId", "hour")
);
CREATE INDEX "ReportNotificationHour_hour_idx" ON "ReportNotificationHour" ("hour" DESC);
CREATE TABLE "ReportReadinessEvent" (
"id" TEXT PRIMARY KEY, "hourId" TEXT NOT NULL REFERENCES "ReportNotificationHour"("id"),
"objectKey" TEXT NOT NULL, "cycle" INTEGER NOT NULL, "tenantId" TEXT NOT NULL,
"reportType" TEXT NOT NULL, "signatureId" TEXT NOT NULL, "drainageItemId" TEXT,
"applicationId" TEXT, "applicationName" TEXT, "signatureName" TEXT NOT NULL,
"targetName" TEXT NOT NULL, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
UNIQUE ("objectKey", "cycle")
);
CREATE INDEX "ReportReadinessEvent_hour_idx" ON "ReportReadinessEvent" ("hourId", "createdAt", "id");
CREATE TABLE "ReportNotificationRead" (
"userId" TEXT NOT NULL, "hourId" TEXT NOT NULL REFERENCES "ReportNotificationHour"("id"),
"revision" INTEGER NOT NULL, PRIMARY KEY ("userId", "hourId")
);
CREATE FUNCTION cmpp_report_ready_mask(kind TEXT, signature_id TEXT, drainage_id TEXT) RETURNS INTEGER
LANGUAGE sql STABLE AS $$
SELECT COALESCE(sum(bit),0)::integer FROM (VALUES ('mobile',1),('unicom',2),('telecom',4)) AS carriers(name,bit)
WHERE EXISTS (
SELECT 1 FROM "SmsChannel" c
WHERE c.status='active' AND c."sendRegion"='全国'
AND (CASE WHEN cardinality(c.carriers)>0 THEN carriers.name=ANY(c.carriers)
ELSE c.carrier IN (carriers.name,'all') END)
AND (SELECT t.status FROM "ChannelSignatureReportTask" t
WHERE t."channelId"=c.id AND t."signatureId"=signature_id AND t."reportType"=kind
AND (kind='signature' OR t."drainageItemId"=drainage_id)
AND (t.carrier=carriers.name OR (t.carrier IS NULL AND t."approvalScope"='legacy_channel'))
ORDER BY (t.carrier=carriers.name) DESC NULLS LAST, t."updatedAt" DESC, t.id DESC LIMIT 1)='approved'
);
$$;
-- Seed only state. Existing successes must never become historical unread notices.
INSERT INTO "ReportReadinessState" ("objectKey",mask,armed)
SELECT 'signature:'||id, mask, mask=0 FROM "SmsSignature" s
CROSS JOIN LATERAL (SELECT cmpp_report_ready_mask('signature',s.id,NULL) AS mask) m;
INSERT INTO "ReportReadinessState" ("objectKey",mask,armed)
SELECT 'drainage:'||id, mask, mask=0 FROM "SmsDrainageInfo" d
CROSS JOIN LATERAL (SELECT cmpp_report_ready_mask('drainage',d."signatureId",d.id) AS mask) m;
CREATE FUNCTION cmpp_report_readiness_before() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE r "ChannelSignatureReportTask"; k TEXT; m INTEGER;
BEGIN
r := CASE WHEN TG_OP='DELETE' THEN OLD ELSE NEW END;
IF TG_OP='UPDATE' AND (OLD."signatureId",OLD."drainageItemId",OLD."reportType") IS DISTINCT FROM
(NEW."signatureId",NEW."drainageItemId",NEW."reportType") THEN
RAISE EXCEPTION 'Reporting task identity is immutable';
END IF;
k := r."reportType"||':'||CASE WHEN r."reportType"='drainage' THEN r."drainageItemId" ELSE r."signatureId" END;
IF k IS NULL THEN RETURN r; END IF;
PERFORM pg_advisory_xact_lock(hashtextextended(k, 20260906));
m := cmpp_report_ready_mask(r."reportType",r."signatureId",r."drainageItemId");
INSERT INTO "ReportReadinessState" ("objectKey",mask,armed) VALUES(k,m,m=0) ON CONFLICT DO NOTHING;
-- A configuration change can remove eligibility without changing a reporting task.
UPDATE "ReportReadinessState" SET mask=m, armed=armed OR m=0 WHERE "objectKey"=k;
RETURN r;
END;
$$;
CREATE FUNCTION cmpp_report_readiness_after() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE r "ChannelSignatureReportTask"; k TEXT; m INTEGER; st "ReportReadinessState";
sig "SmsSignature"; tenant_name TEXT; app_name TEXT; target_name TEXT;
app_id TEXT; hour_value TIMESTAMP(3); hour_id TEXT; next_cycle INTEGER;
BEGIN
r := CASE WHEN TG_OP='DELETE' THEN OLD ELSE NEW END;
k := r."reportType"||':'||CASE WHEN r."reportType"='drainage' THEN r."drainageItemId" ELSE r."signatureId" END;
IF k IS NULL THEN RETURN r; END IF;
SELECT * INTO st FROM "ReportReadinessState" WHERE "objectKey"=k FOR UPDATE;
m := cmpp_report_ready_mask(r."reportType",r."signatureId",r."drainageItemId");
IF m=7 AND st.armed THEN
SELECT * INTO sig FROM "SmsSignature" WHERE id=r."signatureId";
IF sig.id IS NOT NULL THEN
SELECT name INTO tenant_name FROM "Tenant" WHERE id=sig."tenantId";
app_id:=sig."applicationId"; target_name:=sig.name;
IF r."reportType"='drainage' THEN
SELECT COALESCE(d."applicationId",sig."applicationId"), d.url INTO app_id,target_name
FROM "SmsDrainageInfo" d WHERE id=r."drainageItemId";
END IF;
SELECT name INTO app_name FROM "SmsApplication" WHERE id=app_id;
hour_value:=date_trunc('hour',timezone('UTC',statement_timestamp()));
hour_id:=md5(sig."tenantId"||':'||hour_value::text);
next_cycle:=st.cycle+1;
INSERT INTO "ReportNotificationHour" (id,"tenantId","tenantName",hour,"signatureCount","drainageCount")
VALUES(hour_id,sig."tenantId",tenant_name,hour_value,(r."reportType"='signature')::integer,(r."reportType"='drainage')::integer)
ON CONFLICT ("tenantId",hour) DO UPDATE SET revision="ReportNotificationHour".revision+1,
"signatureCount"="ReportNotificationHour"."signatureCount"+EXCLUDED."signatureCount",
"drainageCount"="ReportNotificationHour"."drainageCount"+EXCLUDED."drainageCount",
"updatedAt"=timezone('UTC',statement_timestamp()) RETURNING id INTO hour_id;
INSERT INTO "ReportReadinessEvent" (id,"hourId","objectKey",cycle,"tenantId","reportType","signatureId","drainageItemId","applicationId","applicationName","signatureName","targetName")
VALUES(md5(k||':'||next_cycle),hour_id,k,next_cycle,sig."tenantId",r."reportType",sig.id,r."drainageItemId",app_id,app_name,sig.name,target_name);
UPDATE "ReportReadinessState" SET cycle=next_cycle,armed=false WHERE "objectKey"=k;
END IF;
END IF;
UPDATE "ReportReadinessState" SET mask=m,armed=armed OR m=0,"updatedAt"=timezone('UTC',statement_timestamp()) WHERE "objectKey"=k;
RETURN r;
END;
$$;
CREATE TRIGGER report_readiness_before BEFORE INSERT OR UPDATE OR DELETE ON "ChannelSignatureReportTask"
FOR EACH ROW EXECUTE FUNCTION cmpp_report_readiness_before();
CREATE TRIGGER report_readiness_after AFTER INSERT OR UPDATE OR DELETE ON "ChannelSignatureReportTask"
FOR EACH ROW EXECUTE FUNCTION cmpp_report_readiness_after();
@@ -0,0 +1,73 @@
ALTER TABLE "SmsSubmitRecord" ADD COLUMN "firstWireSubmitAt" TIMESTAMP(3), ADD COLUMN "wireTimeSource" TEXT;
ALTER TABLE "SmsMessageSegmentAudit" ADD COLUMN "firstWireSubmitAt" TIMESTAMP(3), ADD COLUMN "wireTimeSource" TEXT;
ALTER TABLE "UpstreamReceiptInbox" ADD COLUMN "gatewayReceivedAt" TIMESTAMP(3);
ALTER TABLE "SmsSubmitRecord" ADD COLUMN "receiptRequested" BOOLEAN;
ALTER TABLE "SmsMessageSegmentAudit" ADD COLUMN "receiptRequested" BOOLEAN;
CREATE INDEX "SmsSubmitRecord_monitor_updated_idx" ON "SmsSubmitRecord" ("updatedAt",id);
CREATE INDEX "SmsSubmitRecord_monitor_created_idx" ON "SmsSubmitRecord" ("createdAt",id);
CREATE INDEX "UpstreamReceiptInbox_monitor_updated_idx" ON "UpstreamReceiptInbox" ("updatedAt",id);
CREATE INDEX "UpstreamReceiptInbox_monitor_message_idx" ON "UpstreamReceiptInbox" ("matchedMessageRecordId","gatewayMessageId");
CREATE TABLE "SendingMonitorTarget" (
"channelId" TEXT PRIMARY KEY, enabled BOOLEAN NOT NULL, version INTEGER NOT NULL,
"effectiveFrom" TIMESTAMP(3) NOT NULL, "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
"updatedBy" TEXT NOT NULL
);
CREATE TABLE "SendingMonitorTargetVersion" (
"channelId" TEXT NOT NULL, version INTEGER NOT NULL, enabled BOOLEAN NOT NULL,
"effectiveFrom" TIMESTAMP(3) NOT NULL, "updatedBy" TEXT NOT NULL,
PRIMARY KEY("channelId",version)
);
CREATE TABLE "SendingMonitorRule" (
id TEXT PRIMARY KEY, type TEXT NOT NULL, "scopeKey" TEXT NOT NULL, scope JSONB NOT NULL,
config JSONB NOT NULL, version INTEGER NOT NULL, "effectiveAt" TIMESTAMP(3) NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), "updatedBy" TEXT NOT NULL,
UNIQUE(type,"scopeKey")
);
CREATE TABLE "SendingMonitorRuleVersion" (
"ruleId" TEXT NOT NULL, version INTEGER NOT NULL, type TEXT NOT NULL, scope JSONB NOT NULL,
config JSONB NOT NULL, "effectiveAt" TIMESTAMP(3) NOT NULL, "createdAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
"createdBy" TEXT NOT NULL, PRIMARY KEY("ruleId",version)
);
CREATE INDEX "SendingMonitorRuleVersion_effective_idx" ON "SendingMonitorRuleVersion" (type,"effectiveAt");
CREATE TABLE "SendingMonitorFact" (
id TEXT PRIMARY KEY, kind TEXT NOT NULL, "sourceId" TEXT NOT NULL, "dimensionKey" TEXT NOT NULL,
"messageRecordId" TEXT REFERENCES "SmsMessageRecord"(id) ON DELETE SET NULL ON UPDATE CASCADE,
dimensions JSONB NOT NULL, "submittedAt" TIMESTAMP(3) NOT NULL, "successAt" TIMESTAMP(3),
verification BOOLEAN NOT NULL, reason TEXT, "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
UNIQUE(kind,"sourceId")
);
CREATE INDEX "SendingMonitorFact_window_idx" ON "SendingMonitorFact" (kind,"submittedAt","dimensionKey");
CREATE INDEX "SendingMonitorFact_message_idx" ON "SendingMonitorFact" ("messageRecordId");
CREATE TABLE "SendingMonitorMinute" (
kind TEXT NOT NULL, "dimensionKey" TEXT NOT NULL, minute TIMESTAMP(3) NOT NULL,
verification BOOLEAN NOT NULL, dimensions JSONB NOT NULL, metrics JSONB NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
PRIMARY KEY(kind,"dimensionKey",minute,verification)
);
CREATE INDEX "SendingMonitorMinute_window_idx" ON "SendingMonitorMinute" (kind,minute);
CREATE TABLE "SendingMonitorSnapshot" (
id TEXT PRIMARY KEY, type TEXT NOT NULL, "dimensionKey" TEXT NOT NULL, dimensions JSONB NOT NULL,
"evaluationAt" TIMESTAMP(3) NOT NULL, "windowFrom" TIMESTAMP(3) NOT NULL,
"observedUntil" TIMESTAMP(3) NOT NULL, stage TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1,
metrics JSONB NOT NULL, rule JSONB, status TEXT NOT NULL, completeness JSONB NOT NULL,
"computedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
UNIQUE(type,"dimensionKey","evaluationAt")
);
CREATE INDEX "SendingMonitorSnapshot_latest_idx" ON "SendingMonitorSnapshot" (type,"evaluationAt" DESC,status);
CREATE INDEX "SendingMonitorSnapshot_history_idx" ON "SendingMonitorSnapshot" (type,"dimensionKey","evaluationAt");
CREATE TABLE "SendingMonitorAlert" (
id TEXT PRIMARY KEY, type TEXT NOT NULL, "dimensionKey" TEXT NOT NULL, dimensions JSONB NOT NULL,
state TEXT NOT NULL, "openedAt" TIMESTAMP(3) NOT NULL, "lastEvaluatedAt" TIMESTAMP(3) NOT NULL,
"closedAt" TIMESTAMP(3), "closeReason" TEXT, "ruleKey" TEXT NOT NULL,
latest JSONB NOT NULL, worst JSONB NOT NULL, "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
);
CREATE UNIQUE INDEX "SendingMonitorAlert_one_active_idx" ON "SendingMonitorAlert" (type,"dimensionKey") WHERE state='active';
CREATE INDEX "SendingMonitorAlert_state_idx" ON "SendingMonitorAlert" (state,"openedAt" DESC);
CREATE TABLE "SendingMonitorAlertRead" (
"alertId" TEXT NOT NULL, "userId" TEXT NOT NULL, "readAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
PRIMARY KEY("alertId","userId")
);
CREATE TABLE "SendingMonitorCheckpoint" (
id TEXT PRIMARY KEY, data JSONB NOT NULL, "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
);
@@ -0,0 +1,38 @@
CREATE TABLE "NightSendingWindow" (
"id" TEXT PRIMARY KEY,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"windowStartedAt" TIMESTAMP(3) NOT NULL,
"windowEndsAt" TIMESTAMP(3) NOT NULL,
"count" INTEGER NOT NULL DEFAULT 0,
"baselineCount" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL
);
CREATE UNIQUE INDEX "NightSendingWindow_applicationId_windowStartedAt_key" ON "NightSendingWindow"("applicationId", "windowStartedAt");
CREATE INDEX "NightSendingWindow_applicationId_windowEndsAt_idx" ON "NightSendingWindow"("applicationId", "windowEndsAt");
CREATE TABLE "NightSendingReservation" (
"messageRecordId" TEXT PRIMARY KEY,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"windowId" TEXT NOT NULL,
"sequence" INTEGER NOT NULL,
"thresholdValue" INTEGER NOT NULL,
"reviewTaskId" TEXT,
"continuedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "NightSendingReservation_applicationId_windowId_idx" ON "NightSendingReservation"("applicationId", "windowId");
CREATE INDEX "NightSendingReservation_reviewTaskId_idx" ON "NightSendingReservation"("reviewTaskId");
ALTER TABLE "SmsSendTask" ADD COLUMN "continuationLeaseOwner" TEXT;
ALTER TABLE "SmsSendTask" ADD COLUMN "continuationLeaseExpiresAt" TIMESTAMP(3);
-- Preserve rule IDs and thresholds for application overrides and historical hits.
UPDATE "RiskRule" SET "name" = '夜间累计发送量审核',
"description" = '同一企业应用在夜间累计业务短信超过阈值后进入人工审核,所有入口与内容合并计数。',
"metric" = 'nightSendingCount', "action" = 'manual_review',
"config" = COALESCE("config", '{}'::jsonb) || '{"timeZone":"Asia/Shanghai"}'::jsonb,
"updatedAt" = CURRENT_TIMESTAMP
WHERE "code" = 'NON_WORKING_MARKETING_BULK';
-- The newly approved policy applies by default to every application.
UPDATE "RiskRule" SET "status" = 'active', "updatedAt" = CURRENT_TIMESTAMP
WHERE "code" = 'NON_WORKING_MARKETING_BULK' AND "applicationId" IS NULL AND "status" <> 'deleted';
@@ -0,0 +1,7 @@
-- Nullable additive fields preserve historical messages and old readers.
ALTER TABLE "SignatureRetirementMessage"
ADD COLUMN "dailyGroupKey" TEXT,
ADD COLUMN "notificationDate" DATE,
ADD COLUMN "applicationId" TEXT,
ADD COLUMN "detectionIds" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];
CREATE UNIQUE INDEX "SignatureRetirementMessage_dailyGroupKey_key" ON "SignatureRetirementMessage"("dailyGroupKey");
@@ -0,0 +1,30 @@
ALTER TABLE "SmsMessageRecord" ADD COLUMN "drainageGate" JSONB;
ALTER TABLE "SmsSubmitRecord" ADD COLUMN "drainageGate" JSONB;
ALTER TABLE "SmsMessageRecord" ADD COLUMN "drainageReceiptPending" BOOLEAN NOT NULL DEFAULT false;
CREATE INDEX "SmsMessageRecord_drainage_receipt_pending" ON "SmsMessageRecord" ("updatedAt") WHERE "drainageReceiptPending" = true;
CREATE TABLE "SmsDrainageDecision" (
"id" TEXT PRIMARY KEY,
"messageRecordId" TEXT NOT NULL,
"decidedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"snapshot" JSONB NOT NULL
);
CREATE INDEX "SmsDrainageDecision_messageRecordId_decidedAt_idx" ON "SmsDrainageDecision" ("messageRecordId", "decidedAt");
CREATE OR REPLACE FUNCTION drainage_authorization_lock() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'UPDATE' AND OLD."signatureId" IS DISTINCT FROM NEW."signatureId" THEN
PERFORM pg_advisory_xact_lock(hashtextextended(value, 910))
FROM unnest(ARRAY[OLD."signatureId", NEW."signatureId"]) AS ids(value) ORDER BY value;
RETURN NEW;
END IF;
IF TG_OP = 'DELETE' THEN
PERFORM pg_advisory_xact_lock(hashtextextended(OLD."signatureId", 910));
RETURN OLD;
END IF;
PERFORM pg_advisory_xact_lock(hashtextextended(NEW."signatureId", 910));
RETURN NEW;
END $$;
CREATE TRIGGER drainage_material_authorization_lock BEFORE INSERT OR UPDATE OR DELETE ON "SmsDrainageInfo"
FOR EACH ROW EXECUTE FUNCTION drainage_authorization_lock();
CREATE TRIGGER drainage_report_authorization_lock BEFORE INSERT OR UPDATE OR DELETE ON "ChannelSignatureReportTask"
FOR EACH ROW EXECUTE FUNCTION drainage_authorization_lock();
@@ -0,0 +1,20 @@
CREATE TABLE "ChannelSensitiveWord" (
"id" TEXT PRIMARY KEY, "channelId" TEXT NOT NULL, "word" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'active', "remark" TEXT NOT NULL DEFAULT '',
"version" INTEGER NOT NULL DEFAULT 1, "createdBy" TEXT NOT NULL, "updatedBy" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ChannelSensitiveWord_channelId_fkey" FOREIGN KEY ("channelId") REFERENCES "SmsChannel"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "ChannelSensitiveWord_status_check" CHECK ("status" IN ('active','inactive','deleted')),
CONSTRAINT "ChannelSensitiveWord_word_check" CHECK (char_length("word") BETWEEN 1 AND 200)
);
CREATE UNIQUE INDEX "ChannelSensitiveWord_channelId_word_key" ON "ChannelSensitiveWord"("channelId","word");
CREATE INDEX "ChannelSensitiveWord_channelId_status_idx" ON "ChannelSensitiveWord"("channelId","status");
CREATE TABLE "SmsChannelSensitiveDecision" (
"id" TEXT PRIMARY KEY, "messageRecordId" TEXT NOT NULL, "routeAttemptId" TEXT NOT NULL,
"decidedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "snapshot" JSONB NOT NULL,
CONSTRAINT "SmsChannelSensitiveDecision_messageRecordId_fkey" FOREIGN KEY ("messageRecordId") REFERENCES "SmsMessageRecord"("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
CREATE UNIQUE INDEX "SmsChannelSensitiveDecision_routeAttemptId_key" ON "SmsChannelSensitiveDecision"("routeAttemptId");
CREATE INDEX "SmsChannelSensitiveDecision_messageRecordId_decidedAt_idx" ON "SmsChannelSensitiveDecision"("messageRecordId","decidedAt");
ALTER TABLE "SmsMessageRecord" ADD COLUMN "channelWordFinalizationPending" BOOLEAN NOT NULL DEFAULT false;
CREATE INDEX "SmsMessageRecord_channelWordFinalizationPending_idx" ON "SmsMessageRecord"("updatedAt") WHERE "channelWordFinalizationPending" = true;
@@ -0,0 +1,11 @@
ALTER TABLE "HttpWebhookDelivery" ADD COLUMN "recoveryVersion" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN "leaseToken" TEXT, ADD COLUMN "leaseUntil" TIMESTAMP(3);
CREATE TABLE "OpenApiDispatchOutbox" (
"id" TEXT NOT NULL, "requestId" TEXT NOT NULL, "batchTaskId" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'pending', "leaseToken" TEXT, "leaseUntil" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "OpenApiDispatchOutbox_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "OpenApiDispatchOutbox_requestId_key" ON "OpenApiDispatchOutbox"("requestId");
CREATE UNIQUE INDEX "OpenApiDispatchOutbox_batchTaskId_key" ON "OpenApiDispatchOutbox"("batchTaskId");
CREATE INDEX "OpenApiDispatchOutbox_status_leaseUntil_idx" ON "OpenApiDispatchOutbox"("status", "leaseUntil");
@@ -0,0 +1,10 @@
-- Preserve all legacy rows; independent carrier states require distinct business keys.
BEGIN;
CREATE UNIQUE INDEX "ChannelSignatureReportTask_drainage_carrier_key"
ON "ChannelSignatureReportTask" ("signatureId", "drainageItemId", "channelId", "carrier")
WHERE "reportType" = 'drainage' AND "drainageItemId" IS NOT NULL AND "carrier" IS NOT NULL;
CREATE UNIQUE INDEX "ChannelSignatureReportTask_drainage_legacy_key"
ON "ChannelSignatureReportTask" ("signatureId", "drainageItemId", "channelId")
WHERE "reportType" = 'drainage' AND "drainageItemId" IS NOT NULL AND "carrier" IS NULL;
DROP INDEX "ChannelSignatureReportTask_drainage_target_key";
COMMIT;
@@ -0,0 +1,17 @@
CREATE TABLE "InfrastructureAlertCollection" (
"id" TEXT NOT NULL PRIMARY KEY,
"observedAt" TIMESTAMP(3) NOT NULL
);
CREATE TABLE "InfrastructureAlertEvent" (
"id" TEXT NOT NULL PRIMARY KEY,
"fingerprint" TEXT NOT NULL,
"activeAt" TIMESTAMP(3) NOT NULL,
"payload" JSONB NOT NULL,
"lastObservedAt" TIMESTAMP(3) NOT NULL,
"recoveredAt" TIMESTAMP(3),
"clearedAt" TIMESTAMP(3),
"clearedBy" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX "InfrastructureAlertEvent_fingerprint_activeAt_key" ON "InfrastructureAlertEvent"("fingerprint", "activeAt");
CREATE INDEX "InfrastructureAlertEvent_clearedAt_activeAt_idx" ON "InfrastructureAlertEvent"("clearedAt", "activeAt");
@@ -0,0 +1,15 @@
CREATE TABLE "SmsAttemptCompletionWork" (
"id" TEXT PRIMARY KEY, "workKey" TEXT NOT NULL, "tenantId" TEXT, "messageRecordId" TEXT NOT NULL, "sourceSubmitRecordId" TEXT,
"revision" INTEGER NOT NULL DEFAULT 0, "processedRevision" INTEGER NOT NULL DEFAULT 0, "state" TEXT NOT NULL DEFAULT 'pending',
"leaseOwner" TEXT, "leaseUntil" TIMESTAMP(3), "fenceVersion" INTEGER NOT NULL DEFAULT 0, "attempts" INTEGER NOT NULL DEFAULT 0,
"nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), "decision" TEXT, "retrySubmitRecordId" TEXT, "lastError" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'));
CREATE UNIQUE INDEX "SmsAttemptCompletionWork_workKey_key" ON "SmsAttemptCompletionWork"("workKey");
CREATE UNIQUE INDEX "SmsAttemptCompletionWork_sourceSubmitRecordId_key" ON "SmsAttemptCompletionWork"("sourceSubmitRecordId");
CREATE INDEX "SmsAttemptCompletionWork_state_nextAttemptAt_idx" ON "SmsAttemptCompletionWork"("state", "nextAttemptAt");
CREATE INDEX "SmsAttemptCompletionWork_state_leaseUntil_idx" ON "SmsAttemptCompletionWork"("state", "leaseUntil");
CREATE INDEX "SmsAttemptCompletionWork_messageRecordId_idx" ON "SmsAttemptCompletionWork"("messageRecordId");
CREATE TABLE "SmsCompletionEvent" ("id" TEXT PRIMARY KEY, "eventKey" TEXT NOT NULL, "workId" TEXT NOT NULL REFERENCES "SmsAttemptCompletionWork"("id") ON DELETE RESTRICT,
"kind" TEXT NOT NULL, "payload" JSONB NOT NULL, "processedAt" TIMESTAMP(3), "createdAt" TIMESTAMP(3) NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'));
CREATE UNIQUE INDEX "SmsCompletionEvent_eventKey_key" ON "SmsCompletionEvent"("eventKey");
CREATE INDEX "SmsCompletionEvent_workId_processedAt_createdAt_idx" ON "SmsCompletionEvent"("workId", "processedAt", "createdAt");
@@ -0,0 +1,130 @@
-- CreateTable
CREATE TABLE "SignatureAnalyticsGeneration" (
"id" TEXT NOT NULL,
"businessDate" DATE NOT NULL,
"sourceAsOf" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SignatureAnalyticsGeneration_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SignatureAnalyticsDay" (
"businessDate" DATE NOT NULL,
"publishedGenerationId" TEXT,
"generatedAt" TIMESTAMP(3),
"sourceAsOf" TIMESTAMP(3),
"refreshFor" DATE,
"state" TEXT NOT NULL DEFAULT 'missing',
"error" TEXT,
"provenance" TEXT NOT NULL DEFAULT 'daily',
"schemaVersion" INTEGER NOT NULL DEFAULT 1,
"rowCounts" JSONB,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SignatureAnalyticsDay_pkey" PRIMARY KEY ("businessDate")
);
-- CreateTable
CREATE TABLE "SignatureAnalyticsRun" (
"id" TEXT NOT NULL,
"scope" TEXT NOT NULL,
"businessDate" DATE NOT NULL,
"refreshFor" DATE NOT NULL,
"generationId" TEXT NOT NULL,
"state" TEXT NOT NULL DEFAULT 'pending',
"owner" TEXT,
"fence" INTEGER NOT NULL DEFAULT 0,
"leaseUntil" TIMESTAMP(3),
"attempt" INTEGER NOT NULL DEFAULT 0,
"nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"checkpoint" JSONB,
"error" TEXT,
"startedAt" TIMESTAMP(3),
"finishedAt" TIMESTAMP(3),
CONSTRAINT "SignatureAnalyticsRun_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SignatureQualityDaily" (
"generationId" TEXT NOT NULL,
"businessDate" DATE NOT NULL,
"signatureId" TEXT NOT NULL,
"signatureName" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"tenantName" TEXT NOT NULL,
"applicationNames" TEXT NOT NULL,
"total" INTEGER NOT NULL,
"payload" JSONB NOT NULL,
CONSTRAINT "SignatureQualityDaily_pkey" PRIMARY KEY ("generationId","signatureId")
);
-- CreateTable
CREATE TABLE "SignatureActivityDaily" (
"generationId" TEXT NOT NULL,
"businessDate" DATE NOT NULL,
"dimensionKey" TEXT NOT NULL,
"dimensionType" TEXT NOT NULL,
"signatureId" TEXT NOT NULL,
"channelKey" TEXT NOT NULL,
"carrier" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT,
"signatureName" TEXT NOT NULL,
"tenantName" TEXT NOT NULL,
"applicationName" TEXT NOT NULL,
"channelName" TEXT NOT NULL,
"approvedAt" TIMESTAMP(3),
"submittedAttempts" INTEGER NOT NULL,
"acceptedBusinessCount" INTEGER NOT NULL,
"deliveredBusinessCount" INTEGER NOT NULL,
"applicability" TEXT NOT NULL,
CONSTRAINT "SignatureActivityDaily_pkey" PRIMARY KEY ("generationId","dimensionKey")
);
-- CreateTable
CREATE TABLE "UnreportedSignatureDaily" (
"generationId" TEXT NOT NULL,
"businessDate" DATE NOT NULL,
"dimensionKey" TEXT NOT NULL,
"tenantId" TEXT NOT NULL,
"applicationId" TEXT NOT NULL,
"signatureName" TEXT NOT NULL,
"tenantName" TEXT NOT NULL,
"applicationName" TEXT NOT NULL,
"messageCount" INTEGER NOT NULL,
CONSTRAINT "UnreportedSignatureDaily_pkey" PRIMARY KEY ("generationId","dimensionKey")
);
-- CreateIndex
CREATE UNIQUE INDEX "SignatureAnalyticsGeneration_id_businessDate_key" ON "SignatureAnalyticsGeneration"("id", "businessDate");
-- CreateIndex
CREATE INDEX "SignatureAnalyticsRun_state_nextAttemptAt_idx" ON "SignatureAnalyticsRun"("state", "nextAttemptAt");
-- CreateIndex
CREATE UNIQUE INDEX "SignatureAnalyticsRun_scope_businessDate_key" ON "SignatureAnalyticsRun"("scope", "businessDate");
-- CreateIndex
CREATE INDEX "SignatureQualityDaily_businessDate_generationId_total_idx" ON "SignatureQualityDaily"("businessDate", "generationId", "total");
-- CreateIndex
CREATE INDEX "SignatureActivityDaily_businessDate_generationId_dimensionT_idx" ON "SignatureActivityDaily"("businessDate", "generationId", "dimensionType", "acceptedBusinessCount");
-- CreateIndex
CREATE INDEX "UnreportedSignatureDaily_businessDate_generationId_messageC_idx" ON "UnreportedSignatureDaily"("businessDate", "generationId", "messageCount");
-- AddForeignKey
ALTER TABLE "SignatureAnalyticsDay" ADD CONSTRAINT "SignatureAnalyticsDay_publishedGenerationId_businessDate_fkey" FOREIGN KEY ("publishedGenerationId", "businessDate") REFERENCES "SignatureAnalyticsGeneration"("id", "businessDate") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "SignatureQualityDaily" ADD CONSTRAINT "SignatureQualityDaily_generationId_businessDate_fkey" FOREIGN KEY ("generationId", "businessDate") REFERENCES "SignatureAnalyticsGeneration"("id", "businessDate") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "SignatureActivityDaily" ADD CONSTRAINT "SignatureActivityDaily_generationId_businessDate_fkey" FOREIGN KEY ("generationId", "businessDate") REFERENCES "SignatureAnalyticsGeneration"("id", "businessDate") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "UnreportedSignatureDaily" ADD CONSTRAINT "UnreportedSignatureDaily_generationId_businessDate_fkey" FOREIGN KEY ("generationId", "businessDate") REFERENCES "SignatureAnalyticsGeneration"("id", "businessDate") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,4 @@
-- Expression index matches the actual report/retirement time predicate, including legacy NULL submittedAt.
-- Deliberately outside a transaction: online construction must not block SMS writes.
CREATE INDEX CONCURRENTLY "SmsSubmitRecord_effective_at_idx"
ON "SmsSubmitRecord" ((COALESCE("submittedAt", "createdAt")));
@@ -0,0 +1,24 @@
CREATE TABLE "HomeProjectionState" (id TEXT PRIMARY KEY, version INTEGER NOT NULL DEFAULT 0, "seededDay" TEXT, initialized BOOLEAN NOT NULL DEFAULT false, "lastError" TEXT, "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE "HomeProjectionDirty" ("messageRecordId" TEXT PRIMARY KEY,"enqueuedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE "HomeMessageFact" ("messageRecordId" TEXT NOT NULL,"fromVersion" INTEGER NOT NULL,"toVersion" INTEGER,"queuedDay" TEXT NOT NULL,payload JSONB NOT NULL,PRIMARY KEY("messageRecordId","fromVersion"));
CREATE INDEX "HomeMessageFact_queuedDay_toVersion_idx" ON "HomeMessageFact"("queuedDay","toVersion");
CREATE TABLE "HomeSnapshot" (id TEXT PRIMARY KEY,"userId" TEXT NOT NULL,"businessDate" TEXT NOT NULL,version INTEGER NOT NULL,"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,"expiresAt" TIMESTAMP(3) NOT NULL,summary JSONB NOT NULL);
CREATE INDEX "HomeSnapshot_expiresAt_idx" ON "HomeSnapshot"("expiresAt");
INSERT INTO "HomeProjectionState"(id) VALUES ('home');
-- A durable, transactional invalidation only: no business state or external effects.
CREATE FUNCTION home_mark_dirty() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE mid TEXT;
BEGIN
IF TG_TABLE_NAME = 'SmsMessageRecord' THEN mid := COALESCE(NEW.id,OLD.id);
ELSIF TG_TABLE_NAME = 'UpstreamReceiptInbox' THEN mid := COALESCE(NEW."matchedMessageRecordId",OLD."matchedMessageRecordId");
ELSE mid := COALESCE(NEW."messageRecordId",OLD."messageRecordId"); END IF;
IF mid IS NOT NULL THEN
INSERT INTO "HomeProjectionDirty"("messageRecordId") VALUES(mid) ON CONFLICT ("messageRecordId") DO UPDATE SET "enqueuedAt"=CURRENT_TIMESTAMP;
END IF;
RETURN NULL;
END $$;
CREATE TRIGGER home_message_dirty AFTER INSERT OR UPDATE OR DELETE ON "SmsMessageRecord" FOR EACH ROW EXECUTE FUNCTION home_mark_dirty();
CREATE TRIGGER home_submit_dirty AFTER INSERT OR UPDATE OR DELETE ON "SmsSubmitRecord" FOR EACH ROW EXECUTE FUNCTION home_mark_dirty();
CREATE TRIGGER home_segment_dirty AFTER INSERT OR UPDATE OR DELETE ON "SmsMessageSegmentAudit" FOR EACH ROW EXECUTE FUNCTION home_mark_dirty();
CREATE TRIGGER home_inbox_dirty AFTER INSERT OR UPDATE OR DELETE ON "UpstreamReceiptInbox" FOR EACH ROW EXECUTE FUNCTION home_mark_dirty();
CREATE TRIGGER home_receipt_dirty AFTER INSERT OR UPDATE OR DELETE ON "SmsReceiptRecord" FOR EACH ROW EXECUTE FUNCTION home_mark_dirty();
@@ -0,0 +1,24 @@
-- Re-association invalidates both owners; source writes and the durable invalidation are atomic.
CREATE OR REPLACE FUNCTION home_mark_dirty() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE mid TEXT; previous_mid TEXT;
BEGIN
IF TG_TABLE_NAME = 'SmsMessageRecord' THEN
mid := COALESCE(NEW.id,OLD.id); previous_mid := OLD.id;
ELSIF TG_TABLE_NAME = 'UpstreamReceiptInbox' THEN
mid := COALESCE(NEW."matchedMessageRecordId",OLD."matchedMessageRecordId"); previous_mid := OLD."matchedMessageRecordId";
ELSE
mid := COALESCE(NEW."messageRecordId",OLD."messageRecordId"); previous_mid := OLD."messageRecordId";
END IF;
IF mid IS NOT NULL THEN
INSERT INTO "HomeProjectionDirty"("messageRecordId") VALUES(mid)
ON CONFLICT ("messageRecordId") DO UPDATE SET "enqueuedAt"=CURRENT_TIMESTAMP;
END IF;
IF previous_mid IS NOT NULL AND previous_mid IS DISTINCT FROM mid THEN
INSERT INTO "HomeProjectionDirty"("messageRecordId") VALUES(previous_mid)
ON CONFLICT ("messageRecordId") DO UPDATE SET "enqueuedAt"=CURRENT_TIMESTAMP;
END IF;
RETURN NULL;
END $$;
CREATE INDEX "HomeProjectionDirty_enqueuedAt_idx" ON "HomeProjectionDirty"("enqueuedAt");
CREATE INDEX "HomeMessageFact_toVersion_idx" ON "HomeMessageFact"("toVersion");
CREATE UNIQUE INDEX "HomeMessageFact_current_key" ON "HomeMessageFact"("messageRecordId") WHERE "toVersion" IS NULL;
@@ -0,0 +1,24 @@
BEGIN;
-- Preserve every historical record. A conflicting installation must be reviewed before release.
LOCK TABLE "SmsSignature" IN SHARE ROW EXCLUSIVE MODE;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM "SmsSignature"
WHERE "auditStatus" NOT IN ('deleted', 'disabled')
GROUP BY "tenantId", "applicationId", "name" HAVING count(*) > 1
) THEN
RAISE EXCEPTION 'Cannot enforce signature uniqueness: duplicate active signatures exist; review tenantId/applicationId/name groups without deleting or merging automatically';
END IF;
END $$;
CREATE UNIQUE INDEX "SmsSignature_active_application_name_key"
ON "SmsSignature" ("tenantId", "applicationId", "name")
WHERE "applicationId" IS NOT NULL AND "auditStatus" NOT IN ('deleted', 'disabled');
CREATE UNIQUE INDEX "SmsSignature_active_unbound_name_key"
ON "SmsSignature" ("tenantId", "name")
WHERE "applicationId" IS NULL AND "auditStatus" NOT IN ('deleted', 'disabled');
COMMIT;
@@ -0,0 +1,4 @@
ALTER TABLE "SmsTemplate" ADD COLUMN "optOutRules" JSONB NOT NULL DEFAULT '[]';
ALTER TABLE "SmsTemplate" ADD CONSTRAINT "SmsTemplate_optOutRules_array" CHECK (jsonb_typeof("optOutRules") = 'array');
ALTER TABLE "SmsMessageRecord" ADD COLUMN "originalContent" TEXT;
ALTER TABLE "SmsSubmitRecord" ADD COLUMN "sentContent" TEXT, ADD COLUMN "contentPolicy" JSONB;
@@ -0,0 +1,19 @@
-- Widen only; historical invalid values abort the entire transaction. Never narrow on rollback.
BEGIN;
SET LOCAL lock_timeout = '5s';
SET LOCAL statement_timeout = '5min';
ALTER TABLE "UpstreamReceiptInbox" ALTER COLUMN "sequenceId" TYPE BIGINT,
ADD CONSTRAINT "UpstreamReceiptInbox_sequenceId_uint32_check" CHECK ("sequenceId" BETWEEN 0 AND 4294967295);
ALTER TABLE "SmsReceiptRecord" ALTER COLUMN "sequenceId" TYPE BIGINT,
ADD CONSTRAINT "SmsReceiptRecord_sequenceId_uint32_check" CHECK ("sequenceId" BETWEEN 0 AND 4294967295);
ALTER TABLE "SmsUplinkMessage" ALTER COLUMN "sequenceId" TYPE BIGINT,
ADD CONSTRAINT "SmsUplinkMessage_sequenceId_uint32_check" CHECK ("sequenceId" BETWEEN 0 AND 4294967295);
ALTER TABLE "SmsSubmitRecord" ALTER COLUMN "sequenceId" TYPE BIGINT,
ADD CONSTRAINT "SmsSubmitRecord_sequenceId_uint32_check" CHECK ("sequenceId" BETWEEN 0 AND 4294967295);
ALTER TABLE "SmsMessageSegmentAudit" ALTER COLUMN "sequenceId" TYPE BIGINT,
ADD CONSTRAINT "SmsMessageSegmentAudit_sequenceId_uint32_check" CHECK ("sequenceId" BETWEEN 0 AND 4294967295);
ALTER TABLE "CmppDownstreamDelivery" ALTER COLUMN "ackResult" TYPE BIGINT,
ADD CONSTRAINT "CmppDownstreamDelivery_ackResult_uint32_check" CHECK ("ackResult" BETWEEN 0 AND 4294967295);
ALTER TABLE "CmppDownstreamDeliveryAttempt" ALTER COLUMN "ackResult" TYPE BIGINT,
ADD CONSTRAINT "CmppDownstreamDeliveryAttempt_ackResult_uint32_check" CHECK ("ackResult" BETWEEN 0 AND 4294967295);
COMMIT;
+1145 -45
View File
File diff suppressed because it is too large Load Diff
+27 -2
View File
@@ -1,3 +1,7 @@
import { APP_INTERCEPTOR } from '@nestjs/core';
import { ProtocolFieldsInterceptor } from './common/protocol-fields.interceptor';
import { SignatureAnalyticsModule } from './signature-analytics/signature-analytics.module';
import { HomeModule } from './home-dashboard/home.module';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AuditModule } from './audit/audit.module';
@@ -12,6 +16,7 @@ import { DictionariesModule } from './dictionaries/dictionaries.module';
import { DeletionGovernanceModule } from './deletion-governance/deletion-governance.module';
import { FilesModule } from './files/files.module';
import { HealthController } from './health.controller';
import { InfrastructureMonitoringModule } from './infrastructure-monitoring/infrastructure-monitoring.module';
import { OperationsModule } from './operations/operations.module';
import { OpenApiModule } from './open-api/open-api.module';
import { PrismaModule } from './prisma/prisma.module';
@@ -23,6 +28,11 @@ import { SendChainModule } from './send-chain/send-chain.module';
import { SmsConfigModule } from './sms-config/sms-config.module';
import { TenantsModule } from './tenants/tenants.module';
import { UsersModule } from './users/users.module';
import { SignatureRetirementModule } from './signature-retirement/signature-retirement.module';
import { SecurityDetectionModule } from './security-detection/security-detection.module';
import { MetricsModule } from './metrics/metrics.module';
import { ReportNotificationsModule } from './report-notifications/report-notifications.module';
import { SendingMonitorModule } from './sending-monitor/sending-monitor.module';
@Module({
imports: [
@@ -48,13 +58,28 @@ import { UsersModule } from './users/users.module';
ReportMaterialsModule,
SendChainModule,
OperationsModule,
InfrastructureMonitoringModule,
OpenApiModule,
SignatureRetirementModule,
SignatureAnalyticsModule,
HomeModule,
SecurityDetectionModule,
MetricsModule,
ReportNotificationsModule,
SendingMonitorModule,
],
controllers: [HealthController],
providers: [RequestContextMiddleware, SessionValidationMiddleware, ManualOperationAuditMiddleware],
providers: [
{ provide: APP_INTERCEPTOR, useClass: ProtocolFieldsInterceptor },
RequestContextMiddleware,
SessionValidationMiddleware,
ManualOperationAuditMiddleware,
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(RequestContextMiddleware, SessionValidationMiddleware, ManualOperationAuditMiddleware).forRoutes('*');
consumer
.apply(RequestContextMiddleware, SessionValidationMiddleware, ManualOperationAuditMiddleware)
.forRoutes('*');
}
}
+103 -21
View File
@@ -1,12 +1,16 @@
import { Body, Controller, Get, Post, Req, Res, UnauthorizedException } from '@nestjs/common';
import { Body, Controller, Get, Post, Req, Res, UnauthorizedException, UsePipes } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { CurrentSessionUserId } from './current-session-user.decorator';
import { AuthService, LoginDto } from './auth.service';
import { AuthService } from './auth.service';
import { ChangeOwnPasswordDto, LoginDto, PasswordVerificationDto } from './auth.dto';
import { strictValidationPipe } from '../common/strict-validation.pipe';
import { DEVELOPMENT_SESSION_COOKIE_NAME, SESSION_COOKIE_NAME, SessionPortal, SessionService } from './session.service';
import type { SessionRequest } from './session-validation.middleware';
import { UsersService } from '../users/users.service';
import { PrismaService } from '../prisma/prisma.service';
import { Prisma } from '@prisma/client';
import { requestContext } from '../common/request-context';
import { SecurityDetectionService } from '../security-detection/security-detection.service';
type CookieResponse = {
cookie(name: string, value: string, options: Record<string, unknown>): void;
@@ -16,26 +20,56 @@ type CookieResponse = {
@ApiTags('auth')
@Controller()
export class AuthController {
constructor(private readonly auth: AuthService, private readonly users: UsersService, private readonly sessions: SessionService, private readonly prisma: PrismaService) {}
constructor(
private readonly auth: AuthService,
private readonly users: UsersService,
private readonly sessions: SessionService,
private readonly prisma: PrismaService,
private readonly security: SecurityDetectionService,
) {}
@Get('admin/auth/captcha')
adminCaptcha() {
return this.auth.createCaptcha();
adminCaptcha(@Req() request: SessionRequest) {
return this.auth.createCaptcha(this.sourceIp(request));
}
@Post('admin/auth/login')
async adminLogin(@Body() body: LoginDto, @Req() request: SessionRequest, @Res({ passthrough: true }) response: CookieResponse) {
return this.finishLogin(await this.auth.login(body, 'admin'), request, response);
@UsePipes(strictValidationPipe)
async adminLogin(
@Body() body: LoginDto,
@Req() request: SessionRequest,
@Res({ passthrough: true }) response: CookieResponse,
) {
let result: Awaited<ReturnType<AuthService['login']>>;
try {
result = await this.auth.login(body, 'admin', this.sourceIp(request));
} catch (error) {
await this.recordLoginFailure('admin_login_failure', body.login, request).catch(() => undefined);
throw error;
}
return this.finishLogin(result, request, response);
}
@Get('client/auth/captcha')
clientCaptcha() {
return this.auth.createCaptcha();
clientCaptcha(@Req() request: SessionRequest) {
return this.auth.createCaptcha(this.sourceIp(request));
}
@Post('client/auth/login')
async clientLogin(@Body() body: LoginDto, @Req() request: SessionRequest, @Res({ passthrough: true }) response: CookieResponse) {
return this.finishLogin(await this.auth.login(body, 'client'), request, response);
@UsePipes(strictValidationPipe)
async clientLogin(
@Body() body: LoginDto,
@Req() request: SessionRequest,
@Res({ passthrough: true }) response: CookieResponse,
) {
let result: Awaited<ReturnType<AuthService['login']>>;
try {
result = await this.auth.login(body, 'client', this.sourceIp(request));
} catch (error) {
await this.recordLoginFailure('client_login_failure', body.login, request).catch(() => undefined);
throw error;
}
return this.finishLogin(result, request, response);
}
@Get(['admin/auth/session', 'client/auth/session'])
@@ -74,22 +108,32 @@ export class AuthController {
async lock(@Req() request: SessionRequest) {
this.assertSession(request);
const record = await this.sessions.lock(request.sessionToken!);
if (record) await this.writeLog(request, 'auth.session_locked', { portal: record.portal, reason: 'client_idle_timer' });
if (record)
await this.writeLog(request, 'auth.session_locked', { portal: record.portal, reason: 'client_idle_timer' });
return { locked: Boolean(record) };
}
@Post(['admin/auth/session/unlock', 'client/auth/session/unlock'])
async unlock(@Req() request: SessionRequest, @Body('password') password: string, @Res({ passthrough: true }) response: CookieResponse) {
@UsePipes(strictValidationPipe)
async unlock(
@Req() request: SessionRequest,
@Body() body: PasswordVerificationDto,
@Res({ passthrough: true }) response: CookieResponse,
) {
const { password } = body;
this.assertSession(request);
const result = await this.auth.unlock(request.sessionToken!, request.sessionUserId!, password);
if (result.status !== 'active' || !('token' in result)) throw new UnauthorizedException({ code: 'SESSION_LOCK_TIMEOUT', message: '锁定时间过长,请重新登录' });
if (result.status !== 'active' || !('token' in result))
throw new UnauthorizedException({ code: 'SESSION_LOCK_TIMEOUT', message: '锁定时间过长,请重新登录' });
this.setCookie(response, result.record.portal, result.token);
await this.writeLog(request, 'auth.session_unlocked', { portal: result.record.portal });
return this.sessions.publicSession(result.record);
}
@Post(['admin/auth/reauthenticate', 'client/auth/reauthenticate'])
async reauthenticate(@Req() request: SessionRequest, @Body('password') password: string) {
@UsePipes(strictValidationPipe)
async reauthenticate(@Req() request: SessionRequest, @Body() body: PasswordVerificationDto) {
const { password } = body;
this.assertSession(request);
const result = await this.auth.reauthenticate(request.sessionToken!, request.sessionUserId!, password);
if (result.status !== 'active') throw new UnauthorizedException({ code: 'SESSION_LOCKED', message: '会话已锁定' });
@@ -100,30 +144,68 @@ export class AuthController {
@Post(['admin/auth/logout', 'client/auth/logout'])
async logout(@Req() request: SessionRequest, @Res({ passthrough: true }) response: CookieResponse) {
if (request.sessionToken) await this.sessions.remove(request.sessionToken);
if (request.sessionUserId) await this.writeLog(request, 'auth.session_logged_out', { portal: request.authSession?.portal });
if (request.sessionUserId)
await this.writeLog(request, 'auth.session_logged_out', { portal: request.authSession?.portal });
this.clearCookie(response, request.authSession?.portal);
return { success: true };
}
@Post(['admin/auth/password', 'client/auth/password'])
changeOwnPassword(@CurrentSessionUserId() userId: string | undefined, @Body() body: { currentPassword?: string; password?: string }) {
@UsePipes(strictValidationPipe)
changeOwnPassword(@CurrentSessionUserId() userId: string | undefined, @Body() body: ChangeOwnPasswordDto) {
if (!userId) throw new UnauthorizedException('登录会话无效,请重新登录');
return this.users.changeOwnPassword(userId, body.currentPassword ?? '', body.password ?? '');
return this.users.changeOwnPassword(userId, body.currentPassword, body.password);
}
private async finishLogin(result: Awaited<ReturnType<AuthService['login']>>, request: SessionRequest, response: CookieResponse) {
private async finishLogin(
result: Awaited<ReturnType<AuthService['login']>>,
request: SessionRequest,
response: CookieResponse,
) {
this.setCookie(response, result.portal, result.sessionToken);
this.clearLegacyCookie(response);
await this.prisma.operationLog.create({
data: { userId: result.user.id, tenantId: result.user.tenantId, action: 'auth.session_created', resource: 'auth_session', userAgent: request.header('user-agent'), detail: { portal: result.portal } },
data: {
userId: result.user.id,
tenantId: result.user.tenantId,
action: 'auth.session_created',
resource: 'auth_session',
userAgent: request.header('user-agent'),
detail: { portal: result.portal },
},
});
const { sessionToken: _, ...publicResult } = result;
return publicResult;
}
private recordLoginFailure(
ruleCode: 'admin_login_failure' | 'client_login_failure',
account: string,
request: SessionRequest,
) {
return this.security.recordEvent({
ruleCode,
sourceIp: requestContext.getStore()?.ipAddress ?? '127.0.0.1',
account,
protocol: 'http',
path: ruleCode === 'admin_login_failure' ? '/admin/auth/login' : '/client/auth/login',
evidence: { userAgent: request.header('user-agent')?.slice(0, 256) },
});
}
private sourceIp(request: SessionRequest) {
return requestContext.getStore()?.ipAddress ?? '127.0.0.1';
}
private writeLog(request: SessionRequest, action: string, detail: Record<string, unknown>) {
return this.prisma.operationLog.create({
data: { userId: request.sessionUserId, action, resource: 'auth_session', userAgent: request.header('user-agent'), detail: JSON.parse(JSON.stringify(detail)) as Prisma.InputJsonValue },
data: {
userId: request.sessionUserId,
action,
resource: 'auth_session',
userAgent: request.header('user-agent'),
detail: JSON.parse(JSON.stringify(detail)) as Prisma.InputJsonValue,
},
});
}
+17
View File
@@ -0,0 +1,17 @@
import { IsString, MaxLength, MinLength } from 'class-validator';
export class LoginDto {
@IsString() @MinLength(1) @MaxLength(200) login!: string;
@IsString() @MinLength(1) @MaxLength(256) password!: string;
@IsString() @MinLength(1) @MaxLength(64) captchaId!: string;
@IsString() @MinLength(1) @MaxLength(32) captchaText!: string;
}
export class PasswordVerificationDto {
@IsString() @MinLength(1) @MaxLength(256) password!: string;
}
export class ChangeOwnPasswordDto {
@IsString() @MinLength(1) @MaxLength(256) currentPassword!: string;
@IsString() @MinLength(8) @MaxLength(256) password!: string;
}
+2 -1
View File
@@ -5,9 +5,10 @@ import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { RecentAuthenticationGuard } from './recent-authentication.guard';
import { SessionService } from './session.service';
import { SecurityDetectionModule } from '../security-detection/security-detection.module';
@Module({
imports: [UsersModule],
imports: [UsersModule, SecurityDetectionModule],
controllers: [AuthController],
providers: [
AuthService,
+126 -17
View File
@@ -1,6 +1,6 @@
import { UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { hashPassword } from '../users/users.service';
import { legacyHashPassword } from './password-hasher';
function createUsersMock(roleCode: string, overrides: Record<string, unknown> = {}) {
const user = {
@@ -10,7 +10,7 @@ function createUsersMock(roleCode: string, overrides: Record<string, unknown> =
email: 'user@example.com',
phone: '13800000000',
displayName: '用户',
passwordHash: hashPassword('secret1'),
passwordHash: legacyHashPassword('secret1'),
status: 'active',
deletedAt: null,
lockedUntil: null,
@@ -20,56 +20,165 @@ function createUsersMock(roleCode: string, overrides: Record<string, unknown> =
};
return {
findByLogin: jest.fn().mockResolvedValue(user),
verifyLoginPassword: jest.fn(async (_id: string, password: string) => password === 'secret1'),
recordLoginSuccess: jest.fn(),
recordLoginFailure: jest.fn(),
verifyCurrentPassword: jest.fn(),
};
}
function createSessionsMock() {
const captchas = new Map<string, string>();
const failures = new Map<string, number>();
const record = {
userId: 'user-1', portal: 'admin', sessionVersion: 0, createdAt: 1, lastActivityAt: 1,
lastAuthenticatedAt: 1, absoluteExpiresAt: Date.now() + 1000,
userId: 'user-1',
portal: 'admin',
sessionVersion: 0,
createdAt: 1,
lastActivityAt: 1,
lastAuthenticatedAt: 1,
absoluteExpiresAt: Date.now() + 1000,
};
return {
storeCaptcha: jest.fn(async (id: string, answer: string) => {
captchas.set(id, answer);
}),
consumeCaptcha: jest.fn(async (id: string) => {
const answer = captchas.get(id) ?? null;
captchas.delete(id);
return answer;
}),
assertCaptchaRequestAllowed: jest.fn().mockResolvedValue(true),
anonymousLoginLockScope: jest.fn(async (login: string) => ((failures.get(login) ?? 0) >= 5 ? 'account' : null)),
recordAnonymousLoginFailure: jest.fn(async (login: string) => {
const count = (failures.get(login) ?? 0) + 1;
failures.set(login, count);
return [count, count, count];
}),
clearAnonymousLoginFailures: jest.fn(async (login: string) => {
failures.delete(login);
}),
create: jest.fn().mockResolvedValue({ token: 'opaque-session-token', record }),
publicSession: jest.fn().mockReturnValue({ idleTimeoutSeconds: 3600, absoluteExpiresAt: new Date(record.absoluteExpiresAt).toISOString() }),
publicSession: jest
.fn()
.mockReturnValue({
idleTimeoutSeconds: 3600,
absoluteExpiresAt: new Date(record.absoluteExpiresAt).toISOString(),
}),
unlock: jest.fn().mockResolvedValue({ status: 'active' }),
markReauthenticated: jest.fn().mockResolvedValue({ status: 'active' }),
};
}
function createMetricsMock() {
return { recordAuthProtectionResult: jest.fn() };
}
async function loginWithCaptcha(service: AuthService, portal: 'admin' | 'client', password = 'secret1') {
const captcha = service.createCaptcha();
const answer = captcha.challenge.split('=')[0].split('+').map((part) => Number(part.trim())).reduce((sum, value) => sum + value, 0);
return service.login({
login: 'user@example.com',
password,
captchaId: captcha.captchaId,
captchaText: String(answer),
}, portal);
const captcha = await service.createCaptcha('203.0.113.10');
const answer = captcha.challenge
.split('=')[0]
.split('+')
.map((part) => Number(part.trim()))
.reduce((sum, value) => sum + value, 0);
return service.login(
{
login: 'user@example.com',
password,
captchaId: captcha.captchaId,
captchaText: String(answer),
},
portal,
'203.0.113.10',
);
}
describe('AuthService', () => {
it('allows platform admins to login admin portal', async () => {
const users = createUsersMock('platform_admin');
const sessions = createSessionsMock();
const service = new AuthService(users as never, sessions as never);
await expect(loginWithCaptcha(service, 'admin')).resolves.toEqual(expect.objectContaining({ portal: 'admin', sessionToken: 'opaque-session-token' }));
const service = new AuthService(users as never, sessions as never, createMetricsMock() as never);
await expect(loginWithCaptcha(service, 'admin')).resolves.toEqual(
expect.objectContaining({ portal: 'admin', sessionToken: 'opaque-session-token' }),
);
expect(users.recordLoginSuccess).toHaveBeenCalledWith('user-1');
expect(sessions.create).toHaveBeenCalledWith('user-1', 'admin', 0);
});
it('rejects enterprise admins on admin portal', async () => {
const users = createUsersMock('enterprise_admin');
const service = new AuthService(users as never, createSessionsMock() as never);
const service = new AuthService(users as never, createSessionsMock() as never, createMetricsMock() as never);
await expect(loginWithCaptcha(service, 'admin')).rejects.toBeInstanceOf(UnauthorizedException);
expect(users.recordLoginFailure).toHaveBeenCalledWith('user-1');
});
it('locks user after five failed password attempts', async () => {
const users = createUsersMock('platform_admin');
const service = new AuthService(users as never, createSessionsMock() as never);
const service = new AuthService(users as never, createSessionsMock() as never, createMetricsMock() as never);
for (let index = 0; index < 5; index += 1) {
await expect(loginWithCaptcha(service, 'admin', 'bad-password')).rejects.toBeInstanceOf(UnauthorizedException);
}
expect(users.recordLoginFailure).toHaveBeenCalledTimes(5);
});
it('rejects captcha bursts before allocating a captcha', async () => {
const sessions = createSessionsMock();
sessions.assertCaptchaRequestAllowed.mockResolvedValue(false);
const metrics = createMetricsMock();
const service = new AuthService(createUsersMock('platform_admin') as never, sessions as never, metrics as never);
await expect(service.createCaptcha('203.0.113.10')).rejects.toMatchObject({ status: 429 });
expect(sessions.storeCaptcha).not.toHaveBeenCalled();
expect(metrics.recordAuthProtectionResult).toHaveBeenCalledWith('captcha_rejected');
});
it('allows a tenant-bound enterprise admin to login to the client portal', async () => {
const service = new AuthService(
createUsersMock('enterprise_admin') as never,
createSessionsMock() as never,
createMetricsMock() as never,
);
await expect(loginWithCaptcha(service, 'client')).resolves.toEqual(expect.objectContaining({ portal: 'client' }));
});
it('records anonymous failures without disclosing whether an account exists', async () => {
const users = createUsersMock('platform_admin');
users.findByLogin.mockResolvedValue(null);
const sessions = createSessionsMock();
const service = new AuthService(users as never, sessions as never, createMetricsMock() as never);
await expect(loginWithCaptcha(service, 'admin')).rejects.toBeInstanceOf(UnauthorizedException);
expect(sessions.recordAnonymousLoginFailure).toHaveBeenCalledWith('user@example.com', '203.0.113.10');
});
it('rejects expired and incorrect one-time captchas', async () => {
const sessions = createSessionsMock();
const service = new AuthService(
createUsersMock('platform_admin') as never,
sessions as never,
createMetricsMock() as never,
);
await expect(
service.login(
{ login: 'user', password: 'secret1', captchaId: 'missing', captchaText: '1' },
'admin',
'203.0.113.10',
),
).rejects.toMatchObject({ status: 400 });
await sessions.storeCaptcha('captcha-wrong', '7');
await expect(
service.login(
{ login: 'user', password: 'secret1', captchaId: 'captcha-wrong', captchaText: '8' },
'admin',
'203.0.113.10',
),
).rejects.toMatchObject({ status: 400 });
});
it('delegates unlock and recent reauthentication to password and session services', async () => {
const users = createUsersMock('platform_admin');
const sessions = createSessionsMock();
const service = new AuthService(users as never, sessions as never, createMetricsMock() as never);
await expect(service.unlock('token', 'user-1', 'secret1')).resolves.toEqual({ status: 'active' });
await expect(service.reauthenticate('token', 'user-1', 'secret1')).resolves.toEqual({ status: 'active' });
expect(users.verifyCurrentPassword).toHaveBeenCalledTimes(2);
});
});
+40 -47
View File
@@ -1,37 +1,30 @@
import { randomUUID } from 'node:crypto';
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import { hashPassword, UsersService } from '../users/users.service';
import { BadRequestException, HttpException, HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import type { LoginDto } from './auth.dto';
import { SessionService } from './session.service';
export interface LoginDto {
login: string;
password: string;
captchaId: string;
captchaText: string;
}
import { MetricsService } from '../metrics/metrics.service';
type LoginPortal = 'admin' | 'client';
type CaptchaRecord = {
answer: string;
expiresAt: number;
};
const captchaStore = new Map<string, CaptchaRecord>();
const anonymousFailures = new Map<string, { count: number; lockedUntil?: number }>();
@Injectable()
export class AuthService {
constructor(private readonly users: UsersService, private readonly sessions: SessionService) {}
constructor(
private readonly users: UsersService,
private readonly sessions: SessionService,
private readonly metrics: MetricsService,
) {}
createCaptcha() {
async createCaptcha(sourceIp: string) {
if (!(await this.sessions.assertCaptchaRequestAllowed(sourceIp))) {
this.metrics.recordAuthProtectionResult('captcha_rejected');
throw new HttpException('验证码请求过于频繁,请稍后再试', HttpStatus.TOO_MANY_REQUESTS);
}
this.metrics.recordAuthProtectionResult('captcha_allowed');
const left = Math.floor(10 + Math.random() * 40);
const right = Math.floor(1 + Math.random() * 9);
const captchaId = randomUUID();
captchaStore.set(captchaId, {
answer: String(left + right),
expiresAt: Date.now() + 5 * 60 * 1000,
});
await this.sessions.storeCaptcha(captchaId, String(left + right), 5 * 60);
return {
captchaId,
challenge: `${left} + ${right} = ?`,
@@ -39,43 +32,48 @@ export class AuthService {
};
}
async login(data: LoginDto, portal: LoginPortal) {
async login(data: LoginDto, portal: LoginPortal, sourceIp: string) {
const login = data.login?.trim();
if (!login || !data.password) {
throw new BadRequestException('login and password are required');
}
this.verifyCaptcha(data.captchaId, data.captchaText);
this.assertAnonymousNotLocked(login);
await this.verifyCaptcha(data.captchaId, data.captchaText);
await this.assertAnonymousNotLocked(login, sourceIp);
const user = await this.users.findByLogin(login);
if (!user) {
this.recordAnonymousFailure(login);
await this.sessions.recordAnonymousLoginFailure(login, sourceIp);
throw new UnauthorizedException('Invalid login or password');
}
if (user.lockedUntil && user.lockedUntil.getTime() > Date.now()) {
await this.sessions.recordAnonymousLoginFailure(login, sourceIp);
throw new UnauthorizedException('User is locked for 24 hours after repeated failures');
}
if (user.status !== 'active' || user.deletedAt) {
await this.sessions.recordAnonymousLoginFailure(login, sourceIp);
await this.users.recordLoginFailure(user.id);
throw new UnauthorizedException('User is disabled or deleted');
}
if (user.passwordHash !== hashPassword(data.password)) {
if (!(await this.users.verifyLoginPassword(user.id, data.password, user.passwordHash))) {
await this.sessions.recordAnonymousLoginFailure(login, sourceIp);
await this.users.recordLoginFailure(user.id);
throw new UnauthorizedException('Invalid login or password');
}
const roleCodes = user.roles.map((item) => item.role.code);
if (portal === 'admin' && !roleCodes.includes('platform_admin')) {
await this.sessions.recordAnonymousLoginFailure(login, sourceIp);
await this.users.recordLoginFailure(user.id);
throw new UnauthorizedException('Only platform admins can login to admin portal');
}
if (portal === 'client' && (!roleCodes.includes('enterprise_admin') || !user.tenantId)) {
await this.sessions.recordAnonymousLoginFailure(login, sourceIp);
await this.users.recordLoginFailure(user.id);
throw new UnauthorizedException('Only enterprise admins linked to a tenant can login to client portal');
}
await this.users.recordLoginSuccess(user.id);
anonymousFailures.delete(login);
await this.sessions.clearAnonymousLoginFailures(login, sourceIp);
const { token, record } = await this.sessions.create(user.id, portal, user.sessionVersion ?? 0);
return {
@@ -105,30 +103,25 @@ export class AuthService {
return this.sessions.markReauthenticated(token);
}
private verifyCaptcha(captchaId?: string, captchaText?: string) {
const record = captchaId ? captchaStore.get(captchaId) : undefined;
captchaStore.delete(captchaId ?? '');
if (!record || record.expiresAt < Date.now()) {
private async verifyCaptcha(captchaId?: string, captchaText?: string) {
const answer = captchaId ? await this.sessions.consumeCaptcha(captchaId) : null;
if (!answer) {
throw new BadRequestException('Captcha expired, refresh and try again');
}
if (record.answer !== captchaText?.trim()) {
if (answer !== captchaText?.trim()) {
throw new BadRequestException('Captcha is incorrect');
}
}
private assertAnonymousNotLocked(login: string) {
const current = anonymousFailures.get(login);
if (current?.lockedUntil && current.lockedUntil > Date.now()) {
throw new UnauthorizedException('User is locked for 24 hours after repeated failures');
private async assertAnonymousNotLocked(login: string, sourceIp: string) {
const scope = await this.sessions.anonymousLoginLockScope(login, sourceIp);
if (scope) {
this.metrics.recordAuthProtectionResult('login_locked', scope);
throw new UnauthorizedException(
scope === 'account'
? 'User is locked for 24 hours after repeated failures'
: 'Too many login attempts from this source, try again later',
);
}
}
private recordAnonymousFailure(login: string) {
const current = anonymousFailures.get(login) ?? { count: 0 };
const count = current.count + 1;
anonymousFailures.set(login, {
count,
lockedUntil: count >= 5 ? Date.now() + 24 * 60 * 60 * 1000 : current.lockedUntil,
});
}
}
@@ -0,0 +1,14 @@
import { ForbiddenException, createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { SessionRequest } from './session-validation.middleware';
/**
* Returns the tenant bound to the authenticated client session.
* Request headers, query parameters and request bodies must never determine this value.
*/
export const CurrentTenantId = createParamDecorator((_: unknown, context: ExecutionContext) => {
const request = context.switchToHttp().getRequest<SessionRequest>();
if (request.authSession?.portal !== 'client' || !request.sessionTenantId) {
throw new ForbiddenException({ code: 'CLIENT_TENANT_REQUIRED', message: '缺少可信企业上下文' });
}
return request.sessionTenantId;
});
+46
View File
@@ -0,0 +1,46 @@
import { hashPassword, isLegacySha256, legacyHashPassword, passwordNeedsRehash, verifyPassword } from './password-hasher';
describe('password hasher', () => {
const originalTransition = process.env.PASSWORD_HASH_LEGACY_TRANSITION;
const originalUntil = process.env.PASSWORD_HASH_LEGACY_WRITE_UNTIL;
afterEach(() => {
if (originalTransition === undefined) delete process.env.PASSWORD_HASH_LEGACY_TRANSITION;
else process.env.PASSWORD_HASH_LEGACY_TRANSITION = originalTransition;
if (originalUntil === undefined) delete process.env.PASSWORD_HASH_LEGACY_WRITE_UNTIL;
else process.env.PASSWORD_HASH_LEGACY_WRITE_UNTIL = originalUntil;
});
it('stores new passwords using versioned salted scrypt hashes', async () => {
const first = await hashPassword('correct horse battery staple');
const second = await hashPassword('correct horse battery staple');
expect(first).toMatch(/^\$scrypt\$v=1\$/);
expect(second).not.toBe(first);
await expect(verifyPassword('correct horse battery staple', first)).resolves.toBe(true);
await expect(verifyPassword('wrong password', first)).resolves.toBe(false);
expect(passwordNeedsRehash(first)).toBe(false);
});
it('recognizes and verifies legacy SHA-256 hashes for transparent migration', async () => {
const legacy = legacyHashPassword('legacy-password');
expect(isLegacySha256(legacy)).toBe(true);
expect(passwordNeedsRehash(legacy)).toBe(true);
await expect(verifyPassword('legacy-password', legacy)).resolves.toBe(true);
await expect(verifyPassword('wrong-password', legacy)).resolves.toBe(false);
});
it('rejects malformed or excessive scrypt parameters', async () => {
await expect(verifyPassword('password', '$scrypt$v=1$N=1048576,r=8,p=1$YWJjZGVmZ2hpamtsbW5vcA$YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU')).resolves.toBe(false);
});
it('supports only a bounded legacy-write window for the first compatibility rollout', async () => {
process.env.PASSWORD_HASH_LEGACY_TRANSITION = 'true';
process.env.PASSWORD_HASH_LEGACY_WRITE_UNTIL = new Date(Date.now() + 30 * 60 * 1000).toISOString();
await expect(hashPassword('transition-password')).resolves.toBe(legacyHashPassword('transition-password'));
process.env.PASSWORD_HASH_LEGACY_WRITE_UNTIL = new Date(Date.now() + 3 * 60 * 60 * 1000).toISOString();
await expect(hashPassword('strong-password')).resolves.toMatch(/^\$scrypt\$/);
});
});
+87
View File
@@ -0,0 +1,87 @@
import { createHash, randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'node:crypto';
const VERSION = 1;
const KEY_LENGTH = 32;
const DEFAULT_N = 32768;
const DEFAULT_R = 8;
const DEFAULT_P = 1;
const MAX_MEMORY = 64 * 1024 * 1024;
const MAX_LEGACY_WRITE_WINDOW_MS = 2 * 60 * 60 * 1000;
const LEGACY_SHA256 = /^[a-f0-9]{64}$/i;
export async function hashPassword(password: string) {
if (legacyTransitionWriteEnabled()) return legacyHashPassword(password);
const salt = randomBytes(16);
const derived = await deriveScrypt(password, salt, KEY_LENGTH, {
N: DEFAULT_N,
r: DEFAULT_R,
p: DEFAULT_P,
maxmem: MAX_MEMORY,
});
return `$scrypt$v=${VERSION}$N=${DEFAULT_N},r=${DEFAULT_R},p=${DEFAULT_P}$${salt.toString('base64url')}$${derived.toString('base64url')}`;
}
function legacyTransitionWriteEnabled() {
if (process.env.PASSWORD_HASH_LEGACY_TRANSITION !== 'true') return false;
const until = Date.parse(process.env.PASSWORD_HASH_LEGACY_WRITE_UNTIL ?? '');
const remaining = until - Date.now();
return Number.isFinite(until) && remaining > 0 && remaining <= MAX_LEGACY_WRITE_WINDOW_MS;
}
export async function verifyPassword(password: string, encoded: string) {
if (isLegacySha256(encoded)) {
const candidate = Buffer.from(legacyHashPassword(password), 'hex');
const expected = Buffer.from(encoded, 'hex');
return candidate.length === expected.length && timingSafeEqual(candidate, expected);
}
const parsed = parseScryptHash(encoded);
if (!parsed) return false;
const derived = await deriveScrypt(password, parsed.salt, parsed.hash.length, {
N: parsed.N,
r: parsed.r,
p: parsed.p,
maxmem: MAX_MEMORY,
});
return derived.length === parsed.hash.length && timingSafeEqual(derived, parsed.hash);
}
export function passwordNeedsRehash(encoded: string) {
if (isLegacySha256(encoded)) return true;
const parsed = parseScryptHash(encoded);
return !parsed || parsed.version !== VERSION || parsed.N !== DEFAULT_N || parsed.r !== DEFAULT_R || parsed.p !== DEFAULT_P;
}
export function isLegacySha256(encoded: string) {
return LEGACY_SHA256.test(encoded);
}
export function legacyHashPassword(password: string) {
return createHash('sha256').update(password).digest('hex');
}
function parseScryptHash(encoded: string) {
const match = /^\$scrypt\$v=(\d+)\$N=(\d+),r=(\d+),p=(\d+)\$([A-Za-z0-9_-]+)\$([A-Za-z0-9_-]+)$/.exec(encoded);
if (!match) return undefined;
const [, version, N, r, p, salt, hash] = match;
const params = { version: Number(version), N: Number(N), r: Number(r), p: Number(p) };
if (!Number.isInteger(params.N) || params.N < 2 || params.N > DEFAULT_N
|| !Number.isInteger(params.r) || params.r < 1 || params.r > DEFAULT_R
|| !Number.isInteger(params.p) || params.p < 1 || params.p > DEFAULT_P) return undefined;
try {
const decodedSalt = Buffer.from(salt, 'base64url');
const decodedHash = Buffer.from(hash, 'base64url');
if (decodedSalt.length < 16 || decodedHash.length !== KEY_LENGTH) return undefined;
return { ...params, salt: decodedSalt, hash: decodedHash };
} catch {
return undefined;
}
}
function deriveScrypt(password: string, salt: Buffer, keyLength: number, options: { N: number; r: number; p: number; maxmem: number }) {
return new Promise<Buffer>((resolve, reject) => {
scryptCallback(password, salt, keyLength, options, (error, derivedKey) => {
if (error) reject(error);
else resolve(derivedKey);
});
});
}
@@ -1,4 +1,4 @@
import { UnauthorizedException } from '@nestjs/common';
import { ForbiddenException, UnauthorizedException } from '@nestjs/common';
import { SessionValidationMiddleware, type SessionRequest } from './session-validation.middleware';
const record = {
@@ -6,10 +6,10 @@ const record = {
lastActivityAt: 1, lastAuthenticatedAt: 1, absoluteExpiresAt: Date.now() + 1000,
};
function request(path = '/api/admin/users', cookie = 'cmpp_admin_session=opaque-token'): SessionRequest {
function request(path = '/api/admin/users', cookie = 'cmpp_admin_session=opaque-token', tenantId?: string): SessionRequest {
return {
originalUrl: path,
header: jest.fn((name: string) => name === 'cookie' ? cookie : undefined),
header: jest.fn((name: string) => name === 'cookie' ? cookie : name === 'x-tenant-id' ? tenantId : undefined),
};
}
@@ -17,7 +17,7 @@ describe('SessionValidationMiddleware', () => {
const cookieName = jest.fn((portal: 'admin' | 'client') => `cmpp_${portal}_session`);
it('accepts an active Redis session and exposes its user and record', async () => {
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', status: 'active', deletedAt: null, sessionVersion: 3 }) } };
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: null, status: 'active', deletedAt: null, sessionVersion: 3 }) } };
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record }), remove: jest.fn() };
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
const currentRequest = request();
@@ -32,7 +32,7 @@ describe('SessionValidationMiddleware', () => {
});
it('rejects a session after the user session version changes', async () => {
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', status: 'active', deletedAt: null, sessionVersion: 4 }) } };
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: null, status: 'active', deletedAt: null, sessionVersion: 4 }) } };
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record }), remove: jest.fn() };
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
@@ -41,7 +41,7 @@ describe('SessionValidationMiddleware', () => {
});
it('only lets a locked session reach unlock and logout endpoints', async () => {
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', status: 'active', deletedAt: null, sessionVersion: 3 }) } };
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: null, status: 'active', deletedAt: null, sessionVersion: 3 }) } };
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'locked', record }), remove: jest.fn() };
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
@@ -53,7 +53,7 @@ describe('SessionValidationMiddleware', () => {
it('selects only the cookie belonging to the requested portal', async () => {
const clientRecord = { ...record, portal: 'client' as const };
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', status: 'active', deletedAt: null, sessionVersion: 3 }) } };
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: 'tenant-a', status: 'active', deletedAt: null, sessionVersion: 3 }) } };
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record: clientRecord }), remove: jest.fn() };
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
const currentRequest = request('/api/client/users', 'cmpp_admin_session=admin-token; cmpp_client_session=client-token');
@@ -62,6 +62,33 @@ describe('SessionValidationMiddleware', () => {
expect(sessions.validate).toHaveBeenCalledWith('client-token', false);
expect(currentRequest.sessionToken).toBe('client-token');
expect(currentRequest.sessionTenantId).toBe('tenant-a');
});
it('rejects a client session whose user is not bound to a tenant', async () => {
const clientRecord = { ...record, portal: 'client' as const };
const prisma = { user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: null, status: 'active', deletedAt: null, sessionVersion: 3 }) } };
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record: clientRecord }), remove: jest.fn() };
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
await expect(middleware.use(request('/api/client/users', 'cmpp_client_session=client-token'), {}, jest.fn()))
.rejects.toBeInstanceOf(ForbiddenException);
});
it('rejects and audits a client tenant header that disagrees with the authenticated user', async () => {
const clientRecord = { ...record, portal: 'client' as const };
const prisma = {
user: { findUnique: jest.fn().mockResolvedValue({ id: 'user-1', tenantId: 'tenant-a', status: 'active', deletedAt: null, sessionVersion: 3 }) },
operationLog: { create: jest.fn().mockResolvedValue({ id: 'log-1' }) },
};
const sessions = { cookieName, validate: jest.fn().mockResolvedValue({ status: 'active', record: clientRecord }), remove: jest.fn() };
const middleware = new SessionValidationMiddleware(prisma as never, sessions as never);
await expect(middleware.use(request('/api/client/users', 'cmpp_client_session=client-token', 'tenant-b'), {}, jest.fn()))
.rejects.toMatchObject({ response: expect.objectContaining({ code: 'CLIENT_TENANT_MISMATCH' }) });
expect(prisma.operationLog.create).toHaveBeenCalledWith({
data: expect.objectContaining({ tenantId: 'tenant-a', userId: 'user-1', action: 'security.client_tenant_mismatch' }),
});
});
it('does not accept an admin cookie for a client route', async () => {
+22 -2
View File
@@ -1,4 +1,4 @@
import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import { ForbiddenException, Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuthSessionRecord, SessionPortal, SessionService } from './session.service';
@@ -8,6 +8,7 @@ export type SessionRequest = {
url?: string;
sessionUserId?: string;
sessionToken?: string;
sessionTenantId?: string;
authSession?: AuthSessionRecord;
};
@@ -38,7 +39,7 @@ export class SessionValidationMiddleware implements NestMiddleware {
const user = await this.prisma.user.findUnique({
where: { id: result.record.userId },
select: { id: true, status: true, deletedAt: true, sessionVersion: true },
select: { id: true, tenantId: true, status: true, deletedAt: true, sessionVersion: true },
});
if (!user || user.status !== 'active' || user.deletedAt || user.sessionVersion !== result.record.sessionVersion) {
await this.sessions.remove(token);
@@ -51,6 +52,25 @@ export class SessionValidationMiddleware implements NestMiddleware {
request.sessionUserId = user.id;
request.sessionToken = token;
request.authSession = result.record;
if (portal === 'client') {
if (!user.tenantId) {
throw new ForbiddenException({ code: 'CLIENT_TENANT_REQUIRED', message: '当前客户端账号未关联企业' });
}
const suppliedTenantId = request.header('x-tenant-id')?.trim();
if (suppliedTenantId && suppliedTenantId !== user.tenantId) {
await this.prisma.operationLog.create({
data: {
tenantId: user.tenantId,
userId: user.id,
action: 'security.client_tenant_mismatch',
resource: 'auth_session',
detail: { suppliedTenantId },
},
});
throw new ForbiddenException({ code: 'CLIENT_TENANT_MISMATCH', message: '请求企业与登录企业不一致' });
}
request.sessionTenantId = user.tenantId;
}
const isSessionRecoveryRoute = /\/auth\/(?:session(?:\/unlock)?|logout)(?:\?|$)/.test(path);
if (result.status === 'locked' && !isSessionRecoveryRoute) {
if (result.newlyLocked) {
+122 -6
View File
@@ -1,14 +1,43 @@
const values = new Map<string, string>();
const redis = {
get: jest.fn((key: string) => Promise.resolve(values.get(key) ?? null)),
set: jest.fn((key: string, value: string) => { values.set(key, value); return Promise.resolve('OK'); }),
del: jest.fn((key: string) => { values.delete(key); return Promise.resolve(1); }),
getdel: jest.fn((key: string) => {
const value = values.get(key) ?? null;
values.delete(key);
return Promise.resolve(value);
}),
mget: jest.fn((...keys: string[]) => Promise.resolve(keys.map((key) => values.get(key) ?? null))),
set: jest.fn((key: string, value: string) => {
values.set(key, value);
return Promise.resolve('OK');
}),
del: jest.fn((...keys: string[]) => {
keys.forEach((key) => values.delete(key));
return Promise.resolve(keys.length);
}),
eval: jest.fn((_script: string, keyCount: number, ...parts: Array<string | number>) => {
const keys = parts.slice(0, keyCount).map(String);
const args = parts.slice(keyCount).map(Number);
if (keyCount === 1) {
const count = Number(values.get(keys[0]) ?? 0) + 1;
values.set(keys[0], String(count));
return Promise.resolve(count);
}
const counts = keys.slice(0, 3).map((key, index) => {
const count = Number(values.get(key) ?? 0) + 1;
values.set(key, String(count));
if (count >= args[index + 3]) values.set(keys[index + 3], '1');
return count;
});
return Promise.resolve(counts);
}),
disconnect: jest.fn(),
};
jest.mock('ioredis', () => jest.fn(() => redis));
import { SessionService } from './session.service';
import { ServiceUnavailableException } from '@nestjs/common';
describe('SessionService', () => {
let now = 1_700_000_000_000;
@@ -47,7 +76,9 @@ describe('SessionService', () => {
const service = new SessionService();
const created = await service.create('user-1', 'client', 2);
now += 90 * 60 * 1000;
await expect(service.validate(created.token, false)).resolves.toEqual(expect.objectContaining({ status: 'active' }));
await expect(service.validate(created.token, false)).resolves.toEqual(
expect.objectContaining({ status: 'active' }),
);
});
it('requires a full login after a session stays locked for four hours', async () => {
@@ -55,7 +86,10 @@ describe('SessionService', () => {
const created = await service.create('user-1', 'admin', 2);
await service.lock(created.token);
now += 4 * 60 * 60 * 1000 + 1;
await expect(service.validate(created.token, false)).resolves.toEqual({ status: 'expired', code: 'SESSION_LOCK_TIMEOUT' });
await expect(service.validate(created.token, false)).resolves.toEqual({
status: 'expired',
code: 'SESSION_LOCK_TIMEOUT',
});
});
it('rotates the opaque token when a password unlock succeeds', async () => {
@@ -66,8 +100,13 @@ describe('SessionService', () => {
expect(result.status).toBe('active');
if (result.status === 'active' && 'token' in result) {
expect(result.token).not.toBe(created.token);
await expect(service.validate(created.token, false)).resolves.toEqual({ status: 'expired', code: 'SESSION_INVALID' });
await expect(service.validate(result.token, false)).resolves.toEqual(expect.objectContaining({ status: 'active' }));
await expect(service.validate(created.token, false)).resolves.toEqual({
status: 'expired',
code: 'SESSION_INVALID',
});
await expect(service.validate(result.token, false)).resolves.toEqual(
expect.objectContaining({ status: 'active' }),
);
}
});
@@ -78,4 +117,81 @@ describe('SessionService', () => {
expect(service.cookieName('client')).toBe('cmpp_client_session');
delete process.env.SESSION_COOKIE_SECURE;
});
it('stores and consumes a captcha exactly once', async () => {
const service = new SessionService();
await service.storeCaptcha('captcha-1', '9', 300);
await expect(service.consumeCaptcha('captcha-1')).resolves.toBe('9');
await expect(service.consumeCaptcha('captcha-1')).resolves.toBeNull();
});
it('expires an absolute session and supports touch plus recent authentication', async () => {
const service = new SessionService();
const expired = await service.create('expired-user', 'admin', 1);
now += 12 * 60 * 60 * 1000 + 1;
await expect(service.validate(expired.token, false)).resolves.toEqual({
status: 'expired',
code: 'SESSION_ABSOLUTE_TIMEOUT',
});
now = 1_700_000_000_000;
const active = await service.create('active-user', 'client', 1);
now += 31_000;
const touched = await service.touch(active.token);
expect(touched.status).toBe('active');
const reauthenticated = await service.markReauthenticated(active.token);
expect(reauthenticated.status).toBe('active');
if (reauthenticated.status === 'active') {
expect(service.isRecentlyAuthenticated(reauthenticated.record)).toBe(true);
expect(service.publicSession(reauthenticated.record)).toEqual(
expect.objectContaining({ idleTimeoutSeconds: 7200 }),
);
}
});
it('uses host-prefixed cookie names when secure cookies are enabled', () => {
process.env.SESSION_COOKIE_SECURE = 'true';
const service = new SessionService();
expect(service.cookieName('admin')).toBe('__Host-cmpp_admin_session');
expect(service.cookieName('client')).toBe('__Host-cmpp_client_session');
delete process.env.SESSION_COOKIE_SECURE;
});
it('rate limits captcha allocation by hashed source IP', async () => {
const service = new SessionService();
for (let index = 0; index < 30; index += 1) {
await expect(service.assertCaptchaRequestAllowed('203.0.113.10')).resolves.toBe(true);
}
await expect(service.assertCaptchaRequestAllowed('203.0.113.10')).resolves.toBe(false);
expect([...values.keys()].some((key) => key.includes('203.0.113.10'))).toBe(false);
});
it('locks anonymous failures independently by account, IP and account-IP pair', async () => {
const service = new SessionService();
for (let index = 0; index < 5; index += 1) {
await service.recordAnonymousLoginFailure('user@example.com', '203.0.113.10');
}
await expect(service.anonymousLoginLockScope('user@example.com', '198.51.100.7')).resolves.toBe('account');
await expect(service.anonymousLoginLockScope('other@example.com', '203.0.113.10')).resolves.toBeNull();
await service.clearAnonymousLoginFailures('user@example.com', '203.0.113.10');
await expect(service.anonymousLoginLockScope('user@example.com', '203.0.113.10')).resolves.toBeNull();
});
it('fails closed when Redis cannot enforce captcha or login protection', async () => {
const service = new SessionService();
redis.eval.mockRejectedValueOnce(new Error('redis unavailable'));
await expect(service.assertCaptchaRequestAllowed('203.0.113.20')).rejects.toBeInstanceOf(
ServiceUnavailableException,
);
redis.mget.mockRejectedValueOnce(new Error('redis unavailable'));
await expect(service.anonymousLoginLockScope('user@example.com', '203.0.113.20')).rejects.toBeInstanceOf(
ServiceUnavailableException,
);
redis.eval.mockRejectedValueOnce(new Error('redis unavailable'));
await expect(service.recordAnonymousLoginFailure('user@example.com', '203.0.113.20')).rejects.toBeInstanceOf(
ServiceUnavailableException,
);
});
});
+123 -2
View File
@@ -21,6 +21,14 @@ export type SessionValidationResult =
| { status: 'expired'; code: 'SESSION_INVALID' | 'SESSION_ABSOLUTE_TIMEOUT' | 'SESSION_LOCK_TIMEOUT' };
const SESSION_PREFIX = 'cmpp:auth:session:';
const CAPTCHA_PREFIX = 'cmpp:auth:captcha:';
const CAPTCHA_RATE_PREFIX = 'cmpp:auth:captcha-rate:ip:';
const ANONYMOUS_FAILURE_PREFIX = 'cmpp:auth:failure:';
const ANONYMOUS_LOCK_PREFIX = 'cmpp:auth:lock:';
const ANONYMOUS_IP_FAILURE_PREFIX = 'cmpp:auth:failure:ip:';
const ANONYMOUS_IP_LOCK_PREFIX = 'cmpp:auth:lock:ip:';
const ANONYMOUS_PAIR_FAILURE_PREFIX = 'cmpp:auth:failure:pair:';
const ANONYMOUS_PAIR_LOCK_PREFIX = 'cmpp:auth:lock:pair:';
export const SESSION_COOKIE_NAME = '__Host-cmpp_session';
export const DEVELOPMENT_SESSION_COOKIE_NAME = 'cmpp_session';
export const ADMIN_SESSION_COOKIE_NAME = '__Host-cmpp_admin_session';
@@ -123,6 +131,108 @@ export class SessionService implements OnModuleDestroy {
return this.client.del(this.key(token));
}
async storeCaptcha(captchaId: string, answer: string, ttlSeconds: number) {
try {
await this.client.set(`${CAPTCHA_PREFIX}${captchaId}`, answer, 'EX', ttlSeconds);
} catch {
throw new ServiceUnavailableException('验证码服务暂不可用');
}
}
async consumeCaptcha(captchaId: string) {
try {
return await this.client.getdel(`${CAPTCHA_PREFIX}${captchaId}`);
} catch {
throw new ServiceUnavailableException('验证码服务暂不可用');
}
}
async assertCaptchaRequestAllowed(sourceIp: string) {
const key = `${CAPTCHA_RATE_PREFIX}${this.valueDigest(sourceIp)}`;
try {
const count = Number(
await this.client.eval(
`local count = redis.call('INCR', KEYS[1])
if count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
return count`,
1,
key,
5 * 60,
),
);
return count <= 30;
} catch {
throw new ServiceUnavailableException('验证码服务暂不可用');
}
}
async anonymousLoginLockScope(login: string, sourceIp: string) {
const accountDigest = this.loginDigest(login);
const ipDigest = this.valueDigest(sourceIp);
const pairDigest = this.valueDigest(`${accountDigest}:${ipDigest}`);
try {
const locks = await this.client.mget(
`${ANONYMOUS_LOCK_PREFIX}${accountDigest}`,
`${ANONYMOUS_IP_LOCK_PREFIX}${ipDigest}`,
`${ANONYMOUS_PAIR_LOCK_PREFIX}${pairDigest}`,
);
if (locks[0]) return 'account' as const;
if (locks[1]) return 'ip' as const;
if (locks[2]) return 'pair' as const;
return null;
} catch {
throw new ServiceUnavailableException('登录保护服务暂不可用');
}
}
async recordAnonymousLoginFailure(login: string, sourceIp: string) {
const accountDigest = this.loginDigest(login);
const ipDigest = this.valueDigest(sourceIp);
const pairDigest = this.valueDigest(`${accountDigest}:${ipDigest}`);
try {
const result = await this.client.eval(
`local counts = {}
for i = 1, 3 do
counts[i] = redis.call('INCR', KEYS[i])
if counts[i] == 1 then redis.call('EXPIRE', KEYS[i], ARGV[i]) end
if counts[i] >= tonumber(ARGV[i + 3]) then redis.call('SET', KEYS[i + 3], '1', 'EX', ARGV[i]) end
end
return counts`,
6,
`${ANONYMOUS_FAILURE_PREFIX}${accountDigest}`,
`${ANONYMOUS_IP_FAILURE_PREFIX}${ipDigest}`,
`${ANONYMOUS_PAIR_FAILURE_PREFIX}${pairDigest}`,
`${ANONYMOUS_LOCK_PREFIX}${accountDigest}`,
`${ANONYMOUS_IP_LOCK_PREFIX}${ipDigest}`,
`${ANONYMOUS_PAIR_LOCK_PREFIX}${pairDigest}`,
24 * 60 * 60,
15 * 60,
24 * 60 * 60,
5,
30,
5,
);
return (result as number[]).map(Number);
} catch {
throw new ServiceUnavailableException('登录保护服务暂不可用');
}
}
async clearAnonymousLoginFailures(login: string, sourceIp: string) {
const accountDigest = this.loginDigest(login);
const pairDigest = this.valueDigest(`${accountDigest}:${this.valueDigest(sourceIp)}`);
try {
await this.client.del(
`${ANONYMOUS_FAILURE_PREFIX}${accountDigest}`,
`${ANONYMOUS_LOCK_PREFIX}${accountDigest}`,
`${ANONYMOUS_PAIR_FAILURE_PREFIX}${pairDigest}`,
`${ANONYMOUS_PAIR_LOCK_PREFIX}${pairDigest}`,
);
} catch {
throw new ServiceUnavailableException('登录保护服务暂不可用');
}
}
isRecentlyAuthenticated(record: AuthSessionRecord) {
return Date.now() - record.lastAuthenticatedAt < this.recentAuthenticationMs;
}
@@ -138,7 +248,10 @@ export class SessionService implements OnModuleDestroy {
}
get cookieSecure() {
return process.env.SESSION_COOKIE_SECURE === 'true' || (process.env.NODE_ENV === 'production' && process.env.SESSION_COOKIE_SECURE !== 'false');
return (
process.env.SESSION_COOKIE_SECURE === 'true' ||
(process.env.NODE_ENV === 'production' && process.env.SESSION_COOKIE_SECURE !== 'false')
);
}
cookieName(portal: SessionPortal) {
@@ -172,7 +285,7 @@ export class SessionService implements OnModuleDestroy {
private async read(token: string): Promise<AuthSessionRecord | null> {
try {
const value = await this.client.get(this.key(token));
return value ? JSON.parse(value) as AuthSessionRecord : null;
return value ? (JSON.parse(value) as AuthSessionRecord) : null;
} catch {
throw new ServiceUnavailableException('登录会话服务暂不可用');
}
@@ -195,6 +308,14 @@ export class SessionService implements OnModuleDestroy {
return `${SESSION_PREFIX}${createHash('sha256').update(token).digest('hex')}`;
}
private loginDigest(login: string) {
return this.valueDigest(login.trim().toLocaleLowerCase('en-US'));
}
private valueDigest(value: string) {
return createHash('sha256').update(value.trim()).digest('hex');
}
private get client() {
if (!this.redis) {
this.redis = new IORedis(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379', {
+8 -4
View File
@@ -1,6 +1,9 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { Body, Controller, Get, Param, Post, Query, UsePipes } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { TenantId } from '../common/tenant-id.decorator';
import { CurrentTenantId } from '../auth/current-tenant-id.decorator';
import { ClientBillingEstimateDto } from '../common/client-write.dto';
import { strictValidationPipe } from '../common/strict-validation.pipe';
import { RequireRecentAuthentication } from '../auth/require-recent-authentication.decorator';
import { CurrentSessionUserId } from '../auth/current-session-user.decorator';
import {
@@ -125,14 +128,15 @@ export class ClientBillingController {
constructor(private readonly billing: BillingService) {}
@Get('orders')
listRechargeOrders(@TenantId() tenantId?: string, @Query('page') page?: string, @Query('pageSize') pageSize?: string) {
listRechargeOrders(@CurrentTenantId() tenantId: string, @Query('page') page?: string, @Query('pageSize') pageSize?: string) {
return page || pageSize
? this.billing.listRechargeOrdersPage({ tenantId, page: Number(page), pageSize: Number(pageSize) })
: this.billing.listRechargeOrders(tenantId);
}
@Post('estimate')
estimateSmsCost(@Body() body: EstimateSmsCostDto) {
return this.billing.estimateSmsCost(body);
@UsePipes(strictValidationPipe)
estimateSmsCost(@CurrentTenantId() tenantId: string, @Body() body: ClientBillingEstimateDto) {
return this.billing.estimateSmsCost({ ...body, tenantId });
}
}
+43 -8
View File
@@ -7,13 +7,18 @@ function createPrismaMock() {
tenant: {
findFirst: jest.fn().mockResolvedValue({ id: 'tenant-1', name: '示例企业', code: 'TENANT-1' }),
},
user: {
findMany: jest.fn().mockResolvedValue([]),
},
tenantAccount: {
findMany: jest.fn(),
findMany: jest.fn().mockResolvedValue([]),
findUnique: jest.fn().mockImplementation(() => Promise.resolve({ ...accountState })),
findUniqueOrThrow: jest.fn().mockImplementation(() => Promise.resolve({ ...accountState })),
create: jest.fn(),
upsert: jest.fn().mockImplementation(() => Promise.resolve({ ...accountState })),
updateMany: jest.fn().mockImplementation(({ data }) => {
if (data.balanceCents?.increment !== undefined) accountState.balanceCents += data.balanceCents.increment;
else if (data.balanceCents?.decrement !== undefined) accountState.balanceCents -= data.balanceCents.decrement;
accountState.updatedAt = new Date(accountState.updatedAt.getTime() + 1);
return Promise.resolve({ count: 1 });
}),
@@ -25,10 +30,12 @@ function createPrismaMock() {
}),
},
accountTransaction: {
findMany: jest.fn(),
findMany: jest.fn().mockResolvedValue([]),
findFirst: jest.fn(),
findUnique: jest.fn().mockResolvedValue(null),
findUniqueOrThrow: jest.fn().mockImplementation(({ where }) => Promise.resolve({ id: 'tx-charged', idempotencyKey: where.idempotencyKey })),
create: jest.fn().mockImplementation(({ data }) => Promise.resolve({ id: `tx-${data.transactionType}`, ...data })),
createMany: jest.fn().mockResolvedValue({ count: 2 }),
},
rechargeOrder: {
findMany: jest.fn(),
@@ -48,6 +55,7 @@ function createPrismaMock() {
create: jest.fn().mockResolvedValue({ id: 'operation-1' }),
},
$executeRaw: jest.fn(),
$queryRaw: jest.fn(),
};
return Object.assign(prisma, {
$transaction: jest.fn((callback: (client: typeof prisma) => unknown) => callback(prisma)),
@@ -91,7 +99,7 @@ describe('BillingService', () => {
);
});
it('allows sending only when cash balance plus credit is greater than zero', async () => {
it('allows sending only when cash balance plus credit covers the required amount', async () => {
const prisma = createPrismaMock();
const service = new BillingService(prisma as never);
@@ -99,7 +107,7 @@ describe('BillingService', () => {
expect.objectContaining({ availableAmount: 1000, canSend: true }),
);
await expect(service.checkAccount({ tenantId: 'tenant-1', amountCents: 1001 })).resolves.toEqual(
expect.objectContaining({ availableAmount: 1000, canSend: true }),
expect.objectContaining({ availableAmount: 1000, canSend: false }),
);
await service.updateCreditLimit('tenant-1', { creditCents: -1000, operatorId: 'admin-1' });
await expect(service.checkAccount({ tenantId: 'tenant-1', amountCents: 1 })).resolves.toEqual(
@@ -107,7 +115,7 @@ describe('BillingService', () => {
);
await service.updateCreditLimit('tenant-1', { creditCents: 500, operatorId: 'admin-1' });
await expect(service.checkAccount({ tenantId: 'tenant-1', amountCents: 999999 })).resolves.toEqual(
expect.objectContaining({ availableAmount: 1500, creditCents: 500, canSend: true }),
expect.objectContaining({ availableAmount: 1500, creditCents: 500, canSend: false }),
);
await expect(service.updateCreditLimit('tenant-1', { creditCents: 1.5 })).rejects.toThrow('授信额度最多支持人民币小数点后 4 位');
expect(prisma.operationLog.create).toHaveBeenCalledWith({
@@ -181,9 +189,10 @@ describe('BillingService', () => {
it('returns the historical balance after each manual recharge', async () => {
const prisma = createPrismaMock();
prisma.rechargeOrder.findMany.mockResolvedValue([
{ id: 'order-1', tenantId: 'tenant-1', payMethod: 'manual_topup', amountCents: 2000 },
{ id: 'order-1', tenantId: 'tenant-1', payMethod: 'manual_topup', amountCents: 2000, operatorId: 'admin-1' },
{ id: 'order-2', tenantId: 'tenant-1', payMethod: 'manual_topup', amountCents: -300 },
]);
prisma.user.findMany.mockResolvedValue([{ id: 'admin-1', displayName: '运营人员张三', username: 'admin' }]);
prisma.accountTransaction.findMany.mockResolvedValue([
{ relatedId: 'order-1', balanceAfter: 3000 },
{ relatedId: 'order-2', balanceAfter: 2700 },
@@ -191,8 +200,8 @@ describe('BillingService', () => {
const service = new BillingService(prisma as never);
await expect(service.listManualRechargeRecords()).resolves.toEqual([
expect.objectContaining({ id: 'order-1', balanceAfterCents: 3000 }),
expect.objectContaining({ id: 'order-2', balanceAfterCents: 2700 }),
expect.objectContaining({ id: 'order-1', balanceAfterCents: 3000, operatorName: '运营人员张三' }),
expect.objectContaining({ id: 'order-2', balanceAfterCents: 2700, operatorName: null }),
]);
expect(prisma.accountTransaction.findMany).toHaveBeenCalledWith({
where: {
@@ -201,6 +210,10 @@ describe('BillingService', () => {
},
select: { relatedId: true, balanceAfter: true },
});
expect(prisma.user.findMany).toHaveBeenCalledWith({
where: { id: { in: ['admin-1'] } },
select: { id: true, displayName: true, username: true },
});
});
it('allows negative manual recharge amounts for balance correction', async () => {
@@ -304,6 +317,28 @@ describe('BillingService', () => {
expect(prisma.accountState).toEqual(expect.objectContaining({ balanceCents: 890 }));
});
it('settles a frozen SMS charge with one account lock and an idempotent ledger pair', async () => {
const prisma = createPrismaMock();
const rows = new Map<string, Record<string, unknown>>();
prisma.accountTransaction.findMany.mockImplementation(() => Promise.resolve([...rows.values()]));
prisma.$queryRaw.mockImplementation(() => {
const charged = { id: 'tx-charged', idempotencyKey: 'sms-charge:msg-paid-1', transactionType: 'charged', amountCents: -325 };
rows.set(String(charged.idempotencyKey), charged);
return Promise.resolve([charged]);
});
const service = new BillingService(prisma as never);
const input = { tenantId: 'tenant-1', amountCents: 325, messageId: 'msg-paid-1', taskId: 'task-paid-1' };
const first = await service.settleFrozenCharge(input);
const replay = await service.settleFrozenCharge(input);
expect(first).toEqual(expect.objectContaining({ transactionType: 'charged', amountCents: -325 }));
expect(replay).toEqual(first);
expect(prisma.$queryRaw).toHaveBeenCalledTimes(1);
expect(prisma.$executeRaw).not.toHaveBeenCalled();
expect(prisma.tenantAccount.update).not.toHaveBeenCalled();
});
it('serializes and replays concurrent refunds with one balance mutation', async () => {
const prisma = createPrismaMock();
let transactionChain = Promise.resolve<unknown>(undefined);
+84 -13
View File
@@ -163,18 +163,27 @@ export class BillingService {
return orders;
}
const transactions = await this.prisma.accountTransaction.findMany({
where: {
relatedType: 'recharge_order',
relatedId: { in: orderIds },
},
select: { relatedId: true, balanceAfter: true },
});
const operatorIds = [...new Set(orders.map((order) => order.operatorId).filter((id): id is string => Boolean(id)))];
const [transactions, operators] = await Promise.all([
this.prisma.accountTransaction.findMany({
where: {
relatedType: 'recharge_order',
relatedId: { in: orderIds },
},
select: { relatedId: true, balanceAfter: true },
}),
operatorIds.length ? this.prisma.user.findMany({
where: { id: { in: operatorIds } },
select: { id: true, displayName: true, username: true },
}) : [],
]);
const balanceAfterByOrderId = new Map(transactions.map((transaction) => [transaction.relatedId, moneyToNumber(transaction.balanceAfter)]));
const operatorNameById = new Map(operators.map((operator) => [operator.id, operator.displayName || operator.username]));
return orders.map((order) => ({
...order,
balanceAfterCents: balanceAfterByOrderId.get(order.id) ?? null,
operatorName: order.operatorId ? operatorNameById.get(order.operatorId) ?? null : null,
}));
}
@@ -195,13 +204,25 @@ export class BillingService {
this.prisma.rechargeOrder.count({ where }),
]);
const orderIds = orders.map((order) => order.id);
const transactions = orderIds.length ? await this.prisma.accountTransaction.findMany({
where: { relatedType: 'recharge_order', relatedId: { in: orderIds } },
select: { relatedId: true, balanceAfter: true },
}) : [];
const operatorIds = [...new Set(orders.map((order) => order.operatorId).filter((id): id is string => Boolean(id)))];
const [transactions, operators] = await Promise.all([
orderIds.length ? this.prisma.accountTransaction.findMany({
where: { relatedType: 'recharge_order', relatedId: { in: orderIds } },
select: { relatedId: true, balanceAfter: true },
}) : [],
operatorIds.length ? this.prisma.user.findMany({
where: { id: { in: operatorIds } },
select: { id: true, displayName: true, username: true },
}) : [],
]);
const balances = new Map(transactions.map((item) => [item.relatedId, moneyToNumber(item.balanceAfter)]));
const operatorNames = new Map(operators.map((operator) => [operator.id, operator.displayName || operator.username]));
return {
items: orders.map((order) => ({ ...order, balanceAfterCents: balances.get(order.id) ?? null })),
items: orders.map((order) => ({
...order,
balanceAfterCents: balances.get(order.id) ?? null,
operatorName: order.operatorId ? operatorNames.get(order.operatorId) ?? null : null,
})),
total,
page,
pageSize,
@@ -395,7 +416,7 @@ export class BillingService {
availableAmount,
balanceCents,
creditCents,
canSend: availableAmount > 0,
canSend: availableAmount >= requiredAmount,
};
}
@@ -415,6 +436,56 @@ export class BillingService {
});
}
async settleFrozenCharge(data: { tenantId: string; amountCents: number; messageId: string; taskId: string; remark?: string }) {
const amountCents = data.amountCents ?? 0;
if (amountCents <= 0) return null;
const releaseKey = `sms-charge-release:${data.messageId}`;
const chargeKey = `sms-charge:${data.messageId}`;
const existing = await this.prisma.accountTransaction.findMany({
where: { idempotencyKey: { in: [releaseKey, chargeKey] } },
});
const charge = existing.find((row) => row.idempotencyKey === chargeKey);
if (charge) return charge;
const release = existing.find((row) => row.idempotencyKey === releaseKey);
if (release) {
// Recover the legacy two-transaction boundary: a crash may have committed
// release before charge, so this path must perform the missing balance debit.
return this.applyAccountDelta({
tenantId: data.tenantId, transactionType: 'charged', idempotencyKey: chargeKey,
amountCents: -amountCents, relatedType: 'sms_message_record', relatedId: data.messageId,
remark: '提交成功扣费(恢复既有已释放冻结)',
});
}
const rows = await this.prisma.$queryRaw<Array<{ id: string; idempotencyKey: string }>>(Prisma.sql`
WITH account AS (
SELECT "balanceCents" FROM "TenantAccount" WHERE "tenantId" = ${data.tenantId}
), inserted AS (
INSERT INTO "AccountTransaction" (
id, "tenantId", "transactionType", "idempotencyKey", "amountCents",
"balanceAfter", "relatedType", "relatedId", remark, "createdAt"
)
SELECT gen_random_uuid()::text, ${data.tenantId}, ledger."transactionType", ledger."idempotencyKey",
ledger."amountCents", account."balanceCents" + ledger."balanceDelta",
ledger."relatedType", ledger."relatedId", ledger.remark, (NOW() AT TIME ZONE 'UTC')
FROM account
CROSS JOIN (VALUES
('released', ${releaseKey}, ${amountCents}::bigint, ${amountCents}::bigint, 'sms_batch_task', ${data.taskId}, ${data.remark ?? null}),
('charged', ${chargeKey}, ${-amountCents}::bigint, 0::bigint, 'sms_message_record', ${data.messageId}, '提交成功扣费')
) AS ledger("transactionType", "idempotencyKey", "amountCents", "balanceDelta", "relatedType", "relatedId", remark)
ON CONFLICT ("idempotencyKey") DO NOTHING
RETURNING id, "idempotencyKey"
)
SELECT id, "idempotencyKey" FROM inserted WHERE "idempotencyKey" = ${chargeKey}
UNION ALL
SELECT id, "idempotencyKey" FROM "AccountTransaction" WHERE "idempotencyKey" = ${chargeKey}
LIMIT 1
`);
if (rows[0]) return rows[0];
// A concurrent identical callback can win ON CONFLICT while remaining
// invisible to this statement's snapshot; one read repairs that MVCC edge.
return this.prisma.accountTransaction.findUniqueOrThrow({ where: { idempotencyKey: chargeKey } });
}
release(data: BillingActionDto) {
return this.applyAccountDelta({
...data,
@@ -1,8 +1,10 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { Body, Controller, Get, Param, Post, Query, UsePipes } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { CurrentSessionUserId } from '../auth/current-session-user.decorator';
import { TenantId } from '../common/tenant-id.decorator';
import { CertificationService, ReviewCertificationDto, SubmitCertificationDto } from './certification.service';
import { CurrentTenantId } from '../auth/current-tenant-id.decorator';
import { ClientCertificationSubmissionDto } from '../common/client-write.dto';
import { strictValidationPipe } from '../common/strict-validation.pipe';
import { CertificationService, ReviewCertificationDto } from './certification.service';
@ApiTags('client-certification')
@Controller('client/enterprise-certification')
@@ -10,13 +12,14 @@ export class ClientCertificationController {
constructor(private readonly certifications: CertificationService) {}
@Get()
list(@TenantId() tenantId?: string) {
list(@CurrentTenantId() tenantId: string) {
return this.certifications.list(tenantId);
}
@Post()
submit(@Body() body: SubmitCertificationDto) {
return this.certifications.submit(body);
@UsePipes(strictValidationPipe)
submit(@CurrentTenantId() tenantId: string, @Body() body: ClientCertificationSubmissionDto) {
return this.certifications.submit({ ...body, tenantId });
}
}
@@ -26,8 +29,8 @@ export class AdminCertificationController {
constructor(private readonly certifications: CertificationService) {}
@Get()
list(@Query('tenantId') tenantId?: string, @Query('status') status?: string, @Query('keyword') keyword?: string) {
return this.certifications.list(tenantId, status, keyword);
list(@Query('tenantId') tenantId?: string, @Query('status') status?: string, @Query('keyword') keyword?: string, @Query('submittedAtFrom') submittedAtFrom?: string, @Query('submittedAtTo') submittedAtTo?: string) {
return this.certifications.list(tenantId, status, keyword, submittedAtFrom, submittedAtTo);
}
@Get(':id')
@@ -38,6 +38,22 @@ describe('CertificationService', () => {
]);
});
it('filters enterprise certification submissions by Shanghai date range', async () => {
const prisma = createPrismaMock();
const service = new CertificationService(prisma as never);
await service.list(undefined, 'pending', undefined, '2026-08-01', '2026-08-03');
expect(prisma.enterpriseCertification.findMany).toHaveBeenCalledWith(expect.objectContaining({
where: expect.objectContaining({
submittedAt: {
gte: new Date('2026-08-01T00:00:00+08:00'),
lte: new Date('2026-08-03T23:59:59.999+08:00'),
},
}),
}));
});
it('submits certification and marks tenant pending', async () => {
const prisma = createPrismaMock();
const service = new CertificationService(prisma as never);
@@ -1,6 +1,7 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { shanghaiDateRange } from '../common/shanghai-date-range';
export interface SubmitCertificationDto {
tenantId: string;
@@ -20,11 +21,12 @@ export interface ReviewCertificationDto {
export class CertificationService {
constructor(private readonly prisma: PrismaService) {}
async list(tenantId?: string, status?: string, keyword?: string) {
async list(tenantId?: string, status?: string, keyword?: string, submittedAtFrom?: string, submittedAtTo?: string) {
const records = await this.prisma.enterpriseCertification.findMany({
where: {
tenantId,
status: status && status !== 'all' ? status : undefined,
submittedAt: shanghaiDateRange(submittedAtFrom, submittedAtTo),
OR: keyword ? [
{ companyName: { contains: keyword } },
{ licenseNo: { contains: keyword } },
@@ -0,0 +1,51 @@
import { ChannelConfigurationService } from './channel-configuration.service';
import { selectChannelCandidate } from '../send-chain/send-chain.helpers';
describe('carrier capability reduction', () => {
it('preserves group references and avoids reconnecting for a capability-only change', async () => {
const channel = {
id: 'c',
carrier: 'all',
carriers: ['mobile', 'unicom', 'telecom'],
status: 'active',
config: {},
};
const prisma = {
smsChannel: {
findUnique: jest.fn().mockResolvedValue(channel),
update: jest.fn().mockImplementation(({ data }) => ({ ...channel, ...data })),
},
operationLog: { create: jest.fn() },
smsChannelGroupItem: {
findMany: jest.fn().mockResolvedValue([{ group: { name: 'existing' } }]),
deleteMany: jest.fn(),
},
};
const connection = { requestChannelConnection: jest.fn(), requestChannelDisconnection: jest.fn() };
await new ChannelConfigurationService(prisma as never, connection as never).updateChannel('c', {
carriers: ['mobile', 'unicom'],
});
expect(prisma.smsChannel.update).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ carriers: ['mobile', 'unicom'] }) }),
);
expect(prisma.smsChannelGroupItem.deleteMany).not.toHaveBeenCalled();
expect(connection.requestChannelConnection).not.toHaveBeenCalled();
const candidate = {
channelId: 'c',
carrier: 'telecom',
channel: {
...channel,
carrier: 'mobile',
carriers: ['mobile', 'unicom'],
sendRegion: '全国',
connectionStates: [{ status: 'connected', currentConnections: 1, desiredConnections: 1 }],
},
};
expect(
selectChannelCandidate([candidate], {
carrier: 'telecom',
excludedChannelIds: new Set(),
approvedChannelIds: new Set(['c']),
}),
).toBeUndefined();
});
});
@@ -0,0 +1,263 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { assertMoneyUnits, moneyToNumber } from '../common/money';
import { PrismaService } from '../prisma/prisma.service';
import { ChannelConnectionService } from './channel-connection.service';
import type { ChangeChannelStatusDto, CreateChannelDto, UpdateChannelDto } from './channels.contracts';
import {
channelConnectionSettingsChanged,
currentShanghaiDayRange,
legacyCarrierFromCapabilities,
normalizeBusinessCarrier,
normalizeChannelCarriers,
normalizeChannelRateLimit,
normalizeChannelRuntimeConfig,
normalizeCmppVersion,
} from './channels.helpers';
/** R5 channel domain service composed behind ChannelsService. */
export class ChannelConfigurationService {
constructor(
private readonly prisma: PrismaService,
private readonly connection: ChannelConnectionService,
) {}
listChannels() {
return this.prisma.smsChannel.findMany({
include: { connectionStates: true },
orderBy: { createdAt: 'desc' },
});
}
async listChannelsPage(query: {
keyword?: string;
carrier?: string;
status?: string;
page?: number;
pageSize?: number;
}) {
const page = Math.max(1, Math.floor(Number(query.page) || 1));
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
const where: Prisma.SmsChannelWhereInput = {
status: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
carriers: query.carrier && query.carrier !== 'all' ? { has: normalizeBusinessCarrier(query.carrier) } : undefined,
name: query.keyword?.trim() ? { contains: query.keyword.trim() } : undefined,
};
const candidates = await this.prisma.smsChannel.findMany({ where, select: { id: true, name: true } });
const total = candidates.length;
if (total === 0) return { items: [], total, page, pageSize };
const day = currentShanghaiDayRange();
const counts = await this.prisma.$queryRaw<Array<{ channelId: string; total: number }>>(Prisma.sql`
SELECT submit."channelId" AS "channelId", COUNT(*)::integer AS total
FROM "SmsSubmitRecord" submit
WHERE submit."channelId" IN (${Prisma.join(candidates.map((channel) => channel.id))})
AND COALESCE(submit."submittedAt", submit."createdAt") >= ${day.startAt}
AND COALESCE(submit."submittedAt", submit."createdAt") < ${day.endAt}
AND submit."submitStatus" IN ('accepted', 'rejected', 'timeout')
GROUP BY submit."channelId"
`);
const countByChannel = new Map(counts.map((row) => [row.channelId, Number(row.total)]));
// 排序必须发生在分页前,否则只能重排当前页,翻页后会破坏“今日提交量降序”的业务口径。
const pageIds = candidates
.sort(
(left, right) =>
(countByChannel.get(right.id) ?? 0) - (countByChannel.get(left.id) ?? 0) ||
left.name.localeCompare(right.name, 'zh-CN') ||
left.id.localeCompare(right.id),
)
.slice((page - 1) * pageSize, page * pageSize)
.map((channel) => channel.id);
const pageItems = await this.prisma.smsChannel.findMany({
where: { id: { in: pageIds } },
include: { connectionStates: true },
});
const itemById = new Map(pageItems.map((item) => [item.id, item]));
const items = pageIds.flatMap((id) => {
const item = itemById.get(id);
return item ? [item] : [];
});
return { items, total, page, pageSize };
}
async createChannel(data: CreateChannelDto) {
assertMoneyUnits(data.unitPrice ?? 0, '通道单价');
const missingFields = ['code', 'name', 'gatewayHost', 'account', 'passwordCipher', 'srcId'].filter((field) => {
const value = data[field as keyof CreateChannelDto];
return value === undefined || value === null || value === '';
});
if (missingFields.length > 0) {
throw new BadRequestException(`Missing required channel fields: ${missingFields.join(', ')}`);
}
const gatewayPort = Number(data.gatewayPort ?? 7890);
if (!Number.isInteger(gatewayPort) || gatewayPort <= 0 || gatewayPort > 65535) {
throw new BadRequestException('gatewayPort must be an integer between 1 and 65535');
}
const cmppVersion = normalizeCmppVersion(data.cmppVersion);
const config = normalizeChannelRuntimeConfig(
undefined,
data.config,
data.desiredConnections,
data.windowSize,
data.heartbeatIntervalSeconds,
data.heartbeatMissThreshold,
);
const rateLimitPerSecond = normalizeChannelRateLimit(data.rateLimitPerSecond);
const carriers = normalizeChannelCarriers(data.carriers, data.carrier);
const channel = await this.prisma.smsChannel.create({
data: {
code: data.code,
name: data.name,
carrier: legacyCarrierFromCapabilities(carriers),
carriers,
sendRegion: data.sendRegion ?? '全国',
protocol: 'CMPP',
gatewayHost: data.gatewayHost,
gatewayPort,
enterpriseCode: data.enterpriseCode,
account: data.account,
passwordCipher: data.passwordCipher,
srcId: data.srcId,
cmppVersion,
rateLimitPerSecond,
unitPrice: data.unitPrice ?? 0,
status: data.status ?? 'active',
config: config as Prisma.InputJsonValue,
},
});
if (channel.status === 'active') {
await this.connection.requestChannelConnection(channel, 'channel_created');
}
return channel;
}
async updateChannel(channelId: string, data: UpdateChannelDto) {
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId } });
if (!channel) {
throw new NotFoundException('Channel not found');
}
if (data.unitPrice !== undefined) {
assertMoneyUnits(data.unitPrice, '通道单价');
}
const gatewayPort = data.gatewayPort === undefined ? undefined : Number(data.gatewayPort);
if (gatewayPort !== undefined && (!Number.isInteger(gatewayPort) || gatewayPort <= 0 || gatewayPort > 65535)) {
throw new BadRequestException('gatewayPort must be an integer between 1 and 65535');
}
const cmppVersion = data.cmppVersion === undefined ? undefined : normalizeCmppVersion(data.cmppVersion);
const config =
data.config !== undefined ||
data.desiredConnections !== undefined ||
data.windowSize !== undefined ||
data.heartbeatIntervalSeconds !== undefined ||
data.heartbeatMissThreshold !== undefined
? normalizeChannelRuntimeConfig(
channel.config,
data.config,
data.desiredConnections,
data.windowSize,
data.heartbeatIntervalSeconds,
data.heartbeatMissThreshold,
)
: undefined;
const rateLimitPerSecond =
data.rateLimitPerSecond === undefined ? undefined : normalizeChannelRateLimit(data.rateLimitPerSecond);
const existingCarriers = normalizeChannelCarriers(channel.carriers, channel.carrier);
const carriers =
data.carriers !== undefined || data.carrier !== undefined
? normalizeChannelCarriers(data.carriers, data.carrier)
: existingCarriers;
const connectionConfigChanged = channelConnectionSettingsChanged(channel, {
gatewayHost: data.gatewayHost ?? channel.gatewayHost,
gatewayPort: gatewayPort ?? channel.gatewayPort,
account: data.account ?? channel.account,
passwordCipher: data.passwordCipher ?? channel.passwordCipher,
cmppVersion: cmppVersion ?? channel.cmppVersion,
config: config ?? channel.config,
});
const updated = await this.prisma.smsChannel.update({
where: { id: channelId },
data: {
code: data.code,
name: data.name,
carrier:
data.carriers !== undefined || data.carrier !== undefined
? legacyCarrierFromCapabilities(carriers)
: undefined,
carriers: data.carriers !== undefined || data.carrier !== undefined ? carriers : undefined,
sendRegion: data.sendRegion,
protocol: 'CMPP',
gatewayHost: data.gatewayHost,
gatewayPort,
enterpriseCode: data.enterpriseCode,
account: data.account,
passwordCipher: data.passwordCipher,
srcId: data.srcId,
cmppVersion,
rateLimitPerSecond,
unitPrice: data.unitPrice,
status: data.status,
config: config as Prisma.InputJsonValue | undefined,
},
});
await this.prisma.operationLog.create({
data: {
action: 'sms_channel.update',
resource: 'sms_channel',
resourceId: channelId,
detail: {
before: {
code: channel.code,
name: channel.name,
carrier: channel.carrier,
carriers: channel.carriers,
sendRegion: channel.sendRegion,
gatewayHost: channel.gatewayHost,
gatewayPort: channel.gatewayPort,
enterpriseCode: channel.enterpriseCode,
account: channel.account,
srcId: channel.srcId,
unitPrice: moneyToNumber(channel.unitPrice),
},
after: data,
} as Prisma.InputJsonValue,
},
});
const updatedStatus = data.status ?? channel.status;
if (updatedStatus === 'active' && (connectionConfigChanged || channel.status !== 'active')) {
await this.connection.requestChannelConnection(updated, 'channel_updated');
} else if (updatedStatus !== 'active' && channel.status === 'active') {
await this.connection.requestChannelDisconnection(updated, 'channel_disabled');
}
return updated;
}
async changeChannelStatus(channelId: string, data: ChangeChannelStatusDto) {
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId } });
if (!channel) {
throw new NotFoundException('Channel not found');
}
const updated = await this.prisma.smsChannel.update({ where: { id: channelId }, data: { status: data.status } });
await this.prisma.operationLog.create({
data: {
userId: data.operatorId,
action: `sms_channel.${data.status}`,
resource: 'sms_channel',
resourceId: channelId,
detail: {
statusBefore: channel.status,
statusAfter: data.status,
reason: data.reason,
} as Prisma.InputJsonValue,
},
});
if (data.status === 'active') {
await this.connection.requestChannelConnection(updated, 'channel_enabled', data.operatorId);
} else if (channel.status === 'active' || data.status === 'deleted') {
await this.connection.requestChannelDisconnection(
updated,
data.status === 'deleted' ? 'channel_deleted' : 'channel_disabled',
data.operatorId,
);
}
return updated;
}
}
@@ -0,0 +1,616 @@
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { Queue } from 'bullmq';
import IORedis from 'ioredis';
import { Prisma } from '@prisma/client';
import { randomUUID } from 'crypto';
import { assertMoneyUnits, moneyToNumber } from '../common/money';
import { PrismaService } from '../prisma/prisma.service';
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
/** R5 channel domain service composed behind ChannelsService. */
export class ChannelConnectionService {
private readonly logger = new Logger(ChannelConnectionService.name);
private gatewayConnectionQueue?: Queue;
private gatewaySubmitQueue?: Queue;
private redis?: IORedis;
private connectionTimeoutTimer?: ReturnType<typeof setInterval>;
private gatewayStartupReconnectTimer?: ReturnType<typeof setTimeout>;
private gatewayReconcileTimer?: ReturnType<typeof setInterval>;
constructor(private readonly prisma: PrismaService) {}
onModuleInit() {
if (process.env.GATEWAY_CONNECTING_TIMEOUT_SCANNER_DISABLED !== 'true') {
this.connectionTimeoutTimer = setInterval(() => {
void this.markTimedOutConnectingChannels().catch((error) => {
this.logger.error(`Failed to mark timed-out CMPP connections: ${error instanceof Error ? error.message : String(error)}`);
});
}, getPositiveIntegerEnv('GATEWAY_CONNECTING_TIMEOUT_SCAN_MS', DEFAULT_CONNECTING_TIMEOUT_SCAN_MS));
this.connectionTimeoutTimer.unref?.();
}
this.gatewayStartupReconnectTimer = setTimeout(() => {
void this.reconnectActiveChannelsAfterGatewayRestart();
}, getPositiveIntegerEnv('GATEWAY_STARTUP_RECONNECT_DELAY_MS', DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS));
this.gatewayStartupReconnectTimer.unref?.();
if (process.env.GATEWAY_CONNECTION_RECONCILER_DISABLED !== 'true') {
this.gatewayReconcileTimer = setInterval(() => {
void this.reconcileGatewayConnections().catch((error) => {
this.logger.error(`Failed to reconcile supplier connections: ${error instanceof Error ? error.message : String(error)}`);
});
}, getPositiveIntegerEnv('GATEWAY_CONNECTION_RECONCILE_INTERVAL_MS', DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS));
this.gatewayReconcileTimer.unref?.();
}
}
async onModuleDestroy() {
if (this.connectionTimeoutTimer) {
clearInterval(this.connectionTimeoutTimer);
}
if (this.gatewayStartupReconnectTimer) {
clearTimeout(this.gatewayStartupReconnectTimer);
}
if (this.gatewayReconcileTimer) {
clearInterval(this.gatewayReconcileTimer);
}
await this.gatewayConnectionQueue?.close();
await this.gatewaySubmitQueue?.close();
this.redis?.disconnect();
}
listChannelMetrics(channelId: string) {
return this.prisma.channelHealthMetric.findMany({
where: { channelId },
orderBy: { windowStart: 'desc' },
take: 100,
});
}
listChannelConnections(channelId: string) {
return this.prisma.cmppConnectionState.findMany({
where: { channelId },
orderBy: { updatedAt: 'desc' },
});
}
async listChannelConnectionLogs(channelId: string) {
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId }, select: { id: true } });
if (!channel) {
throw new NotFoundException('Channel not found');
}
const [connectionStates, logs] = await Promise.all([
this.prisma.cmppConnectionState.findMany({
where: { channelId },
orderBy: { updatedAt: 'desc' },
take: 50,
}),
this.prisma.operationLog.findMany({
where: {
OR: [
{ resource: 'sms_channel', resourceId: channelId },
{ resource: 'cmpp_connection', resourceId: { startsWith: `${channelId}:` } },
],
},
orderBy: { createdAt: 'desc' },
take: 100,
}),
]);
return {
channelId,
connectionStates,
logs: logs.map((log) => ({
id: log.id,
time: log.createdAt,
event: normalizeLinkEvent(log.action),
action: log.action,
resourceId: log.resourceId,
detail: log.detail,
})),
};
}
listTenantConnections(tenantId: string) {
return this.prisma.cmppConnectionState.findMany({
where: { tenantId },
include: { channel: true },
orderBy: { updatedAt: 'desc' },
});
}
async upsertConnectionState(data: UpsertConnectionStateDto) {
const rawStatus = data.status;
const status = normalizeGatewayConnectionStatus(rawStatus);
if (data.applicationId) {
const application = await this.prisma.smsApplication.findUnique({ where: { id: data.applicationId }, select: { tenantId: true } });
if (!application) {
throw new BadRequestException('applicationId does not reference an existing application');
}
if (data.tenantId && data.tenantId !== application.tenantId) {
throw new BadRequestException('applicationId does not belong to tenantId');
}
data.tenantId = application.tenantId;
}
const payload = {
tenantId: data.tenantId,
applicationId: data.applicationId,
status,
desiredConnections: data.desiredConnections ?? 1,
currentConnections: data.currentConnections ?? (status === 'connected' ? 1 : 0),
lastConnectedAt: data.lastConnectedAt ? new Date(data.lastConnectedAt) : undefined,
lastDisconnectedAt: data.lastDisconnectedAt ? new Date(data.lastDisconnectedAt) : undefined,
lastHeartbeatAt: data.lastHeartbeatAt ? new Date(data.lastHeartbeatAt) : undefined,
reconnectCount: data.reconnectCount ?? 0,
lastReconnectAttemptAt: data.lastReconnectAttemptAt ? new Date(data.lastReconnectAttemptAt) : undefined,
nextReconnectAt: data.nextReconnectAt ? new Date(data.nextReconnectAt) : status === 'connected' ? null : undefined,
lastErrorCategory: status === 'connected' ? null : data.lastErrorCategory,
lastError: status === 'connected' ? null : data.lastError,
};
const existing = await this.prisma.cmppConnectionState.findFirst({
where: {
applicationId: data.applicationId ?? null,
channelId: data.channelId,
connectionId: data.connectionId,
},
});
let state;
if (existing) {
state = await this.prisma.cmppConnectionState.update({ where: { id: existing.id }, data: payload });
} else {
try {
state = await this.prisma.cmppConnectionState.create({
data: {
channelId: data.channelId,
connectionId: data.connectionId,
...payload,
},
});
} catch (error) {
if ((error as { code?: string }).code !== 'P2002') {
throw error;
}
const concurrent = await this.prisma.cmppConnectionState.findFirst({
where: {
applicationId: data.applicationId ?? null,
channelId: data.channelId,
connectionId: data.connectionId,
},
});
if (!concurrent) {
throw error;
}
state = await this.prisma.cmppConnectionState.update({ where: { id: concurrent.id }, data: payload });
}
}
const action = normalizeConnectionAction(
['heartbeat', 'active_test'].includes(rawStatus.toLowerCase()) ? rawStatus : status,
);
const heartbeatObservedAt = data.lastHeartbeatAt ? new Date(data.lastHeartbeatAt) : new Date();
const shouldWriteAudit = action !== 'heartbeat'
|| !existing?.lastHeartbeatAt
|| heartbeatObservedAt.getTime() - existing.lastHeartbeatAt.getTime() >= HEARTBEAT_AUDIT_INTERVAL_MS;
if (shouldWriteAudit) {
await this.prisma.operationLog.create({
data: {
tenantId: data.tenantId,
action: `cmpp_connection.${action}`,
resource: 'cmpp_connection',
resourceId: `${data.channelId}:${data.connectionId}`,
detail: {
status,
applicationId: state.applicationId,
desiredConnections: state.desiredConnections,
currentConnections: state.currentConnections,
lastError: state.lastError,
} as Prisma.InputJsonValue,
},
});
}
return state;
}
async markTimedOutConnectingChannels(now = new Date()) {
const timeoutMs = getPositiveIntegerEnv('GATEWAY_CONNECTING_TIMEOUT_MS', DEFAULT_CONNECTING_TIMEOUT_MS);
const cutoff = new Date(now.getTime() - timeoutMs);
const lastError = `${CONNECTING_TIMEOUT_ERROR} after ${Math.round(timeoutMs / 1000)} seconds`;
const states = await this.prisma.cmppConnectionState.findMany({
where: {
status: 'connecting',
updatedAt: { lte: cutoff },
},
select: {
id: true,
tenantId: true,
applicationId: true,
channelId: true,
connectionId: true,
desiredConnections: true,
currentConnections: true,
updatedAt: true,
},
take: 100,
});
let failed = 0;
for (const state of states) {
const result = await this.prisma.cmppConnectionState.updateMany({
where: {
id: state.id,
status: 'connecting',
updatedAt: { lte: cutoff },
},
data: {
status: 'failed',
currentConnections: 0,
lastDisconnectedAt: now,
nextReconnectAt: now,
lastErrorCategory: 'timeout',
lastError,
},
});
if (result.count === 0) {
continue;
}
failed += result.count;
await this.prisma.operationLog.create({
data: {
tenantId: state.tenantId,
action: 'cmpp_connection.failed',
resource: 'cmpp_connection',
resourceId: `${state.channelId}:${state.connectionId}`,
detail: {
reason: 'connect_timeout',
applicationId: state.applicationId,
status: 'failed',
previousStatus: 'connecting',
desiredConnections: state.desiredConnections,
currentConnectionsBefore: state.currentConnections,
currentConnections: 0,
timeoutMs,
lastError,
} as Prisma.InputJsonValue,
},
});
}
return { checked: states.length, failed };
}
async requestChannelConnection(
channel: {
id: string;
code: string;
name: string;
gatewayHost: string;
gatewayPort: number;
account: string;
passwordCipher: string;
srcId: string;
cmppVersion: string;
rateLimitPerSecond: number;
config?: Prisma.JsonValue | null;
},
reason: 'channel_created' | 'channel_enabled' | 'channel_updated' | 'gateway_restarted' | 'automatic_reconnect',
operatorId?: string,
) {
const desiredConnections = getDesiredConnections(channel.config);
const connectionId = defaultChannelConnectionId(channel.id);
const existing = await this.prisma.cmppConnectionState.findFirst({
where: {
applicationId: null,
channelId: channel.id,
connectionId,
},
});
const data = {
applicationId: null,
status: 'connecting',
desiredConnections,
currentConnections: 0,
lastError: null,
lastReconnectAttemptAt: new Date(),
nextReconnectAt: new Date(Date.now() + getPositiveIntegerEnv('GATEWAY_CONNECTING_TIMEOUT_MS', DEFAULT_CONNECTING_TIMEOUT_MS)),
};
let state;
if (existing) {
state = await this.prisma.cmppConnectionState.update({ where: { id: existing.id }, data });
} else {
try {
state = await this.prisma.cmppConnectionState.create({
data: {
channelId: channel.id,
connectionId,
...data,
},
});
} catch (error) {
if ((error as { code?: string }).code !== 'P2002') {
throw error;
}
const concurrent = await this.prisma.cmppConnectionState.findFirst({
where: { applicationId: null, channelId: channel.id, connectionId },
});
if (!concurrent) {
throw error;
}
state = await this.prisma.cmppConnectionState.update({ where: { id: concurrent.id }, data });
}
}
await this.prisma.operationLog.create({
data: {
userId: operatorId,
action: 'cmpp_connection.connect_requested',
resource: 'cmpp_connection',
resourceId: `${channel.id}:${connectionId}`,
detail: {
reason,
status: state.status,
desiredConnections: state.desiredConnections,
currentConnections: state.currentConnections,
} as Prisma.InputJsonValue,
},
});
const command = {
schemaVersion: 'v1',
messageType: 'ConnectChannel',
traceId: randomUUID(),
channelId: channel.id,
connectionId,
createdAt: new Date().toISOString(),
reason,
desiredConnections,
channel: {
code: channel.code,
name: channel.name,
gatewayHost: channel.gatewayHost,
gatewayPort: channel.gatewayPort,
account: channel.account,
passwordCipher: channel.passwordCipher,
srcId: channel.srcId,
cmppVersion: channel.cmppVersion,
rateLimitPerSecond: channel.rateLimitPerSecond,
windowSize: getPositiveRuntimeInteger(getConfigValue(channel.config, 'windowSize'), 16, 'windowSize'),
connectionWarmupSeconds: Number(getConfigValue(channel.config, 'connectionWarmupSeconds') ?? 30),
connectionDrainTimeoutSeconds: getPositiveRuntimeInteger(getConfigValue(channel.config, 'connectionDrainTimeoutSeconds'), 60, 'connectionDrainTimeoutSeconds'),
submitResponseTimeoutSeconds: getPositiveRuntimeInteger(getConfigValue(channel.config, 'submitResponseTimeoutSeconds'), 60, 'submitResponseTimeoutSeconds'),
connectionFailureCooldownSeconds: getPositiveRuntimeInteger(getConfigValue(channel.config, 'connectionFailureCooldownSeconds'), 30, 'connectionFailureCooldownSeconds'),
heartbeatIntervalSeconds: getPositiveRuntimeInteger(
getConfigValue(channel.config, 'heartbeatIntervalSeconds'),
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
'heartbeatIntervalSeconds',
),
heartbeatMissThreshold: getPositiveRuntimeInteger(
getConfigValue(channel.config, 'heartbeatMissThreshold'),
DEFAULT_HEARTBEAT_MISS_THRESHOLD,
'heartbeatMissThreshold',
),
},
};
const queuedJob = await this.getGatewayConnectionQueue().add('connect-channel', command, {
jobId: `gateway-connect-${channel.id}-${command.traceId}`,
removeOnComplete: 1000,
removeOnFail: 1000,
}).catch((error) => {
this.logger.warn(`Gateway connect marker enqueue failed; continuing with direct control request: ${error instanceof Error ? error.message : String(error)}`);
return undefined;
});
try {
await this.notifyGatewayConnect(command);
} finally {
if (queuedJob) {
await queuedJob.remove().catch((error) => {
this.logger.warn(`Failed to remove delivered Gateway connect marker ${queuedJob.id}: ${error instanceof Error ? error.message : String(error)}`);
});
}
}
return state;
}
async reconnectActiveChannelsAfterGatewayRestart() {
const channels = await this.prisma.smsChannel.findMany({ where: { status: 'active' } });
const results = await Promise.allSettled(
channels.map((channel) => this.requestChannelConnection(channel, 'gateway_restarted')),
);
results.forEach((result, index) => {
if (result.status === 'rejected') {
const channel = channels[index];
this.logger.error(
`Failed to restore active CMPP channel ${channel?.code ?? channel?.id ?? index}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,
);
}
});
}
async reconcileGatewayConnections(now = new Date()) {
const channels = await this.prisma.smsChannel.findMany({
where: { status: { in: ['active', 'disabled', 'deleted'] } },
include: {
connectionStates: {
where: { applicationId: null },
},
},
take: 200,
});
let reconnectRequested = 0;
let disconnectRequested = 0;
for (const channel of channels) {
const state = channel.connectionStates.find((item) => item.connectionId === defaultChannelConnectionId(channel.id));
if (channel.status !== 'active') {
if (state && (state.currentConnections > 0 || ['connected', 'connecting', 'reconnecting'].includes(state.status))) {
await this.withGatewayReconcileLock(channel.id, async () => {
await this.requestChannelDisconnection(channel, 'inactive_channel_reconcile');
disconnectRequested++;
});
}
continue;
}
const desiredConnections = getDesiredConnections(channel.config);
const heartbeatIntervalSeconds = getPositiveRuntimeInteger(
getConfigValue(channel.config, 'heartbeatIntervalSeconds'),
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
'heartbeatIntervalSeconds',
);
const heartbeatMissThreshold = getPositiveRuntimeInteger(
getConfigValue(channel.config, 'heartbeatMissThreshold'),
DEFAULT_HEARTBEAT_MISS_THRESHOLD,
'heartbeatMissThreshold',
);
const heartbeatCutoff = new Date(now.getTime() - heartbeatIntervalSeconds * (heartbeatMissThreshold + 1) * 1000);
const connectedAndFresh = state?.status === 'connected'
&& state.currentConnections >= desiredConnections
&& Boolean(state.lastHeartbeatAt && state.lastHeartbeatAt > heartbeatCutoff);
const retryDue = !state?.nextReconnectAt || state.nextReconnectAt <= now;
if (!connectedAndFresh && retryDue) {
await this.withGatewayReconcileLock(channel.id, async () => {
await this.requestChannelConnection(channel, 'automatic_reconnect');
reconnectRequested++;
});
}
}
return { scanned: channels.length, reconnectRequested, disconnectRequested };
}
async withGatewayReconcileLock(channelId: string, action: () => Promise<void>) {
const redis = this.getRedis();
const key = `cmpp:gateway:reconcile:${channelId}`;
const token = randomUUID();
const acquired = await redis.set(key, token, 'PX', DEFAULT_CONNECTING_TIMEOUT_MS, 'NX');
if (acquired !== 'OK') {
return;
}
try {
await action();
} finally {
await redis.eval(
'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',
1,
key,
token,
);
}
}
async requestChannelDisconnection(
channel: { id: string },
reason: 'channel_disabled' | 'channel_deleted' | 'inactive_channel_reconcile',
operatorId?: string,
) {
const connectionId = defaultChannelConnectionId(channel.id);
const now = new Date();
await this.prisma.cmppConnectionState.updateMany({
where: {
applicationId: null,
channelId: channel.id,
connectionId,
},
data: {
status: 'disconnected',
currentConnections: 0,
lastDisconnectedAt: now,
nextReconnectAt: null,
lastErrorCategory: null,
lastError: null,
},
});
await this.prisma.operationLog.create({
data: {
userId: operatorId,
action: 'cmpp_connection.disconnect_requested',
resource: 'cmpp_connection',
resourceId: `${channel.id}:${connectionId}`,
detail: { reason } as Prisma.InputJsonValue,
},
});
const command = {
schemaVersion: 'v1',
messageType: 'DisconnectChannel',
traceId: randomUUID(),
channelId: channel.id,
connectionId,
createdAt: now.toISOString(),
reason,
};
const queuedJob = await this.getGatewayConnectionQueue().add('disconnect-channel', command, {
jobId: `gateway-disconnect-${channel.id}-${command.traceId}`,
removeOnComplete: 1000,
removeOnFail: 1000,
}).catch((error) => {
this.logger.warn(`Gateway disconnect marker enqueue failed; continuing with direct control request: ${error instanceof Error ? error.message : String(error)}`);
return undefined;
});
try {
await this.notifyGatewayDisconnect(command);
} finally {
if (queuedJob) {
await queuedJob.remove().catch((error) => {
this.logger.warn(`Failed to remove delivered Gateway disconnect marker ${queuedJob.id}: ${error instanceof Error ? error.message : String(error)}`);
});
}
}
}
getGatewayConnectionQueue() {
this.gatewayConnectionQueue ??= new Queue(GATEWAY_CONNECTION_QUEUE, { connection: bullmqConnection() });
return this.gatewayConnectionQueue;
}
getGatewaySubmitQueue() {
this.gatewaySubmitQueue ??= new Queue(GATEWAY_SUBMIT_QUEUE, { connection: bullmqConnection() });
return this.gatewaySubmitQueue;
}
getRedis() {
if (!this.redis) {
this.redis = new IORedis(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379', {
maxRetriesPerRequest: null,
});
}
return this.redis;
}
async publishGatewaySubmitCommand(command: unknown) {
return this.getRedis().xadd(
process.env.GATEWAY_SUBMIT_STREAM ?? GATEWAY_SUBMIT_STREAM,
'*',
'messageType',
'SubmitCommand',
'data',
JSON.stringify(command),
);
}
async notifyGatewayConnect(command: Record<string, unknown>) {
const baseUrl = (process.env.GATEWAY_CONTROL_URL ?? DEFAULT_GATEWAY_CONTROL_URL).replace(/\/+$/, '');
let response: { ok: boolean; status: number; text: () => Promise<string> };
try {
response = await fetch(`${baseUrl}/connections/connect`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(command),
signal: AbortSignal.timeout(getPositiveIntegerEnv('GATEWAY_CONTROL_TIMEOUT_MS', DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS)),
});
} catch (error) {
throw new BadRequestException(`Gateway connect request failed: ${error instanceof Error ? error.message : String(error)}`);
}
if (!response.ok) {
const responseText = await response.text();
throw new BadRequestException(`Gateway connect request failed: ${response.status} ${responseText}`);
}
}
async notifyGatewayDisconnect(command: Record<string, unknown>) {
const baseUrl = (process.env.GATEWAY_CONTROL_URL ?? DEFAULT_GATEWAY_CONTROL_URL).replace(/\/+$/, '');
let response: { ok: boolean; status: number; text: () => Promise<string> };
try {
response = await fetch(`${baseUrl}/connections/disconnect`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(command),
signal: AbortSignal.timeout(getPositiveIntegerEnv('GATEWAY_CONTROL_TIMEOUT_MS', DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS)),
});
} catch (error) {
throw new BadRequestException(`Gateway disconnect request failed: ${error instanceof Error ? error.message : String(error)}`);
}
if (!response.ok) {
const responseText = await response.text();
throw new BadRequestException(`Gateway disconnect request failed: ${response.status} ${responseText}`);
}
}
}
+102
View File
@@ -0,0 +1,102 @@
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { Queue } from 'bullmq';
import IORedis from 'ioredis';
import { Prisma } from '@prisma/client';
import { randomUUID } from 'crypto';
import { assertMoneyUnits, moneyToNumber } from '../common/money';
import { PrismaService } from '../prisma/prisma.service';
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
/** R5 channel domain service composed behind ChannelsService. */
export class ChannelCopyService {
constructor(private readonly prisma: PrismaService) {}
async copyChannel(channelId: string, data: CopyChannelDto = {}) {
const source = await this.prisma.smsChannel.findUnique({
where: { id: channelId },
include: { reportFields: true },
});
if (!source) {
throw new NotFoundException('Channel not found');
}
const suffix = Date.now().toString(36).toUpperCase();
const nextName = data.name ?? `${source.name}副本`;
const nextCode = data.code ?? `${source.code}-COPY-${suffix}`;
const copied = await this.prisma.$transaction(async (tx) => {
const nextChannel = await tx.smsChannel.create({
data: {
code: nextCode,
name: nextName,
carrier: source.carrier,
carriers: source.carriers,
protocol: source.protocol,
gatewayHost: source.gatewayHost,
gatewayPort: source.gatewayPort,
enterpriseCode: source.enterpriseCode,
account: source.account,
passwordCipher: source.passwordCipher,
srcId: source.srcId,
sendRegion: source.sendRegion,
cmppVersion: source.cmppVersion,
rateLimitPerSecond: source.rateLimitPerSecond,
unitPrice: source.unitPrice,
status: 'disabled',
config: source.config as Prisma.InputJsonValue | undefined,
reportFields: {
create: source.reportFields.map((field) => ({
drainageFieldId: field.drainageFieldId,
reportType: field.reportType,
code: field.code,
name: field.name,
fieldType: field.fieldType,
required: field.required,
description: field.description,
sortOrder: field.sortOrder,
status: field.status,
})),
},
},
include: { reportFields: true },
});
const reportMaterials = await tx.signatureReportMaterial.findMany({ where: { channelId } });
if (reportMaterials.length > 0) {
await tx.signatureReportMaterial.createMany({
data: reportMaterials.map((material) => ({
signatureId: material.signatureId,
channelId: nextChannel.id,
fieldCode: material.fieldCode,
fieldValue: material.fieldValue,
fileObjectId: material.fileObjectId,
})),
skipDuplicates: true,
});
}
await tx.operationLog.create({
data: {
userId: data.operatorId,
action: 'sms_channel.copy',
resource: 'sms_channel',
resourceId: nextChannel.id,
detail: {
sourceChannelId: source.id,
sourceCode: source.code,
sourceStatus: source.status,
copiedStatus: 'disabled',
copiedReportFields: source.reportFields.length,
copiedReportMaterials: reportMaterials.length,
} as Prisma.InputJsonValue,
},
});
return nextChannel;
});
return copied;
}
}
@@ -0,0 +1,19 @@
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { Queue } from 'bullmq';
import IORedis from 'ioredis';
import { Prisma } from '@prisma/client';
import { randomUUID } from 'crypto';
import { assertMoneyUnits, moneyToNumber } from '../common/money';
import { PrismaService } from '../prisma/prisma.service';
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
import { ChannelConfigurationService } from './channel-configuration.service';
/** R5 channel domain service composed behind ChannelsService. */
export class ChannelDeletionService {
constructor(private readonly prisma: PrismaService, private readonly configuration: ChannelConfigurationService) {}
async deleteChannel(channelId: string, data: ChangeChannelStatusDto = { status: 'deleted' }) {
return this.configuration.changeChannelStatus(channelId, { ...data, status: 'deleted' });
}
}
@@ -0,0 +1,277 @@
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { Queue } from 'bullmq';
import IORedis from 'ioredis';
import { Prisma } from '@prisma/client';
import { randomUUID } from 'crypto';
import { assertMoneyUnits, moneyToNumber } from '../common/money';
import { PrismaService } from '../prisma/prisma.service';
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
/** R5 channel domain service composed behind ChannelsService. */
export class ChannelGroupRoutingService {
constructor(private readonly prisma: PrismaService) {}
listGroups() {
return this.prisma.smsChannelGroup.findMany({
where: { status: { not: 'deleted' } },
include: { items: { include: { channel: { include: { connectionStates: true } } }, orderBy: [{ province: 'asc' }, { priority: 'asc' }] } },
orderBy: { createdAt: 'desc' },
});
}
createGroup(data: CreateChannelGroupDto) {
const retryTimeLimitMinutes = normalizeRetryTimeLimitMinutes(data.retryTimeLimitMinutes, data.retryTimeLimitHours, 720);
const carrier = normalizeBusinessCarrier(data.carrier);
return this.prisma.smsChannelGroup.create({
data: {
code: data.code,
name: data.name,
carrier,
description: data.description,
status: data.status ?? 'active',
retryEnabled: data.retryEnabled ?? true,
retryTimeLimitHours: Math.ceil(retryTimeLimitMinutes / 60),
retryTimeLimitMinutes,
},
});
}
async addGroupItem(data: CreateChannelGroupItemDto) {
const group = await this.prisma.smsChannelGroup.findUnique({ where: { id: data.groupId } });
if (!group) {
throw new NotFoundException('Channel group not found');
}
const groupCarrier = normalizeBusinessCarrier(group.carrier);
const itemCarrier = data.carrier ? normalizeBusinessCarrier(data.carrier) : groupCarrier;
if (itemCarrier !== groupCarrier) {
throw new BadRequestException('Channel group items must use the same carrier as the channel group');
}
const channel = await this.prisma.smsChannel.findUnique({ where: { id: data.channelId } });
if (!channel) {
throw new NotFoundException('Channel not found');
}
if (!isChannelCarrierCompatible(channel.carrier, groupCarrier, channel.carriers)) {
throw new BadRequestException('Channel carrier is not compatible with the channel group carrier');
}
if (data.province && !isRegionCompatible(channel.sendRegion, data.province)) {
throw new BadRequestException('Province route must use a channel with the same sendRegion');
}
const existing = await this.prisma.smsChannelGroupItem.findFirst({
where: { groupId: data.groupId, channelId: data.channelId },
});
if (existing) {
throw new BadRequestException('通道组内不能重复配置同一通道');
}
if (data.province) {
const existingProvince = await this.prisma.smsChannelGroupItem.findFirst({
where: { groupId: data.groupId, province: data.province },
});
if (existingProvince) {
throw new BadRequestException('同一通道组内同一省份只能配置一个通道');
}
} else {
const existingPriority = await this.prisma.smsChannelGroupItem.findFirst({
where: { groupId: data.groupId, province: null, priority: data.priority ?? 100 },
});
if (existingPriority) {
throw new BadRequestException('同一通道组内全国通道优先级不能重复');
}
}
return this.prisma.smsChannelGroupItem.create({
data: {
groupId: data.groupId,
channelId: data.channelId,
carrier: itemCarrier,
province: data.province,
priority: data.priority ?? 100,
weight: data.weight ?? 1,
isBackup: data.isBackup ?? false,
},
});
}
async updateGroup(groupId: string, data: UpdateChannelGroupDto) {
const current = await this.prisma.smsChannelGroup.findUnique({
where: { id: groupId },
include: { items: { include: { channel: true }, orderBy: [{ province: 'asc' }, { priority: 'asc' }] } },
});
if (!current) {
throw new NotFoundException('Channel group not found');
}
const retryTimeLimitMinutes = normalizeRetryTimeLimitMinutes(
data.retryTimeLimitMinutes,
data.retryTimeLimitHours,
current.retryTimeLimitMinutes ?? current.retryTimeLimitHours * 60,
);
const carrier = data.carrier ? normalizeBusinessCarrier(data.carrier) : normalizeBusinessCarrier(current.carrier);
const items = data.items ?? [];
const channelIds = [...new Set(items.map((item) => item.channelId))];
const channels = await this.prisma.smsChannel.findMany({ where: { id: { in: channelIds } } });
const channelById = new Map(channels.map((channel) => [channel.id, channel]));
validateGroupItems(carrier, items, channelById);
return this.prisma.$transaction(async (tx) => {
await tx.smsChannelGroupItem.deleteMany({ where: { groupId } });
await tx.smsChannelGroup.update({
where: { id: groupId },
data: {
code: data.code ?? current.code,
name: data.name ?? current.name,
carrier,
description: data.description,
status: data.status ?? current.status,
retryEnabled: data.retryEnabled ?? current.retryEnabled,
retryTimeLimitHours: Math.ceil(retryTimeLimitMinutes / 60),
retryTimeLimitMinutes,
},
});
if (items.length > 0) {
await tx.smsChannelGroupItem.createMany({
data: items.map((item) => ({
groupId,
channelId: item.channelId,
carrier,
province: item.province,
priority: item.priority ?? 100,
weight: item.weight ?? 1,
isBackup: item.isBackup ?? false,
})),
});
}
const updated = await tx.smsChannelGroup.findUnique({
where: { id: groupId },
include: { items: { include: { channel: true }, orderBy: [{ province: 'asc' }, { priority: 'asc' }] } },
});
await tx.operationLog.create({
data: {
action: 'sms_channel_group.update',
resource: 'sms_channel_group',
resourceId: groupId,
detail: {
before: channelGroupAuditSnapshot(current),
after: updated ? channelGroupAuditSnapshot(updated) : null,
} as Prisma.InputJsonValue,
},
});
return updated;
});
}
async getGroupDeletionImpact(groupId: string) {
const group = await this.prisma.smsChannelGroup.findUnique({
where: { id: groupId },
select: { id: true, name: true, items: { select: { id: true } } },
});
if (!group) {
throw new NotFoundException('Channel group not found');
}
const routes = await this.prisma.channelRouteRule.findMany({
where: { groupId, applicationId: { not: null }, status: { not: 'deleted' } },
select: { applicationId: true },
});
const applicationIds = [...new Set(routes.flatMap((route) => route.applicationId ? [route.applicationId] : []))];
const [applications, pendingSupplierSubmitCount] = await Promise.all([
this.prisma.smsApplication.findMany({
where: { id: { in: applicationIds } },
select: { id: true, status: true },
}),
this.prisma.smsSubmitRecord.count({
where: { channelGroupId: groupId, submitStatus: 'queued' },
}),
]);
const applicationStatusById = new Map(applications.map((application) => [application.id, application.status]));
const deletedApplicationCount = applicationIds.filter((applicationId) => {
const status = applicationStatusById.get(applicationId);
return status === undefined || status === 'deleted';
}).length;
return {
groupId: group.id,
groupName: group.name,
normalApplicationCount: applicationIds.length - deletedApplicationCount,
deletedApplicationCount,
channelCount: group.items.length,
pendingSupplierSubmitCount,
};
}
async deleteGroup(groupId: string) {
const group = await this.prisma.smsChannelGroup.findUnique({
where: { id: groupId },
include: { items: { include: { channel: true }, orderBy: [{ province: 'asc' }, { priority: 'asc' }] } },
});
if (!group) {
throw new NotFoundException('Channel group not found');
}
if (group.status === 'deleted') {
return group;
}
const impact = await this.getGroupDeletionImpact(groupId);
// Logical deletion keeps group items and route bindings available for historical
// receipts and uplink access-number matching; new submits already require an active group.
return this.prisma.$transaction(async (tx) => {
const deleted = await tx.smsChannelGroup.update({
where: { id: groupId },
data: { status: 'deleted' },
});
await tx.operationLog.create({
data: {
action: 'sms_channel_group.delete',
resource: 'sms_channel_group',
resourceId: groupId,
detail: {
before: channelGroupAuditSnapshot(group),
impact,
deletionMode: 'soft_delete',
} as Prisma.InputJsonValue,
},
});
return deleted;
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
}
listRouteRules() {
return this.prisma.channelRouteRule.findMany({
include: { group: true, channel: true },
orderBy: [{ priority: 'asc' }, { createdAt: 'desc' }],
});
}
async createRouteRule(data: CreateRouteRuleDto) {
if (!data.applicationId) {
throw new BadRequestException('applicationId is required for channel group routing');
}
if (!data.carrier) {
throw new BadRequestException('carrier is required for application channel group routing');
}
const carrier = normalizeBusinessCarrier(data.carrier);
if (data.channelId) {
throw new BadRequestException('Route rules can only bind channel groups, not single channels');
}
if (data.province) {
throw new BadRequestException('Province routing must be configured inside the channel group');
}
const group = await this.prisma.smsChannelGroup.findUnique({ where: { id: data.groupId } });
if (!group) {
throw new NotFoundException('Channel group not found');
}
if (normalizeBusinessCarrier(group.carrier) !== carrier) {
throw new BadRequestException('Route rule carrier must match the channel group carrier');
}
return this.prisma.channelRouteRule.create({
data: {
tenantId: data.tenantId,
applicationId: data.applicationId,
groupId: data.groupId,
channelId: undefined,
carrier,
province: undefined,
priority: data.priority ?? 100,
status: data.status ?? 'active',
},
});
}
}
@@ -0,0 +1,935 @@
import { selectDrainageReportTask } from '../common/drainage-report-task';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import type {
CreateReportFieldDto,
ReplaceReportFieldsDto,
CreateReportMaterialDto,
CreateReportTaskDto,
ChangeReportTaskStatusesDto,
CreateReportExportDto,
CreateReceiptImportDto,
} from './channels.contracts';
import {
parseReceiptContent,
deriveReceiptStatus,
ChannelReportDeliveryRow,
summarizeChannelReportDelivery,
latestDate,
currentShanghaiDayRange,
normalizeSpreadsheetSize,
normalizeBusinessCarrier,
normalizeChannelCarriers,
normalizeReportType,
summarizeReportStatuses,
} from './channels.helpers';
/** R5 channel domain service composed behind ChannelsService. */
export class ChannelReportingService {
constructor(private readonly prisma: PrismaService) {}
listReportFields(channelId?: string) {
return this.prisma.channelReportField.findMany({
where: channelId ? { channelId } : undefined,
include: { drainageField: true },
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
});
}
async createReportField(data: CreateReportFieldDto) {
if (!data.drainageFieldId) throw new BadRequestException('drainageFieldId is required');
const field = await this.prisma.drainageField.findUnique({ where: { id: data.drainageFieldId } });
if (!field || field.status !== 'active') {
throw new BadRequestException('报备字段库字段不存在或已停用');
}
const reportType = normalizeReportType(data.reportType);
return this.prisma.channelReportField.create({
data: {
channelId: data.channelId,
drainageFieldId: field.id,
reportType,
code: field.code,
name: field.name,
exportName: data.exportName?.trim() || field.name,
fieldType: field.fieldType,
required: data.required ?? field.required,
description: data.description ?? field.description,
sortOrder: data.sortOrder ?? 100,
columnWidth: normalizeSpreadsheetSize(data.columnWidth, 18, 6, 80),
imageWidth: normalizeSpreadsheetSize(data.imageWidth, 120, 24, 600),
imageHeight: normalizeSpreadsheetSize(data.imageHeight, 80, 24, 600),
defaultValue: data.defaultValue,
transform: data.transform,
status: data.status ?? 'active',
},
});
}
async replaceReportFields(channelId: string, reportType: 'signature' | 'drainage', data: ReplaceReportFieldsDto) {
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId } });
if (!channel) throw new NotFoundException('Channel not found');
const ids = data.fields.map((field) => field.drainageFieldId);
if (new Set(ids).size !== ids.length) throw new BadRequestException('同一通道报备类型不能重复配置字段');
const libraryFields = await this.prisma.drainageField.findMany({ where: { id: { in: ids }, status: 'active' } });
if (libraryFields.length !== ids.length) throw new BadRequestException('报备字段库字段不存在或已停用');
const fieldById = new Map(libraryFields.map((field) => [field.id, field]));
return this.prisma.$transaction(async (tx) => {
const oppositeType = reportType === 'signature' ? 'drainage' : 'signature';
const [legacyBoth, oppositeFields] = await Promise.all([
tx.channelReportField.findMany({ where: { channelId, reportType: 'both' } }),
tx.channelReportField.findMany({ where: { channelId, reportType: oppositeType } }),
]);
const oppositeCodes = new Set(oppositeFields.map((field) => field.code));
await tx.channelReportField.deleteMany({ where: { channelId, reportType: { in: [reportType, 'both'] } } });
for (const legacy of legacyBoth) {
if (oppositeCodes.has(legacy.code)) continue;
const { id: _id, createdAt: _createdAt, updatedAt: _updatedAt, ...legacyData } = legacy;
void _id;
void _createdAt;
void _updatedAt;
await tx.channelReportField.create({ data: { ...legacyData, reportType: oppositeType } });
}
for (const [index, configured] of data.fields.entries()) {
const field = fieldById.get(configured.drainageFieldId)!;
await tx.channelReportField.create({
data: {
channelId,
drainageFieldId: field.id,
reportType,
code: field.code,
name: field.name,
exportName: configured.exportName?.trim() || field.name,
fieldType: field.fieldType,
required: configured.required ?? field.required,
description: configured.description ?? field.description,
sortOrder: configured.sortOrder ?? (index + 1) * 10,
columnWidth: normalizeSpreadsheetSize(configured.columnWidth, 18, 6, 80),
imageWidth: normalizeSpreadsheetSize(configured.imageWidth, 120, 24, 600),
imageHeight: normalizeSpreadsheetSize(configured.imageHeight, 80, 24, 600),
defaultValue: configured.defaultValue,
transform: configured.transform,
status: configured.status ?? 'active',
},
});
}
return tx.channelReportField.findMany({
where: { channelId, reportType },
include: { drainageField: true },
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }],
});
});
}
listReportMaterials(signatureId?: string, channelId?: string) {
return this.prisma.signatureReportMaterial.findMany({
where: {
signatureId,
channelId,
},
orderBy: { createdAt: 'desc' },
});
}
upsertReportMaterial(data: CreateReportMaterialDto) {
return this.prisma.signatureReportMaterial.upsert({
where: {
signatureId_channelId_fieldCode: {
signatureId: data.signatureId,
channelId: data.channelId,
fieldCode: data.fieldCode,
},
},
update: {
fieldValue: data.fieldValue,
fileObjectId: data.fileObjectId,
},
create: {
signatureId: data.signatureId,
channelId: data.channelId,
fieldCode: data.fieldCode,
fieldValue: data.fieldValue,
fileObjectId: data.fileObjectId,
},
});
}
async listReportTasks(tenantId?: string, status?: string, channelId?: string, reportType?: string) {
const tasks = await this.prisma.channelSignatureReportTask.findMany({
where: {
tenantId,
status:
status === 'reporting' || status === 'exporting'
? { in: ['reporting', 'exporting'] }
: status === 'failed'
? { in: ['failed', 'rejected'] }
: status,
channelId,
reportType,
signature: { auditStatus: { not: 'deleted' } },
},
include: {
signature: { include: { tenant: true, application: true } },
channel: true,
drainageInfo: true,
exportItems: {
include: { exportFile: true, batchItem: { include: { batch: true } } },
orderBy: { id: 'desc' },
take: 1,
},
records: { orderBy: { createdAt: 'desc' }, take: 20 },
},
orderBy: { createdAt: 'desc' },
});
if (tasks.length === 0) {
return tasks;
}
const channelIds = [...new Set(tasks.map((task) => task.channelId))];
const signatureIds = [...new Set(tasks.map((task) => task.signatureId))];
const day = currentShanghaiDayRange();
const rows = await this.prisma.$queryRaw<ChannelReportDeliveryRow[]>(Prisma.sql`
WITH base AS (
SELECT
submit."channelId" AS channel_id,
message."signatureId" AS signature_id,
message.carrier AS carrier,
message."drainageInfoId" AS drainage_info_id,
CASE WHEN COALESCE(submit."drainageGate", message."drainageGate") IS NULL THEN NULL ELSE ARRAY(
SELECT DISTINCT material_id FROM jsonb_array_elements(COALESCE(COALESCE(submit."drainageGate", message."drainageGate")->'targets', '[]'::jsonb)) target
CROSS JOIN LATERAL jsonb_array_elements_text(target->'materialIds') AS ids(material_id)
) END AS drainage_ids,
submit."submitStatus" AS submit_status,
COALESCE(submit."submittedAt", submit."createdAt") AS attempted_at,
CASE
WHEN segment_summary.segment_count > 0
AND segment_summary.delivered_count = segment_summary.segment_count
THEN segment_summary.completed_at
WHEN segment_summary.segment_count = 0 THEN delivered_receipt.delivered_at
END AS successful_at,
CASE
WHEN submit."submitStatus" <> 'accepted' THEN 'submit_failed'
WHEN segment_summary.segment_count > 0 AND segment_summary.failure_count > 0 THEN 'failure'
WHEN segment_summary.segment_count > 0
AND segment_summary.delivered_count = segment_summary.segment_count THEN 'success'
WHEN segment_summary.segment_count = 0 AND failed_receipt.failed_at IS NOT NULL THEN 'failure'
WHEN segment_summary.segment_count = 0 AND delivered_receipt.delivered_at IS NOT NULL THEN 'success'
ELSE 'unknown'
END AS delivery_status
FROM "SmsSubmitRecord" submit
JOIN "SmsMessageRecord" message ON message.id = submit."messageRecordId"
LEFT JOIN LATERAL (
SELECT
COUNT(*)::integer AS segment_count,
COUNT(*) FILTER (WHERE segment."receiptStatus" = 'delivered')::integer AS delivered_count,
COUNT(*) FILTER (WHERE segment."receiptStatus" = 'undelivered')::integer AS failure_count,
MAX(segment."deliveredAt") FILTER (WHERE segment."receiptStatus" = 'delivered') AS completed_at
FROM "SmsMessageSegmentAudit" segment
WHERE segment."submitRecordId" = submit.id
) segment_summary ON TRUE
LEFT JOIN LATERAL (
SELECT MIN(receipt."deliveredAt") AS delivered_at
FROM "SmsReceiptRecord" receipt
WHERE receipt."gatewayMessageId" = submit."gatewayMessageId"
AND receipt."channelId" = submit."channelId"
AND receipt."receiptStatus" = 'delivered'
) delivered_receipt ON TRUE
LEFT JOIN LATERAL (
SELECT MIN(receipt."deliveredAt") AS failed_at
FROM "SmsReceiptRecord" receipt
WHERE receipt."gatewayMessageId" = submit."gatewayMessageId"
AND receipt."channelId" = submit."channelId"
AND receipt."receiptStatus" = 'undelivered'
) failed_receipt ON TRUE
WHERE submit."submitStatus" IN ('accepted', 'rejected', 'timeout')
AND NOT (COALESCE(submit."errorCode", '') LIKE 'DRN%' AND submit."firstWireSubmitAt" IS NULL)
AND submit."channelId" IN (${Prisma.join(channelIds)})
AND message."signatureId" IN (${Prisma.join(signatureIds)})
)
SELECT
channel_id AS "channelId",
signature_id AS "signatureId",
carrier,
drainage_info_id AS "drainageInfoId",
drainage_ids AS "drainageIds",
COUNT(*) FILTER (
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
)::integer AS total,
COUNT(*) FILTER (
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
AND submit_status = 'accepted'
)::integer AS "acceptedCount",
COUNT(*) FILTER (
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
AND delivery_status = 'submit_failed'
)::integer AS "submitFailureCount",
COUNT(*) FILTER (
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
AND delivery_status = 'success'
)::integer AS "successCount",
COUNT(*) FILTER (
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
AND delivery_status = 'unknown'
)::integer AS "unknownCount",
COUNT(*) FILTER (
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
AND delivery_status = 'failure'
)::integer AS "failureCount",
MAX(successful_at) FILTER (WHERE delivery_status = 'success') AS "lastSuccessfulSentAt"
FROM base
GROUP BY channel_id, signature_id, drainage_info_id, carrier, drainage_ids
`);
return tasks.map((task) => {
const taskRows = rows.filter(
(row) =>
row.channelId === task.channelId &&
row.signatureId === task.signatureId &&
(!task.carrier || row.carrier === task.carrier) &&
((task.reportType ?? 'signature') === 'signature' ||
(row.drainageIds
? row.drainageIds.includes(task.drainageItemId ?? '')
: row.drainageInfoId === task.drainageItemId)),
);
const deliveryStats = summarizeChannelReportDelivery(taskRows);
return {
...task,
deliveryStats,
lastSuccessfulSentAt: latestDate(taskRows.map((row) => row.lastSuccessfulSentAt)),
};
});
}
async listReportTasksPage(query: {
tenantId?: string;
applicationId?: string;
status?: string;
channelId?: string;
reportType?: string;
keyword?: string;
carrier?: string;
todaySendMin?: number;
todaySendMax?: number;
sort?: string;
createdAtFrom?: string;
createdAtTo?: string;
page?: number;
pageSize?: number;
}) {
const page = Math.max(1, Math.floor(Number(query.page) || 1));
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
const keyword = query.keyword?.trim();
const from = query.createdAtFrom ? new Date(`${query.createdAtFrom}T00:00:00+08:00`) : undefined;
const to = query.createdAtTo ? new Date(`${query.createdAtTo}T23:59:59.999+08:00`) : undefined;
const all = await this.listReportTasks(query.tenantId, query.status, query.channelId, query.reportType);
const filtered = all.filter((task) => {
const createdAt = task.createdAt instanceof Date ? task.createdAt : new Date(task.createdAt);
const total = (task as typeof task & { deliveryStats?: { total: number } }).deliveryStats?.total ?? 0;
if (query.applicationId && task.signature.applicationId !== query.applicationId) return false;
if (query.carrier && task.carrier !== query.carrier) return false;
if (from && createdAt < from) return false;
if (to && createdAt > to) return false;
if (Number.isFinite(query.todaySendMin) && total < Number(query.todaySendMin)) return false;
if (Number.isFinite(query.todaySendMax) && total > Number(query.todaySendMax)) return false;
if (!keyword) return true;
return [
task.id,
task.channel.name,
task.signature.name,
task.signature.tenant.name,
task.signature.application?.name,
task.drainageInfo?.siteName,
task.drainageInfo?.url,
].some((value) => String(value ?? '').includes(keyword));
});
filtered.sort((left, right) =>
query.sort === 'todaySendDesc'
? ((right as typeof right & { deliveryStats?: { total: number } }).deliveryStats?.total ?? 0) -
((left as typeof left & { deliveryStats?: { total: number } }).deliveryStats?.total ?? 0) ||
right.updatedAt.getTime() - left.updatedAt.getTime()
: right.createdAt.getTime() - left.createdAt.getTime(),
);
return { items: filtered.slice((page - 1) * pageSize, page * pageSize), total: filtered.length, page, pageSize };
}
async listReportDetailsPage(query: {
tenantId?: string;
applicationId?: string;
signatureId?: string;
channelId?: string;
carrier?: string;
status?: string;
reportType?: string;
keyword?: string;
createdAtFrom?: string;
createdAtTo?: string;
page?: number;
pageSize?: number;
}) {
const page = Math.max(1, Math.floor(Number(query.page) || 1));
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
const signatures = await this.prisma.smsSignature.findMany({
where: {
id: query.signatureId,
tenantId: query.tenantId,
applicationId: query.applicationId,
auditStatus: 'approved',
},
include: {
tenant: true,
application: true,
drainageItems: { where: { auditStatus: 'approved' } },
reportTasks: {
include: {
channel: true,
drainageInfo: true,
exportItems: {
include: { exportFile: true, batchItem: { include: { batch: true } } },
orderBy: { id: 'desc' },
take: 1,
},
records: { orderBy: { createdAt: 'desc' }, take: 20 },
},
},
},
orderBy: [{ updatedAt: 'desc' }, { id: 'desc' }],
});
const applicationIds = [
...new Set(signatures.map((item) => item.applicationId).filter((id): id is string => Boolean(id))),
];
const routes = applicationIds.length
? await this.prisma.channelRouteRule.findMany({
where: { applicationId: { in: applicationIds }, status: 'active' },
include: { group: { include: { items: { include: { channel: true } } } } },
})
: [];
const details = signatures
.flatMap((signature) => {
const channels = [
...new Map(
routes
.filter((route) => route.applicationId === signature.applicationId && route.group.status === 'active')
.flatMap((route) => route.group.items.map((item) => item.channel))
.filter((channel) => channel.status === 'active')
.map((channel) => [channel.id, channel]),
).values(),
];
const signatureDetails = channels.flatMap((channel) =>
normalizeChannelCarriers(channel.carriers, channel.carrier).map((carrier) => {
const existing = signature.reportTasks.find(
(task) =>
task.reportType === 'signature' &&
task.channelId === channel.id &&
(task.carrier === carrier || (!task.carrier && task.approvalScope === 'legacy_channel')),
);
return existing
? { ...existing, signature }
: {
id: `virtual:${signature.id}:${channel.id}:${carrier}`,
tenantId: signature.tenantId,
signatureId: signature.id,
channelId: channel.id,
carrier,
approvalScope: 'carrier_specific',
reportType: 'signature',
drainageItemId: null,
status: 'pending',
reason: null,
approvedAt: null,
createdAt: signature.reportChangedAt ?? signature.updatedAt,
updatedAt: signature.reportChangedAt ?? signature.updatedAt,
createdById: null,
signature,
channel,
drainageInfo: null,
exportItems: [],
records: [],
virtual: true,
};
}),
);
const drainageDetails = signature.drainageItems.flatMap((drainageInfo) =>
channels.flatMap((channel) =>
normalizeChannelCarriers(channel.carriers, channel.carrier).flatMap((carrier) => {
const tasks = signature.reportTasks.filter(
(task) => task.reportType === 'drainage' && task.drainageItemId === drainageInfo.id,
);
const existing = selectDrainageReportTask(tasks, channel.id, carrier);
return existing
? [
{
...existing,
id: existing.carrier ? existing.id : `virtual:${drainageInfo.id}:${channel.id}:${carrier}`,
carrier,
virtual: !existing.carrier,
signature,
},
]
: [];
}),
),
);
return [...signatureDetails, ...drainageDetails];
})
.filter((task) => {
if (!task) return false;
if (query.channelId && task.channelId !== query.channelId) return false;
if (query.carrier && task.carrier !== query.carrier) return false;
if (query.status && task.status !== query.status) return false;
if (query.reportType && task.reportType !== query.reportType) return false;
const changedAt = new Date(task.updatedAt);
if (query.createdAtFrom && changedAt < new Date(`${query.createdAtFrom}T00:00:00+08:00`)) return false;
if (query.createdAtTo && changedAt > new Date(`${query.createdAtTo}T23:59:59.999+08:00`)) return false;
if (!query.keyword?.trim()) return true;
const keyword = query.keyword.trim();
return [
task.id,
task.signature.name,
task.signature.tenant.name,
task.signature.application?.name,
task.channel.name,
task.drainageInfo?.siteName,
task.drainageInfo?.url,
].some((value) => String(value ?? '').includes(keyword));
});
return { items: details.slice((page - 1) * pageSize, page * pageSize), total: details.length, page, pageSize };
}
async createReportTask(data: CreateReportTaskDto) {
const reportType = data.reportType ?? 'signature';
if (reportType === 'drainage' && !data.drainageItemId) throw new BadRequestException('drainageItemId is required');
if (reportType === 'drainage') {
const drainageInfo = await this.prisma.smsDrainageInfo.findUnique({ where: { id: data.drainageItemId! } });
if (!drainageInfo || drainageInfo.signatureId !== data.signatureId)
throw new NotFoundException('Drainage info not found');
if (drainageInfo.auditStatus !== 'approved') throw new BadRequestException('引流信息审核通过后才能进入通道报备');
throw new BadRequestException('引流信息通道报备任务由运营审核通过后按应用路由自动生成');
}
const channel = await this.prisma.smsChannel.findUnique({ where: { id: data.channelId } });
if (!channel) throw new NotFoundException('Channel not found');
if (!data.carrier) throw new BadRequestException('签名报备任务必须指定运营商');
const carrier = normalizeBusinessCarrier(data.carrier);
if (!normalizeChannelCarriers(channel.carriers, channel.carrier).includes(carrier)) {
throw new BadRequestException('报备运营商不在通道支持范围内');
}
const existing = await this.prisma.channelSignatureReportTask.findFirst({
where: {
signatureId: data.signatureId,
channelId: data.channelId,
carrier,
reportType: 'signature',
drainageItemId: null,
},
});
if (existing) throw new BadRequestException('该签名在当前通道和运营商下已存在报备任务');
const task = await this.prisma.channelSignatureReportTask.create({
data: {
tenantId: data.tenantId,
signatureId: data.signatureId,
channelId: data.channelId,
carrier,
approvalScope: 'carrier_specific',
reportType,
drainageItemId: undefined,
createdById: data.createdById,
status: 'pending',
},
});
await this.recordReportTask(task.id, task.channelId, 'create', undefined, 'pending');
return task;
}
async changeReportTaskStatuses(data: ChangeReportTaskStatusesDto) {
if (!data.items.length) throw new BadRequestException('items is required');
const allowed = new Set([
'pending',
'waiting_material',
'reporting',
'approved',
'failed',
'rejected',
'abandoned',
]);
for (const item of data.items) {
if (!allowed.has(item.status)) throw new BadRequestException('unsupported report task status');
}
const sourceEntry = data.sourceEntry ?? 'report_task';
if (!['enterprise_signature', 'report_task', 'channel_report'].includes(sourceEntry)) {
throw new BadRequestException('unsupported report task source entry');
}
return this.prisma.$transaction(async (tx) => {
for (const signatureId of [...new Set(data.items.map((item) => item.signatureId))].sort()) {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${signatureId}, 910))`;
}
const signatureIds = [
...new Set(
data.items.filter((item) => (item.reportType ?? 'signature') === 'signature').map((item) => item.signatureId),
),
];
const drainageResults: Array<{
signatureId: string;
reportType: 'drainage';
drainageItemId: string;
channelId: string;
carrier: string | null;
status: string;
}> = [];
for (const item of data.items) {
const reportType = item.reportType ?? 'signature';
if (reportType === 'drainage' && !item.drainageItemId)
throw new BadRequestException('drainageItemId is required');
const signature = await tx.smsSignature.findUnique({ where: { id: item.signatureId } });
const channel = await tx.smsChannel.findUnique({ where: { id: item.channelId } });
if (!signature || !channel) throw new NotFoundException('Signature or channel not found');
if (reportType === 'drainage') {
const drainageInfo = await tx.smsDrainageInfo.findUnique({ where: { id: item.drainageItemId! } });
if (!drainageInfo || drainageInfo.signatureId !== item.signatureId)
throw new NotFoundException('Drainage info not found');
if (drainageInfo.auditStatus !== 'approved')
throw new BadRequestException('引流信息审核通过后才能修改通道报备状态');
}
const carrier = item.carrier ? normalizeBusinessCarrier(item.carrier) : null;
if (carrier && !normalizeChannelCarriers(channel.carriers, channel.carrier).includes(carrier)) {
throw new BadRequestException('报备运营商不在通道支持范围内');
}
const existing = await tx.channelSignatureReportTask.findFirst({
where: {
signatureId: item.signatureId,
channelId: item.channelId,
reportType,
drainageItemId: reportType === 'drainage' ? item.drainageItemId : null,
carrier,
},
});
if (reportType === 'drainage' && !existing) {
const legacy = carrier
? await tx.channelSignatureReportTask.findFirst({
where: {
signatureId: item.signatureId,
channelId: item.channelId,
reportType,
drainageItemId: item.drainageItemId,
carrier: null,
},
})
: null;
if (!legacy) throw new BadRequestException('引流信息通道报备任务不存在,请先完成运营审核');
}
if (reportType === 'signature' && !carrier && !existing)
throw new BadRequestException('签名报备状态必须指定运营商');
const approvedAt =
item.status === 'approved'
? existing?.status === 'approved'
? (existing.approvedAt ?? new Date())
: new Date()
: null;
const task = existing
? await tx.channelSignatureReportTask.update({
where: { id: existing.id },
data: { status: item.status, reason: data.reason, approvedAt },
})
: await tx.channelSignatureReportTask.create({
data: {
tenantId: signature.tenantId,
signatureId: item.signatureId,
channelId: item.channelId,
carrier,
approvalScope: 'carrier_specific',
approvedAt,
reportType,
drainageItemId: reportType === 'drainage' ? item.drainageItemId : undefined,
status: item.status,
reason: data.reason,
createdById: data.operatorId,
},
});
await tx.channelSignatureReportRecord.create({
data: {
taskId: task.id,
channelId: item.channelId,
action: 'manual_status_change',
statusBefore: existing?.status,
statusAfter: item.status,
reason: data.reason,
operatorId: data.operatorId,
sourceEntry,
},
});
if (reportType === 'drainage')
drainageResults.push({
signatureId: item.signatureId,
reportType,
drainageItemId: item.drainageItemId!,
channelId: item.channelId,
carrier,
status: item.status,
});
}
const summaries = [];
for (const signatureId of signatureIds)
summaries.push(await this.recomputeSignatureReportSummary(tx, signatureId));
return [...summaries, ...drainageResults];
});
}
async recomputeSignatureReportSummary(tx: Prisma.TransactionClient, signatureId: string) {
const signature = await tx.smsSignature.findUnique({ where: { id: signatureId } });
if (!signature) throw new NotFoundException('Signature not found');
const routes = signature.applicationId
? await tx.channelRouteRule.findMany({
where: { applicationId: signature.applicationId, status: 'active' },
include: { group: { include: { items: { include: { channel: true } } } } },
})
: [];
const configuredChannels = routes
.flatMap((route) => route.group.items.map((item) => item.channel))
.filter((channel) => channel.status !== 'deleted');
const tasks = await tx.channelSignatureReportTask.findMany({
where: { signatureId, reportType: 'signature' },
include: { channel: true },
});
const channels = configuredChannels.length ? configuredChannels : tasks.map((task) => task.channel);
const uniqueChannels = [...new Map(channels.map((channel) => [channel.id, channel])).values()];
const carrierReportSummary = Object.fromEntries(
['mobile', 'unicom', 'telecom'].map((carrier) => {
const targets = uniqueChannels.filter((channel) =>
normalizeChannelCarriers(channel.carriers, channel.carrier).includes(carrier),
);
const statuses = targets.map((channel) => {
const task =
tasks.find((candidate) => candidate.channelId === channel.id && candidate.carrier === carrier) ??
tasks.find(
(candidate) =>
candidate.channelId === channel.id &&
candidate.carrier === null &&
candidate.approvalScope === 'legacy_channel',
);
return task?.status ?? 'pending';
});
return [carrier, summarizeReportStatuses(statuses)];
}),
);
const allStatuses = ['mobile', 'unicom', 'telecom'].flatMap((carrier) => {
const targets = uniqueChannels.filter((channel) =>
normalizeChannelCarriers(channel.carriers, channel.carrier).includes(carrier),
);
return targets.map(
(channel) =>
tasks.find((candidate) => candidate.channelId === channel.id && candidate.carrier === carrier)?.status ??
tasks.find(
(candidate) =>
candidate.channelId === channel.id &&
candidate.carrier === null &&
candidate.approvalScope === 'legacy_channel',
)?.status ??
'pending',
);
});
const reportStatus = summarizeReportStatuses(allStatuses).status;
await tx.smsSignature.update({ where: { id: signatureId }, data: { reportStatus } });
return { signatureId, reportStatus, carrierReportSummary };
}
async createReportExport(taskId: string, data: CreateReportExportDto) {
const task = await this.getReportTaskOrThrow(taskId);
const exported = await this.prisma.reportExportFile.create({
data: {
taskId,
fileObjectId: data.fileObjectId,
fileName: data.fileName,
rowCount: data.rowCount ?? 0,
},
});
await this.updateReportTaskStatus(taskId, task.channelId, task.status, 'exporting', 'export');
return exported;
}
async importReportReceipt(taskId: string, data: CreateReceiptImportDto) {
const task = await this.getReportTaskOrThrow(taskId);
const parsed = data.fileContent ? parseReceiptContent(data.fileContent, data.delimiter) : undefined;
const rowCount = data.rowCount ?? parsed?.rowCount ?? 0;
const successCount = data.successCount ?? parsed?.successCount ?? 0;
const failedCount = data.failedCount ?? parsed?.failedCount ?? 0;
const statusAfter = data.statusAfter ?? deriveReceiptStatus(rowCount, successCount, failedCount);
const imported = await this.prisma.reportReceiptImport.create({
data: {
taskId,
fileObjectId: data.fileObjectId,
fileName: data.fileName,
rowCount,
successCount,
failedCount,
status: 'imported',
result: (data.result ?? parsed?.result) as Prisma.InputJsonValue | undefined,
},
});
await this.updateReportTaskStatus(taskId, task.channelId, task.status, statusAfter, 'receipt_import', data.reason);
if ((task.reportType ?? 'signature') === 'signature') {
await this.recomputeSignatureReportSummary(this.prisma as unknown as Prisma.TransactionClient, task.signatureId);
}
return imported;
}
listReportRecords(taskId?: string, channelId?: string) {
return this.prisma.channelSignatureReportRecord.findMany({
where: { taskId, channelId },
include: { channel: true, task: { include: { signature: true, drainageInfo: true } } },
orderBy: { createdAt: 'desc' },
});
}
async listReportRecordsPage(query: {
taskId?: string;
channelId?: string;
batchNo?: string;
statusAfter?: string;
action?: string;
sourceEntry?: string;
operatorKeyword?: string;
keyword?: string;
reportType?: string;
createdAtFrom?: string;
createdAtTo?: string;
page?: number;
pageSize?: number;
}) {
const page = Math.max(1, Math.floor(Number(query.page) || 1));
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
const keyword = query.keyword?.trim();
const operatorKeyword = query.operatorKeyword?.trim();
const operatorIds = operatorKeyword
? (
await this.prisma.user.findMany({
where: {
OR: [{ username: { contains: operatorKeyword } }, { displayName: { contains: operatorKeyword } }],
},
select: { id: true },
})
).map((item) => item.id)
: undefined;
const where: Prisma.ChannelSignatureReportRecordWhereInput = {
taskId: query.taskId,
channelId: query.channelId,
statusAfter: query.statusAfter,
action: query.action,
sourceEntry: query.sourceEntry,
operatorId: operatorIds ? { in: operatorIds } : undefined,
task:
query.reportType || query.batchNo
? {
reportType: query.reportType,
exportItems: query.batchNo
? { some: { batchItem: { batch: { batchNo: { contains: query.batchNo.trim() } } } } }
: undefined,
}
: undefined,
createdAt:
query.createdAtFrom || query.createdAtTo
? {
gte: query.createdAtFrom ? new Date(`${query.createdAtFrom}T00:00:00+08:00`) : undefined,
lte: query.createdAtTo ? new Date(`${query.createdAtTo}T23:59:59.999+08:00`) : undefined,
}
: undefined,
OR: keyword
? [
{ taskId: { contains: keyword } },
{ action: { contains: keyword } },
{ reason: { contains: keyword } },
{ channel: { name: { contains: keyword } } },
{ task: { signature: { name: { contains: keyword } } } },
{ task: { drainageInfo: { siteName: { contains: keyword } } } },
{ task: { drainageInfo: { url: { contains: keyword } } } },
]
: undefined,
};
const [items, total] = await Promise.all([
this.prisma.channelSignatureReportRecord.findMany({
where,
include: { channel: true, task: { include: { signature: true, drainageInfo: true } } },
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
skip: (page - 1) * pageSize,
take: pageSize,
}),
this.prisma.channelSignatureReportRecord.count({ where }),
]);
const userIds = [...new Set(items.map((item) => item.operatorId).filter((id): id is string => Boolean(id)))];
const operators = userIds.length
? await this.prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, username: true, displayName: true },
})
: [];
const operatorMap = new Map(operators.map((item) => [item.id, item]));
return {
items: items.map((item) => ({
...item,
operator: item.operatorId ? operatorMap.get(item.operatorId) : undefined,
})),
total,
page,
pageSize,
};
}
async getReportTaskOrThrow(taskId: string) {
const task = await this.prisma.channelSignatureReportTask.findUnique({
where: { id: taskId },
include: { drainageInfo: true },
});
if (!task) {
throw new NotFoundException('Report task not found');
}
if (task.reportType === 'drainage' && task.drainageInfo?.auditStatus !== 'approved') {
throw new BadRequestException('引流信息审核通过后才能处理通道报备任务');
}
return task;
}
async updateReportTaskStatus(
taskId: string,
channelId: string,
statusBefore: string,
statusAfter: string,
action: string,
reason?: string,
) {
await this.prisma.channelSignatureReportTask.update({
where: { id: taskId },
data: {
status: statusAfter,
reason,
...((
await this.prisma.channelSignatureReportTask.findUnique({
where: { id: taskId },
select: { reportType: true, status: true, approvedAt: true },
})
)?.reportType === 'signature'
? { approvedAt: statusAfter === 'approved' ? (statusBefore === 'approved' ? undefined : new Date()) : null }
: {}),
},
});
await this.recordReportTask(taskId, channelId, action, statusBefore, statusAfter, reason);
}
recordReportTask(
taskId: string,
channelId: string,
action: string,
statusBefore: string | undefined,
statusAfter: string,
reason?: string,
) {
return this.prisma.channelSignatureReportRecord.create({
data: {
taskId,
channelId,
action,
statusBefore,
statusAfter,
reason,
},
});
}
}
+124
View File
@@ -0,0 +1,124 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { randomUUID } from 'crypto';
import { moneyToNumber } from '../common/money';
import { PrismaService } from '../prisma/prisma.service';
import type { TestChannelDto } from './channels.contracts';
import {
normalizeTestPhones,
normalizeTestContent,
normalizeGatewayConnectionStatus,
calculateBillingUnits,
buildChannelTestSubmitCommand,
} from './channels.helpers';
import { ChannelConnectionService } from './channel-connection.service';
/** R5 channel domain service composed behind ChannelsService. */
export class ChannelTestService {
constructor(
private readonly prisma: PrismaService,
private readonly connection: ChannelConnectionService,
) {}
async testChannel(channelId: string, data: TestChannelDto = {}) {
const phoneNumbers = normalizeTestPhones(data);
const content = normalizeTestContent(data.content);
const channel = await this.prisma.smsChannel.findUnique({
where: { id: channelId },
include: { connectionStates: true },
});
if (!channel) {
throw new NotFoundException('Channel not found');
}
if (channel.status !== 'active') {
throw new BadRequestException('通道未启用,不能发送测试短信');
}
const connectedState = channel.connectionStates.find(
(state) => normalizeGatewayConnectionStatus(state.status) === 'connected' && (state.currentConnections ?? 0) > 0,
);
if (!connectedState) {
throw new BadRequestException('通道当前没有可用 CMPP 连接,请先连接成功后再测试发送');
}
const createdAt = new Date();
const testNo = `CHTEST-${Date.now()}-${randomUUID().slice(0, 8)}`;
const results = [];
for (const [index, phoneNumber] of phoneNumbers.entries()) {
const messageId = `MSG-TEST-${Date.now()}-${randomUUID().slice(0, 8)}`;
const submitId = `SUB-TEST-${Date.now()}-${randomUUID().slice(0, 8)}`;
const session = await this.prisma.cmppSubmitSession.upsert({
where: { sessionNo: `OPEN-${channel.id}` },
update: { submitTotal: { increment: 1 } },
create: { channelId: channel.id, sessionNo: `OPEN-${channel.id}`, submitTotal: 1 },
});
const messageRecord = await this.prisma.smsMessageRecord.create({
data: {
messageId,
phoneNumber,
content,
billingUnits: calculateBillingUnits(content),
unitPrice: 0,
amountCents: 0,
queuePriority: 'normal',
channelId: channel.id,
submitId,
status: 'submit_queued',
submitStatus: 'queued',
},
});
await this.prisma.smsSubmitRecord.create({
data: {
messageRecordId: messageRecord.id,
channelId: channel.id,
sessionId: session.id,
submitId,
submitStatus: 'queued',
costUnitPrice: channel.unitPrice,
costAmountCents: moneyToNumber(channel.unitPrice) * messageRecord.billingUnits,
},
});
const command = buildChannelTestSubmitCommand({
channel,
content,
phoneNumber,
messageId,
submitId,
testNo,
attempt: index,
accessNo: data.accessNo,
});
await this.connection.getGatewaySubmitQueue().add('submit-command', command);
const streamMessageId = await this.connection.publishGatewaySubmitCommand(command);
results.push({
phoneNumber,
messageRecordId: messageRecord.id,
submitId,
streamMessageId,
});
}
await this.prisma.operationLog.create({
data: {
userId: data.operatorId,
action: 'sms_channel.test_submit',
resource: 'sms_channel',
resourceId: channel.id,
detail: {
testNo,
phoneTotal: phoneNumbers.length,
messageRecordIds: results.map((item) => item.messageRecordId),
connectionId: connectedState.connectionId,
} as Prisma.InputJsonValue,
},
});
return {
channelId,
status: 'submit_queued',
testNo,
submitted: results.length,
messages: results,
queuedAt: createdAt,
};
}
}
+176
View File
@@ -0,0 +1,176 @@
/** Stable request contracts shared by the channel controller and R5 domains. */
export interface CreateChannelDto {
code: string;
name: string;
carrier?: string;
carriers?: string[];
sendRegion?: string;
protocol?: string;
gatewayHost: string;
gatewayPort?: number;
enterpriseCode?: string;
account: string;
passwordCipher: string;
srcId: string;
cmppVersion?: string;
rateLimitPerSecond?: number;
unitPrice?: number;
status?: string;
desiredConnections?: number;
windowSize?: number;
heartbeatIntervalSeconds?: number;
heartbeatMissThreshold?: number;
config?: Record<string, unknown>;
}
export type UpdateChannelDto = Partial<CreateChannelDto>;
export interface CreateChannelGroupDto {
code: string;
name: string;
carrier: string;
description?: string;
status?: string;
retryEnabled?: boolean;
retryTimeLimitHours?: number;
retryTimeLimitMinutes?: number;
}
export interface CreateChannelGroupItemDto {
groupId: string;
channelId: string;
carrier?: string;
province?: string;
priority?: number;
weight?: number;
isBackup?: boolean;
}
export interface UpdateChannelGroupDto {
code?: string;
name?: string;
carrier?: string;
description?: string;
status?: string;
retryEnabled?: boolean;
retryTimeLimitHours?: number;
retryTimeLimitMinutes?: number;
items?: Array<Omit<CreateChannelGroupItemDto, 'groupId'>>;
}
export interface CreateRouteRuleDto {
tenantId?: string;
applicationId?: string;
groupId: string;
channelId?: string;
carrier?: string;
province?: string;
priority?: number;
status?: string;
}
export interface CreateReportFieldDto {
channelId: string;
drainageFieldId: string;
reportType: 'signature' | 'drainage' | 'both';
code?: string;
name?: string;
fieldType?: string;
required?: boolean;
description?: string;
sortOrder?: number;
exportName?: string;
columnWidth?: number;
imageWidth?: number;
imageHeight?: number;
defaultValue?: string;
transform?: string;
status?: string;
}
export interface ReplaceReportFieldsDto {
fields: Array<Omit<CreateReportFieldDto, 'channelId' | 'reportType'>>;
}
export interface CreateReportMaterialDto {
signatureId: string;
channelId: string;
fieldCode: string;
fieldValue?: string;
fileObjectId?: string;
}
export interface CreateReportTaskDto {
tenantId: string;
signatureId: string;
channelId: string;
carrier?: string;
reportType?: 'signature' | 'drainage';
drainageItemId?: string;
createdById?: string;
}
export interface ChangeReportTaskStatusesDto {
items: Array<{ signatureId: string; channelId: string; carrier?: string; status: string; reportType?: 'signature' | 'drainage'; drainageItemId?: string }>;
reason?: string;
operatorId?: string;
sourceEntry?: 'enterprise_signature' | 'report_task' | 'channel_report';
}
export interface CreateReportExportDto {
fileObjectId?: string;
fileName: string;
rowCount?: number;
}
export interface CreateReceiptImportDto {
fileObjectId?: string;
fileName: string;
fileContent?: string;
delimiter?: ',' | '\t';
rowCount?: number;
successCount?: number;
failedCount?: number;
statusAfter?: string;
reason?: string;
result?: Record<string, unknown>;
}
export interface UpsertConnectionStateDto {
tenantId?: string;
applicationId?: string;
channelId: string;
connectionId: string;
status: string;
desiredConnections?: number;
currentConnections?: number;
lastConnectedAt?: string;
lastDisconnectedAt?: string;
lastHeartbeatAt?: string;
reconnectCount?: number;
lastReconnectAttemptAt?: string;
nextReconnectAt?: string;
lastErrorCategory?: string;
lastError?: string;
}
export interface ChangeChannelStatusDto {
status: string;
operatorId?: string;
reason?: string;
}
export interface CopyChannelDto {
name?: string;
code?: string;
operatorId?: string;
}
export interface TestChannelDto {
phoneNumber?: string;
phones?: string[] | string;
content?: string;
accessNo?: string;
operatorId?: string;
}
+142 -12
View File
@@ -4,7 +4,6 @@ import { RequireRecentAuthentication } from '../auth/require-recent-authenticati
import { CurrentSessionUserId } from '../auth/current-session-user.decorator';
import { DeleteTargetDto, DeletionGovernanceService } from '../deletion-governance/deletion-governance.service';
import {
ChannelsService,
ChangeChannelStatusDto,
CopyChannelDto,
CreateChannelDto,
@@ -22,15 +21,25 @@ import {
UpsertConnectionStateDto,
UpdateChannelDto,
UpdateChannelGroupDto,
} from './channels.service';
} from './channels.contracts';
import { ChannelsService } from './channels.service';
@ApiTags('channels')
@Controller('admin')
export class ChannelsController {
constructor(private readonly channels: ChannelsService, private readonly deletions: DeletionGovernanceService) {}
constructor(
private readonly channels: ChannelsService,
private readonly deletions: DeletionGovernanceService,
) {}
@Get('channels')
listChannels(@Query('keyword') keyword?: string, @Query('carrier') carrier?: string, @Query('status') status?: string, @Query('page') page?: string, @Query('pageSize') pageSize?: string) {
listChannels(
@Query('keyword') keyword?: string,
@Query('carrier') carrier?: string,
@Query('status') status?: string,
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return page || pageSize
? this.channels.listChannelsPage({ keyword, carrier, status, page: Number(page), pageSize: Number(pageSize) })
: this.channels.listChannels();
@@ -68,7 +77,11 @@ export class ChannelsController {
@Delete('channels/:id')
@RequireRecentAuthentication()
deleteChannel(@Param('id') channelId: string, @Body() body: DeleteTargetDto, @CurrentSessionUserId() operatorId?: string) {
deleteChannel(
@Param('id') channelId: string,
@Body() body: DeleteTargetDto,
@CurrentSessionUserId() operatorId?: string,
) {
return this.deletions.delete('channel', channelId, { ...body, operatorId });
}
@@ -119,6 +132,11 @@ export class ChannelsController {
return this.channels.updateGroup(groupId, body);
}
@Get('channel-groups/:id/deletion-impact')
getGroupDeletionImpact(@Param('id') groupId: string) {
return this.channels.getGroupDeletionImpact(groupId);
}
@Delete('channel-groups/:id')
@RequireRecentAuthentication()
deleteGroup(@Param('id') groupId: string) {
@@ -154,7 +172,11 @@ export class ChannelsController {
@Put('channels/:channelId/report-fields/:reportType')
@RequireRecentAuthentication()
replaceReportFields(@Param('channelId') channelId: string, @Param('reportType') reportType: 'signature' | 'drainage', @Body() body: ReplaceReportFieldsDto) {
replaceReportFields(
@Param('channelId') channelId: string,
@Param('reportType') reportType: 'signature' | 'drainage',
@Body() body: ReplaceReportFieldsDto,
) {
return this.channels.replaceReportFields(channelId, reportType, body);
}
@@ -169,12 +191,82 @@ export class ChannelsController {
}
@Get('report-tasks')
listReportTasks(@Query('tenantId') tenantId?: string, @Query('status') status?: string, @Query('channelId') channelId?: string, @Query('reportType') reportType?: string, @Query('keyword') keyword?: string, @Query('createdAtFrom') createdAtFrom?: string, @Query('createdAtTo') createdAtTo?: string, @Query('page') page?: string, @Query('pageSize') pageSize?: string) {
return page || pageSize || keyword || createdAtFrom || createdAtTo
? this.channels.listReportTasksPage({ tenantId, status, channelId, reportType, keyword, createdAtFrom, createdAtTo, page: Number(page), pageSize: Number(pageSize) })
listReportTasks(
@Query('tenantId') tenantId?: string,
@Query('applicationId') applicationId?: string,
@Query('status') status?: string,
@Query('channelId') channelId?: string,
@Query('reportType') reportType?: string,
@Query('keyword') keyword?: string,
@Query('carrier') carrier?: string,
@Query('todaySendMin') todaySendMin?: string,
@Query('todaySendMax') todaySendMax?: string,
@Query('sort') sort?: string,
@Query('createdAtFrom') createdAtFrom?: string,
@Query('createdAtTo') createdAtTo?: string,
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return page ||
pageSize ||
keyword ||
applicationId ||
carrier ||
todaySendMin ||
todaySendMax ||
sort ||
createdAtFrom ||
createdAtTo
? this.channels.listReportTasksPage({
tenantId,
applicationId,
status,
channelId,
reportType,
keyword,
carrier,
todaySendMin: Number(todaySendMin),
todaySendMax: Number(todaySendMax),
sort,
createdAtFrom,
createdAtTo,
page: Number(page),
pageSize: Number(pageSize),
})
: this.channels.listReportTasks(tenantId, status, channelId, reportType);
}
@Get('report-details')
listReportDetails(
@Query('tenantId') tenantId?: string,
@Query('applicationId') applicationId?: string,
@Query('signatureId') signatureId?: string,
@Query('channelId') channelId?: string,
@Query('carrier') carrier?: string,
@Query('status') status?: string,
@Query('reportType') reportType?: string,
@Query('keyword') keyword?: string,
@Query('createdAtFrom') createdAtFrom?: string,
@Query('createdAtTo') createdAtTo?: string,
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return this.channels.listReportDetailsPage({
tenantId,
applicationId,
signatureId,
channelId,
carrier,
status,
reportType,
keyword,
createdAtFrom,
createdAtTo,
page: Number(page),
pageSize: Number(pageSize),
});
}
@Post('report-tasks/generate')
createReportTask(@Body() body: CreateReportTaskDto) {
return this.channels.createReportTask(body);
@@ -197,9 +289,47 @@ export class ChannelsController {
}
@Get('report-records')
listReportRecords(@Query('taskId') taskId?: string, @Query('channelId') channelId?: string, @Query('keyword') keyword?: string, @Query('reportType') reportType?: string, @Query('createdAtFrom') createdAtFrom?: string, @Query('createdAtTo') createdAtTo?: string, @Query('page') page?: string, @Query('pageSize') pageSize?: string) {
return page || pageSize || keyword || reportType || createdAtFrom || createdAtTo
? this.channels.listReportRecordsPage({ taskId, channelId, keyword, reportType, createdAtFrom, createdAtTo, page: Number(page), pageSize: Number(pageSize) })
listReportRecords(
@Query('taskId') taskId?: string,
@Query('channelId') channelId?: string,
@Query('batchNo') batchNo?: string,
@Query('statusAfter') statusAfter?: string,
@Query('action') action?: string,
@Query('sourceEntry') sourceEntry?: string,
@Query('operatorKeyword') operatorKeyword?: string,
@Query('keyword') keyword?: string,
@Query('reportType') reportType?: string,
@Query('createdAtFrom') createdAtFrom?: string,
@Query('createdAtTo') createdAtTo?: string,
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return page ||
pageSize ||
keyword ||
batchNo ||
statusAfter ||
action ||
sourceEntry ||
operatorKeyword ||
reportType ||
createdAtFrom ||
createdAtTo
? this.channels.listReportRecordsPage({
taskId,
channelId,
batchNo,
statusAfter,
action,
sourceEntry,
operatorKeyword,
keyword,
reportType,
createdAtFrom,
createdAtTo,
page: Number(page),
pageSize: Number(pageSize),
})
: this.channels.listReportRecords(taskId, channelId);
}
}
@@ -0,0 +1,14 @@
import { BadRequestException } from '@nestjs/common';
import { normalizeChannelRuntimeConfig } from './channels.helpers';
describe('Gateway channel capacity validation', () => {
it.each([1, 2, 4, 8])('accepts %i supplier connections', (desiredConnections) => {
expect(normalizeChannelRuntimeConfig(undefined, undefined, desiredConnections, 16)).toEqual(expect.objectContaining({ desiredConnections, windowSize: 16 }));
});
it.each([1, 16, 32, 64])('accepts supplier window %i', (windowSize) => {
expect(normalizeChannelRuntimeConfig(undefined, undefined, 1, windowSize)).toEqual(expect.objectContaining({ desiredConnections: 1, windowSize }));
});
it.each([[0, 16], [9, 16], [1, 0], [1, 65]])('rejects capacity outside 1..8 connections and 1..64 window', (connections, window) => {
expect(() => normalizeChannelRuntimeConfig(undefined, undefined, connections, window)).toThrow(BadRequestException);
});
});
+22
View File
@@ -0,0 +1,22 @@
import {
isChannelCarrierCompatible,
legacyCarrierFromCapabilities,
normalizeChannelCarriers,
} from './channels.helpers';
describe('channel carrier capabilities', () => {
it('preserves the legacy default when an old caller omits carrier fields', () => {
expect(normalizeChannelCarriers()).toEqual(['mobile']);
});
it('expands a historical three-network channel without inventing data for partial capabilities', () => {
expect(normalizeChannelCarriers(undefined, 'all')).toEqual(['mobile', 'unicom', 'telecom']);
expect(normalizeChannelCarriers(['telecom', 'mobile'], 'all')).toEqual(['mobile', 'telecom']);
expect(legacyCarrierFromCapabilities(['mobile', 'telecom'])).toBe('multi');
});
it('checks a group carrier against the new multi-select capability list', () => {
expect(isChannelCarrierCompatible('multi', 'mobile', ['mobile', 'telecom'])).toBe(true);
expect(isChannelCarrierCompatible('multi', 'unicom', ['mobile', 'telecom'])).toBe(false);
});
});
+813
View File
@@ -0,0 +1,813 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { randomUUID } from 'crypto';
import { summarizeReportStatuses as summarizeCommonReportStatuses } from '../common/report-status';
import type { CreateChannelGroupItemDto, TestChannelDto } from './channels.contracts';
export function summarizeReportStatuses(statuses: string[]) {
return summarizeCommonReportStatuses(statuses);
}
/** Constants and pure validation/normalization helpers shared by R5 domains. */
export const GATEWAY_CONNECTION_QUEUE = 'gateway.connection.commands';
export const GATEWAY_SUBMIT_QUEUE = 'gateway.submit.queue';
export const GATEWAY_SUBMIT_STREAM = 'gateway.submit.commands';
export const DEFAULT_GATEWAY_CONTROL_URL = 'http://127.0.0.1:8090';
export const DEFAULT_CHANNEL_CONNECTION_ID = 'primary';
export const DEFAULT_CONNECTING_TIMEOUT_MS = 30_000;
export const DEFAULT_CONNECTING_TIMEOUT_SCAN_MS = 5_000;
export const DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS = 1_000;
export const DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS = 30_000;
export const DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS = 10_000;
export const DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30;
export const DEFAULT_HEARTBEAT_MISS_THRESHOLD = 3;
export const HEARTBEAT_AUDIT_INTERVAL_MS = 5 * 60_000;
export const CONNECTING_TIMEOUT_ERROR = 'Gateway connection request timed out';
export const DEFAULT_CMPP_VERSION = '2.0';
export function normalizeTestPhones(data: TestChannelDto) {
const rawPhones = Array.isArray(data.phones)
? data.phones
: String(data.phoneNumber ?? data.phones ?? '').split(/[,\n\s]+/u);
const phones = rawPhones.map((phone) => String(phone).trim()).filter(Boolean);
const uniquePhones = Array.from(new Set(phones));
if (uniquePhones.length === 0) {
throw new BadRequestException('请填写测试手机号');
}
if (uniquePhones.length > 10) {
throw new BadRequestException('测试手机号最多允许 10 个');
}
for (const phone of uniquePhones) {
if (!/^1[3-9]\d{9}$/.test(phone)) {
throw new BadRequestException(`手机号格式不正确:${phone}`);
}
}
return uniquePhones;
}
export function normalizeTestContent(content?: string) {
const normalized = (content ?? '').trim();
if (!normalized) {
throw new BadRequestException('请填写测试短信内容');
}
if (normalized.length > 1000) {
throw new BadRequestException('测试短信内容不能超过 1000 字符');
}
return normalized;
}
export function calculateBillingUnits(content: string) {
return Math.max(1, Math.ceil([...content].length / 67));
}
export function buildChannelTestSubmitCommand({
channel,
content,
phoneNumber,
messageId,
submitId,
testNo,
attempt,
accessNo,
}: {
channel: {
id: string;
code: string;
gatewayHost: string;
gatewayPort: number;
account: string;
passwordCipher: string;
srcId: string;
cmppVersion: string;
rateLimitPerSecond: number;
config?: Prisma.JsonValue | null;
};
content: string;
phoneNumber: string;
messageId: string;
submitId: string;
testNo: string;
attempt: number;
accessNo?: string;
}) {
const srcId = accessNo?.trim() ? `${channel.srcId}${accessNo.trim()}` : channel.srcId;
return {
schemaVersion: 'v1',
messageType: 'SubmitCommand',
traceId: randomUUID(),
messageId,
channelId: channel.id,
createdAt: new Date().toISOString(),
tenantId: 'platform-channel-test',
applicationId: 'admin-channel-test',
taskId: testNo,
submitId,
queuePriority: 'normal',
phoneNumber,
content,
signature: 'CHANNEL_TEST',
templateId: 'admin-channel-test',
billingUnits: calculateBillingUnits(content),
route: {
channelCode: channel.code,
cmppAccountCode: channel.account,
priority: attempt,
rateLimitPerSecond: channel.rateLimitPerSecond,
},
cmpp: {
serviceId: getStringConfigValue(channel.config, 'serviceId', 'SMS'),
srcId,
extensionDigits: normalizeExtensionDigits(getConfigValue(channel.config, 'extensionDigits')),
registeredDelivery: 1,
msgFmt: 8,
},
upstream: {
gatewayHost: channel.gatewayHost,
gatewayPort: channel.gatewayPort,
account: channel.account,
passwordCipher: channel.passwordCipher,
cmppVersion: channel.cmppVersion,
desiredConnections: getPositiveRuntimeInteger(
getConfigValue(channel.config, 'desiredConnections'),
1,
'desiredConnections',
),
windowSize: getPositiveRuntimeInteger(getConfigValue(channel.config, 'windowSize'), 16, 'windowSize'),
heartbeatIntervalSeconds: getPositiveRuntimeInteger(
getConfigValue(channel.config, 'heartbeatIntervalSeconds'),
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
'heartbeatIntervalSeconds',
),
heartbeatMissThreshold: getPositiveRuntimeInteger(
getConfigValue(channel.config, 'heartbeatMissThreshold'),
DEFAULT_HEARTBEAT_MISS_THRESHOLD,
'heartbeatMissThreshold',
),
},
retry: { attempt: 0, maxAttempts: 1 },
};
}
export function getConfigValue(config: Prisma.JsonValue | null | undefined, key: string) {
if (config && typeof config === 'object' && !Array.isArray(config) && key in config) {
return config[key as keyof typeof config];
}
return undefined;
}
export function getStringConfigValue(config: Prisma.JsonValue | null | undefined, key: string, fallback: string) {
const value = getConfigValue(config, key);
if (value === undefined || value === null || value === '') {
return fallback;
}
return String(value);
}
export function normalizeConnectionAction(status: string) {
const normalized = status.toLowerCase();
if (normalized === 'connected') {
return 'connected';
}
if (['heartbeat', 'active_test'].includes(normalized)) {
return 'heartbeat';
}
if (['reconnecting', 'reconnect'].includes(normalized)) {
return 'reconnecting';
}
if (['offline', 'closed', 'disconnected'].includes(normalized)) {
return 'disconnected';
}
if (['auth_failed', 'heartbeat_timeout', 'failed', 'error'].includes(normalized)) {
return 'failed';
}
return 'updated';
}
export function normalizeCmppVersion(version?: string) {
const normalized = (version ?? DEFAULT_CMPP_VERSION).trim();
if (normalized === '2.0' || normalized === '3.0') {
return normalized;
}
throw new BadRequestException('cmppVersion must be 2.0 or 3.0');
}
export function normalizeGatewayConnectionStatus(status: string) {
const normalized = status.toLowerCase();
if (['online', 'open', 'connected', 'heartbeat', 'active_test'].includes(normalized)) {
return 'connected';
}
if (['connecting', 'connect_requested'].includes(normalized)) {
return 'connecting';
}
if (['reconnecting', 'reconnect'].includes(normalized)) {
return 'reconnecting';
}
if (['offline', 'closed', 'disconnected'].includes(normalized)) {
return 'disconnected';
}
if (['auth_failed', 'heartbeat_timeout', 'failed', 'error'].includes(normalized)) {
return 'failed';
}
return normalized;
}
export function defaultChannelConnectionId(channelId: string) {
return `${channelId}:${DEFAULT_CHANNEL_CONNECTION_ID}`;
}
export function getDesiredConnections(config?: Prisma.JsonValue | null) {
if (config && typeof config === 'object' && !Array.isArray(config) && 'desiredConnections' in config) {
const value = Number(config.desiredConnections);
if (Number.isInteger(value) && value >= 1 && value <= 8) {
return value;
}
}
return 1;
}
export type ChannelConnectionSettings = {
gatewayHost: string;
gatewayPort: number;
account: string;
passwordCipher: string;
cmppVersion: string;
config?: Prisma.JsonValue | Record<string, unknown> | null;
};
export function getRuntimeConfigInteger(
config: Prisma.JsonValue | Record<string, unknown> | null | undefined,
key: string,
fallback: number,
) {
if (!config || typeof config !== 'object' || Array.isArray(config)) return fallback;
const value = Number((config as Record<string, unknown>)[key]);
return Number.isInteger(value) && value > 0 ? value : fallback;
}
export function channelConnectionSettingsChanged(before: ChannelConnectionSettings, after: ChannelConnectionSettings) {
return (
before.gatewayHost !== after.gatewayHost ||
before.gatewayPort !== after.gatewayPort ||
before.account !== after.account ||
before.passwordCipher !== after.passwordCipher ||
before.cmppVersion !== after.cmppVersion ||
getRuntimeConfigInteger(before.config, 'desiredConnections', 1) !==
getRuntimeConfigInteger(after.config, 'desiredConnections', 1) ||
getRuntimeConfigInteger(before.config, 'windowSize', 16) !==
getRuntimeConfigInteger(after.config, 'windowSize', 16) ||
getRuntimeConfigInteger(before.config, 'heartbeatIntervalSeconds', DEFAULT_HEARTBEAT_INTERVAL_SECONDS) !==
getRuntimeConfigInteger(after.config, 'heartbeatIntervalSeconds', DEFAULT_HEARTBEAT_INTERVAL_SECONDS) ||
getRuntimeConfigInteger(before.config, 'heartbeatMissThreshold', DEFAULT_HEARTBEAT_MISS_THRESHOLD) !==
getRuntimeConfigInteger(after.config, 'heartbeatMissThreshold', DEFAULT_HEARTBEAT_MISS_THRESHOLD)
);
}
export function channelGroupAuditSnapshot(group: {
code: string;
name: string;
carrier: string;
description?: string | null;
status: string;
retryEnabled: boolean;
retryTimeLimitMinutes: number;
items?: Array<{
channelId: string;
carrier?: string | null;
province?: string | null;
priority: number;
weight: number;
isBackup: boolean;
channel?: { code?: string; name?: string } | null;
}>;
}) {
return {
code: group.code,
name: group.name,
carrier: group.carrier,
description: group.description ?? null,
status: group.status,
retryEnabled: group.retryEnabled,
retryTimeLimitMinutes: group.retryTimeLimitMinutes,
items: (group.items ?? []).map((item) => ({
channelId: item.channelId,
channelCode: item.channel?.code ?? null,
channelName: item.channel?.name ?? null,
carrier: item.carrier ?? null,
province: item.province ?? null,
priority: item.priority,
weight: item.weight,
isBackup: item.isBackup,
})),
};
}
export function normalizeChannelRuntimeConfig(
existingConfig?: Prisma.JsonValue | Record<string, unknown> | null,
incomingConfig?: Record<string, unknown> | null,
desiredConnections?: number,
windowSize?: number,
heartbeatIntervalSeconds?: number,
heartbeatMissThreshold?: number,
) {
const existing =
existingConfig && typeof existingConfig === 'object' && !Array.isArray(existingConfig)
? (existingConfig as Record<string, unknown>)
: {};
const incoming =
incomingConfig && typeof incomingConfig === 'object' && !Array.isArray(incomingConfig) ? incomingConfig : {};
const base = { ...existing, ...incoming };
base.desiredConnections = boundedRuntimeInteger(
desiredConnections ?? base.desiredConnections,
1,
8,
1,
'desiredConnections',
);
base.windowSize = boundedRuntimeInteger(windowSize ?? base.windowSize, 1, 64, 16, 'windowSize');
base.connectionWarmupSeconds = boundedRuntimeInteger(
base.connectionWarmupSeconds,
0,
300,
30,
'connectionWarmupSeconds',
);
base.connectionDrainTimeoutSeconds = boundedRuntimeInteger(
base.connectionDrainTimeoutSeconds,
1,
600,
60,
'connectionDrainTimeoutSeconds',
);
base.submitResponseTimeoutSeconds = boundedRuntimeInteger(
base.submitResponseTimeoutSeconds,
1,
300,
60,
'submitResponseTimeoutSeconds',
);
base.connectionFailureCooldownSeconds = boundedRuntimeInteger(
base.connectionFailureCooldownSeconds,
1,
300,
30,
'connectionFailureCooldownSeconds',
);
base.heartbeatIntervalSeconds = getPositiveRuntimeInteger(
heartbeatIntervalSeconds ?? base.heartbeatIntervalSeconds,
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
'heartbeatIntervalSeconds',
);
base.heartbeatMissThreshold = getPositiveRuntimeInteger(
heartbeatMissThreshold ?? base.heartbeatMissThreshold,
DEFAULT_HEARTBEAT_MISS_THRESHOLD,
'heartbeatMissThreshold',
);
base.extensionDigits = normalizeExtensionDigits(base.extensionDigits);
base.serviceId = normalizeCmppServiceId(base.serviceId);
base.longMessageReceiptMode = normalizeLongMessageReceiptMode(base.longMessageReceiptMode);
return base;
}
function boundedRuntimeInteger(value: unknown, minimum: number, maximum: number, fallback: number, field: string) {
const normalized = value === undefined || value === null || value === '' ? fallback : Number(value);
if (!Number.isInteger(normalized) || normalized < minimum || normalized > maximum) {
throw new BadRequestException(`${field} must be an integer between ${minimum} and ${maximum}`);
}
return normalized;
}
export function normalizeLongMessageReceiptMode(value: unknown) {
const normalized = String(value ?? 'per_segment').trim() || 'per_segment';
if (!['per_segment', 'message_level'].includes(normalized)) {
throw new BadRequestException('longMessageReceiptMode must be per_segment or message_level');
}
return normalized;
}
export function normalizeCmppServiceId(value: unknown) {
const normalized = String(value ?? 'SMS').trim() || 'SMS';
if (!/^[\x20-\x7E]{1,10}$/.test(normalized)) {
throw new BadRequestException('serviceId must contain 1 to 10 ASCII characters');
}
return normalized;
}
export function normalizeChannelRateLimit(value: unknown) {
const normalized = getPositiveRuntimeInteger(value, 100, 'rateLimitPerSecond');
if (normalized > 2000) {
throw new BadRequestException('rateLimitPerSecond must be between 1 and 2000');
}
return normalized;
}
export function normalizeExtensionDigits(value: unknown) {
if (value === undefined || value === null || value === '') {
return 0;
}
const normalized = Number(value);
if (!Number.isInteger(normalized) || normalized < 0 || normalized > 20) {
throw new BadRequestException('extensionDigits must be an integer between 0 and 20');
}
return normalized;
}
export function getPositiveRuntimeInteger(value: unknown, fallback: number, fieldName: string) {
if (value === undefined || value === null || value === '') {
return fallback;
}
const normalized = Number(value);
if (!Number.isInteger(normalized) || normalized <= 0) {
throw new BadRequestException(`${fieldName} must be a positive integer`);
}
return normalized;
}
export function bullmqConnection() {
const redisUrl = new URL(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379');
return {
host: redisUrl.hostname,
port: Number(redisUrl.port || 6379),
username: redisUrl.username || undefined,
password: redisUrl.password || undefined,
maxRetriesPerRequest: null,
};
}
export function getPositiveIntegerEnv(name: string, fallback: number) {
const value = Number(process.env[name]);
if (Number.isInteger(value) && value > 0) {
return value;
}
return fallback;
}
export function parseReceiptContent(content: string, delimiter?: ',' | '\t') {
const lines = content
.replace(/^\uFEFF/, '')
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
if (lines.length === 0) {
throw new BadRequestException('Receipt file is empty');
}
const separator = delimiter ?? (lines[0].includes('\t') ? '\t' : ',');
const firstCells = splitReceiptLine(lines[0], separator);
const hasHeader = firstCells.some((cell) =>
['phone', 'mobile', 'status', 'result', '手机号', '号码', '状态', '结果'].includes(cell.toLowerCase()),
);
const header = hasHeader ? firstCells : [];
const rows = hasHeader ? lines.slice(1) : lines;
const statusIndex = findReceiptStatusIndex(header);
let successCount = 0;
let failedCount = 0;
const resultRows = rows.map((line, index) => {
const cells = splitReceiptLine(line, separator);
const rawStatus = cells[statusIndex] ?? cells[cells.length - 1] ?? '';
const normalizedStatus = normalizeReceiptStatus(rawStatus);
if (normalizedStatus === 'success') {
successCount += 1;
} else {
failedCount += 1;
}
return {
rowNumber: hasHeader ? index + 2 : index + 1,
phone: cells[0] ?? '',
status: normalizedStatus,
rawStatus,
raw: cells,
};
});
return {
rowCount: resultRows.length,
successCount,
failedCount,
result: {
delimiter: separator === '\t' ? 'tab' : 'comma',
hasHeader,
rows: resultRows,
},
};
}
export function splitReceiptLine(line: string, delimiter: ',' | '\t') {
if (delimiter === '\t') {
return line.split('\t').map((cell) => stripReceiptCell(cell));
}
const cells: string[] = [];
let current = '';
let quoted = false;
for (let index = 0; index < line.length; index += 1) {
const char = line[index];
const next = line[index + 1];
if (char === '"' && quoted && next === '"') {
current += '"';
index += 1;
} else if (char === '"') {
quoted = !quoted;
} else if (char === ',' && !quoted) {
cells.push(stripReceiptCell(current));
current = '';
} else {
current += char;
}
}
cells.push(stripReceiptCell(current));
return cells;
}
export function stripReceiptCell(value: string) {
return value.trim().replace(/^"|"$/g, '').trim();
}
export function findReceiptStatusIndex(header: string[]) {
if (header.length === 0) {
return 1;
}
const index = header.findIndex((cell) => ['status', 'result', '状态', '结果'].includes(cell.toLowerCase()));
return index >= 0 ? index : Math.max(0, header.length - 1);
}
export function normalizeReceiptStatus(value: string) {
const normalized = value.trim().toLowerCase();
if (
[
'success',
'succeeded',
'approved',
'completed',
'ok',
'pass',
'passed',
'通过',
'成功',
'已完成',
'报备成功',
].includes(normalized)
) {
return 'success';
}
if (
[
'failed',
'fail',
'rejected',
'reject',
'error',
'no',
'denied',
'驳回',
'失败',
'不通过',
'拒绝',
'报备失败',
].includes(normalized)
) {
return 'failed';
}
return 'failed';
}
export function deriveReceiptStatus(rowCount: number, successCount: number, failedCount: number) {
if (rowCount <= 0 || successCount <= 0) {
return 'failed';
}
if (failedCount > 0) {
return 'partial';
}
return 'completed';
}
export type ChannelReportDeliveryRow = {
drainageIds?: string[] | null;
carrier: string | null;
channelId: string;
signatureId: string;
drainageInfoId: string | null;
total: number;
acceptedCount: number;
submitFailureCount: number;
successCount: number;
unknownCount: number;
failureCount: number;
lastSuccessfulSentAt: Date | null;
};
export function summarizeChannelReportDelivery(rows: ChannelReportDeliveryRow[]) {
const total = sumReportDelivery(rows, 'total');
const acceptedCount = sumReportDelivery(rows, 'acceptedCount');
const submitFailureCount = sumReportDelivery(rows, 'submitFailureCount');
const successCount = sumReportDelivery(rows, 'successCount');
const unknownCount = sumReportDelivery(rows, 'unknownCount');
const failureCount = sumReportDelivery(rows, 'failureCount');
return {
total,
acceptedCount,
submitFailureCount,
submitFailureRate: percentage(submitFailureCount, total),
successCount,
successRate: percentage(successCount, acceptedCount),
unknownCount,
unknownRate: percentage(unknownCount, acceptedCount),
failureCount,
failureRate: percentage(failureCount, acceptedCount),
};
}
export function sumReportDelivery(
rows: ChannelReportDeliveryRow[],
key: keyof Pick<
ChannelReportDeliveryRow,
'total' | 'acceptedCount' | 'submitFailureCount' | 'successCount' | 'unknownCount' | 'failureCount'
>,
) {
return rows.reduce((total, row) => total + Number(row[key] ?? 0), 0);
}
export function percentage(count: number, total: number) {
return total > 0 ? Number(((count * 100) / total).toFixed(1)) : 0;
}
export function latestDate(values: Array<Date | null>) {
const timestamps = values.filter((value): value is Date => Boolean(value)).map((value) => value.getTime());
return timestamps.length > 0 ? new Date(Math.max(...timestamps)) : null;
}
export function currentShanghaiDayRange(now = new Date()) {
const shifted = new Date(now.getTime() + 8 * 60 * 60 * 1_000);
const localDate = shifted.toISOString().slice(0, 10);
const startAt = new Date(`${localDate}T00:00:00+08:00`);
return { startAt, endAt: new Date(startAt.getTime() + 24 * 60 * 60 * 1_000) };
}
export function normalizeRetryTimeLimitMinutes(
minutes: number | undefined,
hours: number | undefined,
fallbackMinutes: number,
) {
const value = minutes ?? (hours === undefined ? fallbackMinutes : hours * 60);
if (!Number.isInteger(value) || value <= 0 || value > 72 * 60) {
throw new BadRequestException('retryTimeLimitMinutes must be an integer between 1 and 4320');
}
return value;
}
export function normalizeSpreadsheetSize(
value: number | undefined,
fallback: number,
minimum: number,
maximum: number,
) {
if (value === undefined || !Number.isFinite(value)) return fallback;
return Math.min(maximum, Math.max(minimum, Math.round(value)));
}
export function normalizeBusinessCarrier(carrier?: string | null) {
const normalized = normalizeChannelCarrier(carrier);
if (!['mobile', 'unicom', 'telecom'].includes(normalized)) {
throw new BadRequestException('carrier must be mobile, unicom, or telecom');
}
return normalized;
}
export function normalizeChannelCarrier(carrier?: string | null) {
const value = String(carrier ?? '')
.trim()
.toLowerCase();
if (['mobile', 'cmcc', '移动', '中国移动'].includes(value)) return 'mobile';
if (['unicom', 'cucc', '联通', '中国联通'].includes(value)) return 'unicom';
if (['telecom', 'ctcc', '电信', '中国电信'].includes(value)) return 'telecom';
if (['all', 'tri', '三网', '全网'].includes(value)) return 'all';
return value;
}
export const SUPPORTED_CHANNEL_CARRIERS = ['mobile', 'unicom', 'telecom'] as const;
export function normalizeChannelCarriers(carriers?: string[] | null, legacyCarrier?: string | null): string[] {
const source = carriers?.length
? carriers
: normalizeChannelCarrier(legacyCarrier ?? 'mobile') === 'all'
? [...SUPPORTED_CHANNEL_CARRIERS]
: [normalizeChannelCarrier(legacyCarrier ?? 'mobile')];
const normalized = [...new Set(source.map((carrier) => normalizeBusinessCarrier(carrier)))];
if (normalized.length === 0) throw new BadRequestException('至少选择一个运营商');
return SUPPORTED_CHANNEL_CARRIERS.filter((carrier) => normalized.includes(carrier));
}
export function legacyCarrierFromCapabilities(carriers: string[]) {
if (carriers.length === 1) return carriers[0];
if (carriers.length === SUPPORTED_CHANNEL_CARRIERS.length) return 'all';
// Old readers must fail closed for a two-carrier channel instead of treating
// it as three-network capable and accidentally routing unsupported traffic.
return 'multi';
}
export function isChannelCarrierCompatible(
channelCarrier: string | null | undefined,
groupCarrier: string,
carriers?: string[] | null,
) {
return normalizeChannelCarriers(carriers, channelCarrier).includes(normalizeBusinessCarrier(groupCarrier));
}
export function normalizeRegion(region?: string | null) {
return String(region ?? '')
.replace(/省|市|自治区|壮族|回族|维吾尔/g, '')
.trim();
}
export function isRegionCompatible(channelRegion: string | null | undefined, itemProvince: string) {
return normalizeRegion(channelRegion) === normalizeRegion(itemProvince);
}
export function validateGroupItems(
groupCarrier: string,
items: Array<Omit<CreateChannelGroupItemDto, 'groupId'>>,
channels: Map<
string,
{ id: string; carrier?: string | null; carriers?: string[] | null; sendRegion?: string | null }
>,
) {
const channelIds = new Set<string>();
const provinces = new Set<string>();
const nationalPriorities = new Set<number>();
for (const item of items) {
const itemCarrier = item.carrier ? normalizeBusinessCarrier(item.carrier) : groupCarrier;
if (itemCarrier !== groupCarrier) {
throw new BadRequestException('Channel group items must use the same carrier as the channel group');
}
const channel = channels.get(item.channelId);
if (!channel) {
throw new NotFoundException('Channel not found');
}
if (channelIds.has(item.channelId)) {
throw new BadRequestException('通道组内不能重复配置同一通道');
}
channelIds.add(item.channelId);
if (!isChannelCarrierCompatible(channel.carrier, groupCarrier, channel.carriers)) {
throw new BadRequestException('Channel carrier is not compatible with the channel group carrier');
}
if (item.province) {
const province = normalizeRegion(item.province);
if (provinces.has(province)) {
throw new BadRequestException('同一通道组内同一省份只能配置一个通道');
}
provinces.add(province);
if (!isRegionCompatible(channel.sendRegion, item.province)) {
throw new BadRequestException('Province route must use a channel with the same sendRegion');
}
} else {
const priority = item.priority ?? 100;
if (nationalPriorities.has(priority)) {
throw new BadRequestException('同一通道组内全国通道优先级不能重复');
}
nationalPriorities.add(priority);
}
}
}
export function normalizeReportType(value?: string) {
if (value === 'signature' || value === 'drainage' || value === 'both') return value;
throw new BadRequestException('reportType must be signature, drainage or both');
}
export function normalizeLinkEvent(action: string) {
if (action.includes('connect_requested')) {
return '连接请求';
}
if (action.includes('connected')) {
return '连接成功';
}
if (action.includes('heartbeat')) {
return '心跳';
}
if (action.includes('reconnecting')) {
return '重连';
}
if (action.includes('disconnected')) {
return '断开';
}
if (action.includes('failed')) {
return '连接失败';
}
if (action.includes('copy')) {
return '复制';
}
if (action.includes('deleted')) {
return '删除';
}
return '更新';
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,55 @@
import { registerDecorator, type ValidationArguments, type ValidationOptions } from 'class-validator';
type BoundedJsonOptions = {
maxDepth?: number;
maxKeys?: number;
maxStringLength?: number;
};
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
export function IsBoundedJsonObject(options: BoundedJsonOptions = {}, validationOptions?: ValidationOptions) {
return (target: object, propertyName: string) =>
registerDecorator({
name: 'isBoundedJsonObject',
target: target.constructor,
propertyName,
constraints: [options],
options: validationOptions,
validator: {
validate(value: unknown, args: ValidationArguments) {
if (value === undefined || value === null) return true;
const [constraints] = args.constraints as [BoundedJsonOptions];
return isBoundedJsonValue(value, {
maxDepth: constraints.maxDepth ?? 4,
maxKeys: constraints.maxKeys ?? 100,
maxStringLength: constraints.maxStringLength ?? 2_000,
});
},
defaultMessage(args: ValidationArguments) {
return `${args.property} contains too many, too deeply nested, or unsafe values`;
},
},
});
}
function isBoundedJsonValue(value: unknown, limits: Required<BoundedJsonOptions>) {
let keyCount = 0;
const visit = (current: unknown, depth: number): boolean => {
if (depth > limits.maxDepth) return false;
if (current == null || typeof current === 'boolean' || typeof current === 'number') return true;
if (typeof current === 'string') return current.length <= limits.maxStringLength;
if (Array.isArray(current)) {
keyCount += current.length;
return keyCount <= limits.maxKeys && current.every((item) => visit(item, depth + 1));
}
if (typeof current !== 'object') return false;
const entries = Object.entries(current as Record<string, unknown>);
keyCount += entries.length;
return (
keyCount <= limits.maxKeys &&
entries.every(([key, item]) => key.length <= 128 && !FORBIDDEN_KEYS.has(key) && visit(item, depth + 1))
);
};
return visit(value, 0);
}
+65
View File
@@ -0,0 +1,65 @@
import { BadRequestException } from '@nestjs/common';
import { ClientBatchTaskDto, ClientDeleteResourceDto, ClientDrainageInfoDto, ClientImportConfirmDto } from './client-write.dto';
import { strictValidationPipe } from './strict-validation.pipe';
function validate<T>(metatype: new () => T, value: unknown) {
return strictValidationPipe.transform(value, { type: 'body', metatype, data: undefined });
}
describe('strict client write DTOs', () => {
it('accepts an import confirmation without a client-supplied phones array', async () => {
await expect(
validate(ClientImportConfirmDto, {
content: '【测试】验证码 ${code}',
importContent: 'phone,code\n13800000001,1234',
}),
).resolves.toEqual(expect.objectContaining({ importContent: expect.any(String) }));
});
it('rejects a direct batch task without validated phone numbers', async () => {
await expect(validate(ClientBatchTaskDto, { content: '【测试】通知' })).rejects.toBeInstanceOf(BadRequestException);
});
it('rejects a client-supplied operator identity', async () => {
await expect(
validate(ClientDeleteResourceDto, { status: 'deleted', operatorId: 'another-user' }),
).rejects.toBeInstanceOf(BadRequestException);
});
it('rejects a client-supplied tenant identity', async () => {
await expect(
validate(ClientBatchTaskDto, {
tenantId: 'other-tenant',
content: '【测试】通知',
phones: ['13800000001'],
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('rejects deeply nested or prototype-like dynamic values', async () => {
await expect(
validate(ClientBatchTaskDto, {
content: '【测试】通知',
phones: ['13800000001'],
variables: { safe: { nested: { too: { deep: { value: 'x' } } } } },
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it.each([
'https://example.com/path',
'example.com/path?source=sms',
'www.example.com',
'192.0.2.10:8080/landing',
'13800138000',
'+86 138-0013-8000',
'0755-12345678',
'(010) 12345678-123',
])('accepts a drainage URL or phone number without a separate name: %s', async (url) => {
await expect(validate(ClientDrainageInfoDto, { url })).resolves.toEqual(expect.objectContaining({ url }));
});
it('rejects arbitrary drainage text that is neither a URL nor a phone number', async () => {
await expect(validate(ClientDrainageInfoDto, { url: '品牌官网' })).rejects.toBeInstanceOf(BadRequestException);
});
});
+190
View File
@@ -0,0 +1,190 @@
import { Type } from 'class-transformer';
import { PartialType } from '@nestjs/swagger';
import {
ArrayMaxSize,
IsArray,
IsBoolean,
IsIn,
IsInt,
IsObject,
IsOptional,
IsString,
IsUrl,
IsDateString,
Matches,
Max,
MaxLength,
Min,
MinLength,
ValidateNested,
} from 'class-validator';
import { IsBoundedJsonObject } from './bounded-json-object.validator';
import { DRAINAGE_TARGET_ERROR, DRAINAGE_TARGET_PATTERN } from './drainage-target';
export class ClientCertificationSubmissionDto {
@IsString() @MinLength(1) @MaxLength(200) companyName!: string;
@IsOptional() @IsString() @MaxLength(100) licenseNo?: string;
@IsOptional() @IsString() @MaxLength(100) contactName?: string;
@IsOptional() @Matches(/^\+?[0-9-]{6,24}$/) contactPhone?: string;
@IsOptional() @IsObject() @IsBoundedJsonObject({ maxKeys: 100, maxDepth: 4 }) materials?: Record<string, unknown>;
}
export class ClientTaskBaseDto {
@IsOptional() @IsString() @MaxLength(64) applicationId?: string;
@IsOptional() @IsString() @MaxLength(64) templateId?: string;
@IsString() @MinLength(1) @MaxLength(5000) content!: string;
@IsOptional() @IsString() @MaxLength(64) category?: string;
@IsOptional() @IsIn(['immediate', 'scheduled']) sendMode?: 'immediate' | 'scheduled';
@IsOptional() @IsDateString({ strict: true }) scheduledAt?: string;
@IsOptional() @IsObject() @IsBoundedJsonObject({ maxKeys: 100, maxDepth: 4 }) variables?: Record<string, unknown>;
@IsOptional() @IsDateString({ strict: true }) requestedAt?: string;
@IsOptional() @IsString() @MaxLength(128) clientMessageId?: string;
}
export class ClientBatchTaskDto extends ClientTaskBaseDto {
@IsArray() @ArrayMaxSize(100000) @Matches(/^1\d{10}$/, { each: true }) phones!: string[];
}
export class ClientImportPreviewDto {
@IsOptional() @IsString() @MaxLength(64) applicationId?: string;
@IsString() @MinLength(1) @MaxLength(5_000_000) content!: string;
@IsOptional() @IsString() @MaxLength(255) fileName?: string;
@IsOptional() @IsIn(['utf8', 'gbk']) encoding?: 'utf8' | 'gbk';
@IsOptional() @IsIn([',', '\t']) delimiter?: ',' | '\t';
@IsOptional() @IsArray() @ArrayMaxSize(100) @IsString({ each: true }) requiredVariables?: string[];
}
export class ClientImportConfirmDto extends ClientTaskBaseDto {
@IsString() @MinLength(1) @MaxLength(5_000_000) importContent!: string;
@IsOptional() @IsArray() @ArrayMaxSize(100) @IsString({ each: true }) requiredVariables?: string[];
}
export class ClientBillingEstimateDto {
@IsOptional() @IsString() @MaxLength(64) applicationId?: string;
@IsString() @MinLength(1) @MaxLength(5000) content!: string;
@Type(() => Number) @IsInt() @Min(1) @Max(100000) phoneCount!: number;
@IsOptional() @Type(() => Number) @Min(0) unitPrice?: number;
@IsOptional() @IsString() @MaxLength(64) taskId?: string;
}
export class ClientSmsApplicationDto {
@IsString() @MinLength(1) @MaxLength(100) name!: string;
@IsOptional() @IsString() @MaxLength(500) scene?: string;
@IsOptional() @IsUrl({ require_tld: false }) @MaxLength(2048) callbackUrl?: string;
@IsOptional() @IsString() @MaxLength(64) cmppAccount?: string;
@IsOptional() @IsString() @MaxLength(64) cmppEnterpriseCode?: string;
@IsOptional() @IsString() @MaxLength(32) cmppApplicationExtension?: string;
@IsOptional() @IsBoolean() cmppAccessNumberFillEnabled?: boolean;
@IsOptional() @IsString() @MaxLength(32) cmppAccessNumberFillPrefix?: string;
@IsOptional() @IsString() @MaxLength(4096) passwordCipher?: string;
@IsOptional() @IsBoolean() interfaceEnabled?: boolean;
@IsOptional() @IsString() @MaxLength(32) interfaceType?: string;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100) cmppMaxConnections?: number;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(1000) cmppWindowSize?: number;
@IsOptional() @Type(() => Number) @IsInt() @Min(0) dailyLimit?: number;
@IsOptional() @Type(() => Number) @Min(0) customerUnitPrice?: number;
@IsOptional() @IsString() @MaxLength(32) queuePriority?: string;
@IsOptional() @IsString() @MaxLength(32) templateMismatchMode?: string;
@IsOptional() @IsBoolean() downstreamReceiptRetryEnabled?: boolean;
@IsOptional() @IsBoolean() downstreamUplinkRetryEnabled?: boolean;
@IsOptional() @IsArray() @ArrayMaxSize(100) @IsString({ each: true }) ipAllowlist?: string[];
}
export class ClientSmsSignatureDto {
@IsOptional() @IsString() @MaxLength(64) applicationId?: string;
@IsString() @MinLength(1) @MaxLength(100) name!: string;
@IsOptional() @IsString() @MaxLength(500) purpose?: string;
@IsOptional() @IsObject() @IsBoundedJsonObject({ maxKeys: 100, maxDepth: 4 }) drainageInfo?: Record<string, unknown>;
}
export class ClientSmsSignatureUpdateDto extends PartialType(ClientSmsSignatureDto) {
@IsOptional() @IsString() @MaxLength(32) auditStatus?: string;
}
export class ClientDrainageInfoDto {
@IsOptional() @IsString() @MaxLength(200) siteName?: string;
@IsString()
@MinLength(1)
@MaxLength(2048)
@Matches(DRAINAGE_TARGET_PATTERN, {
message: DRAINAGE_TARGET_ERROR,
})
url!: string;
@IsOptional() @IsString() @MaxLength(1000) remark?: string;
@IsOptional() @IsObject() @IsBoundedJsonObject({ maxKeys: 200, maxDepth: 4 }) reportValues?: Record<string, unknown>;
}
export class ClientDrainageInfoUpdateDto extends PartialType(ClientDrainageInfoDto) {}
export class ClientSignatureMaterialDto {
@IsOptional() @IsString() @MaxLength(64) fileObjectId?: string;
@IsString() @MinLength(1) @MaxLength(64) materialType!: string;
@IsString() @MinLength(1) @MaxLength(200) title!: string;
@IsOptional() @IsString() @MaxLength(2000) description?: string;
}
class TemplateVariableDto {
@IsString() @MinLength(1) @MaxLength(64) name!: string;
@IsOptional() @IsString() @MaxLength(500) example?: string;
@IsOptional() @IsBoolean() required?: boolean;
}
export class ClientSmsTemplateDto {
@IsString() @MaxLength(64) applicationId!: string;
@IsOptional() @IsString() @MaxLength(64) signatureId?: string;
@IsString() @MinLength(1) @MaxLength(200) name!: string;
@IsString() @MinLength(1) @MaxLength(5000) content!: string;
@IsOptional() @IsString() @MaxLength(64) category?: string;
@IsOptional()
@IsArray()
@ArrayMaxSize(100)
@ValidateNested({ each: true })
@Type(() => TemplateVariableDto)
variables?: TemplateVariableDto[];
}
export class ClientSmsTemplateUpdateDto extends PartialType(ClientSmsTemplateDto) {
@IsOptional() @IsString() @MaxLength(32) auditStatus?: string;
}
export class ClientStatusChangeDto {
@IsOptional() @IsString() @MaxLength(32) status?: string;
@IsOptional() @IsString() @MaxLength(1000) reason?: string;
@IsOptional() @IsBoolean() force?: boolean;
@IsOptional() @IsString() @MaxLength(200) confirmName?: string;
@IsOptional() @IsString() @MaxLength(200) confirmText?: string;
@IsOptional() @IsString() @MaxLength(64) expectedUpdatedAt?: string;
@IsOptional() @IsString() @MaxLength(128) idempotencyKey?: string;
@IsOptional() @IsBoolean() deleteAssociatedTemplates?: boolean;
@IsOptional() @IsBoolean() deleteAssociatedDrainage?: boolean;
@IsOptional() @IsBoolean() abandonAssociatedReportTasks?: boolean;
}
export class ClientSecretResetDto {
@IsOptional() @IsString() @MaxLength(1000) reason?: string;
@IsOptional() @IsString() @MaxLength(64) expectedUpdatedAt?: string;
@IsOptional() @IsString() @MaxLength(128) idempotencyKey?: string;
}
export class ClientApplicationStatusDto {
@IsOptional() @IsIn(['active', 'disabled', 'disabling', 'deleted']) status?: string;
@IsOptional() @IsString() @MaxLength(1000) reason?: string;
@IsOptional() @IsBoolean() force?: boolean;
@IsOptional() @IsString() @MaxLength(200) confirmName?: string;
@IsOptional() @IsString() @MaxLength(200) confirmText?: string;
@IsOptional() @IsString() @MaxLength(64) expectedUpdatedAt?: string;
@IsOptional() @IsString() @MaxLength(128) idempotencyKey?: string;
}
export class ClientDeleteResourceDto {
@IsIn(['deleted']) status!: 'deleted';
@IsOptional() @IsString() @MaxLength(1000) reason?: string;
@IsOptional() @IsBoolean() force?: boolean;
@IsOptional() @IsString() @MaxLength(200) confirmName?: string;
@IsOptional() @IsString() @MaxLength(200) confirmText?: string;
@IsOptional() @IsString() @MaxLength(64) expectedUpdatedAt?: string;
@IsOptional() @IsString() @MaxLength(128) idempotencyKey?: string;
@IsOptional() @IsBoolean() deleteAssociatedTemplates?: boolean;
@IsOptional() @IsBoolean() deleteAssociatedDrainage?: boolean;
@IsOptional() @IsBoolean() abandonAssociatedReportTasks?: boolean;
}
+13
View File
@@ -0,0 +1,13 @@
/** A carrier-specific decision overrides a legacy channel decision, including rejection. */
export function selectDrainageReportTask<
T extends {
channelId: string;
carrier?: string | null;
approvalScope?: string;
},
>(tasks: T[], channelId: string, carrier?: string) {
return (
(carrier ? tasks.find((task) => task.channelId === channelId && task.carrier === carrier) : undefined) ??
tasks.find((task) => task.channelId === channelId && !task.carrier && task.approvalScope !== 'carrier_specific')
);
}
+22
View File
@@ -0,0 +1,22 @@
import { parse } from 'tldts';
import { isIP } from 'node:net';
export const DRAINAGE_TARGET_PATTERN =
/^(?:(?:https?:\/\/)?(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{2,59})|(?:\d{1,3}\.){3}\d{1,3})(?::\d{1,5})?(?:[/?#]\S*)?|(?:\+?86[\s-]?)?1(?:[\s-]?\d){10}|(?:\+?86[\s-]?)?(?:\(?0\d{2,3}\)?[\s-]?)?\d{7,8}(?:[\s-]?(?:转|ext\.?)?[\s-]?\d{1,6})?)$/i;
export const DRAINAGE_TARGET_ERROR = '引流信息必须是 URL(可不带协议)、手机号码或固定电话号码';
export function normalizeDrainageTarget(value?: string) {
const target = value?.trim() ?? '';
const normalized = target.normalize('NFKC');
if (!target || !DRAINAGE_TARGET_PATTERN.test(normalized)) return undefined;
if (/[a-z]/i.test(normalized) && !/ext\.?/i.test(normalized)) {
try {
const host = new URL(/^https?:\/\//i.test(normalized) ? normalized : `https://${normalized}`).hostname;
if (!isIP(host) && !parse(host, { allowPrivateDomains: true }).domain) return undefined;
} catch {
return undefined;
}
}
return target;
}
@@ -0,0 +1,10 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { map } from 'rxjs/operators';
import { protocolFieldsToJson } from './protocol-uint32';
@Injectable()
export class ProtocolFieldsInterceptor implements NestInterceptor {
intercept(_context: ExecutionContext, next: CallHandler) {
return next.handle().pipe(map(protocolFieldsToJson));
}
}
+40
View File
@@ -0,0 +1,40 @@
import {
protocolFieldsToJson,
protocolUint32,
protocolUint32FromDb,
protocolUint32ToDb,
parseProtocolSequence,
} from './protocol-uint32';
describe('CMPP unsigned protocol fields', () => {
it.each([0, 2147483647, 2147483648, 4294967295])(
'round trips %s without changing the JSON number contract',
(value) => {
expect(protocolUint32FromDb(protocolUint32ToDb(value))).toBe(value);
expect(
JSON.parse(
JSON.stringify(protocolFieldsToJson({ rows: [{ sequenceId: BigInt(value), ackResult: BigInt(value) }] })),
),
).toEqual({ rows: [{ sequenceId: value, ackResult: value }] });
},
);
it.each([-1, 4294967296, 1.5, NaN, Infinity, '', '0', ' ', {}, true])('rejects invalid wire value %s', (value) => {
expect(() => protocolUint32(value)).toThrow();
expect(() => protocolUint32ToDb(value)).toThrow();
});
it('preserves optional historical nulls and unrelated serializers', () => {
expect(protocolUint32ToDb(null)).toBeUndefined();
expect(protocolUint32FromDb(null)).toBeUndefined();
const date = new Date();
expect(
protocolFieldsToJson({ date, money: 10000n, sequenceId: null, gatewayMessageId: '18446744073709551615' }),
).toEqual({ date, money: 10000n, sequenceId: null, gatewayMessageId: '18446744073709551615' });
expect(() => protocolUint32FromDb(4294967296n)).toThrow();
});
it('distinguishes text zero from missing or malformed historical sequences', () => {
for (const value of [null, undefined, '', ' ', '-1', '1.5', '1e2', '4294967296'])
expect(parseProtocolSequence(value)).toBeUndefined();
expect(parseProtocolSequence('0')).toBe(0);
expect(parseProtocolSequence('4294967295')).toBe(4294967295);
});
});
+39
View File
@@ -0,0 +1,39 @@
import { BadRequestException } from '@nestjs/common';
/** Protocol integers are exact JS numbers on the wire and bigint in PostgreSQL. */
export function protocolUint32(value: unknown, field = 'sequenceId'): number {
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 0xffffffff) {
throw new BadRequestException(`${field} must be an unsigned 32-bit integer`);
}
return value;
}
export function protocolUint32ToDb(value: unknown, field = 'sequenceId'): bigint | undefined {
return value == null ? undefined : BigInt(protocolUint32(value, field));
}
export function protocolUint32FromDb(value: bigint | number | null | undefined): number | undefined {
if (value == null) return undefined;
return protocolUint32(typeof value === 'bigint' ? Number(value) : value);
}
/** Historical Submit sequence columns are text; blanks must never become zero. */
export function parseProtocolSequence(value: string | null | undefined): number | undefined {
if (value == null || !/^\d+$/.test(value)) return undefined;
const number = Number(value);
return Number.isInteger(number) && number <= 0xffffffff ? number : undefined;
}
/** Only protocol fields are converted, leaving money and dates to their existing serializers. */
export function protocolFieldsToJson(value: unknown): unknown {
if (Array.isArray(value)) return value.map(protocolFieldsToJson);
if (!value || typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype) return value;
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
(key === 'sequenceId' || key === 'ackResult') && typeof item === 'bigint'
? protocolUint32FromDb(item)
: protocolFieldsToJson(item),
]),
);
}
+16
View File
@@ -0,0 +1,16 @@
import { summarizeReportStatuses } from './report-status';
describe('summarizeReportStatuses', () => {
it.each([
[[], { status: 'not_applicable', approved: 0, total: 0 }],
[['approved', 'approved'], { status: 'approved', approved: 2, total: 2 }],
[['abandoned', 'abandoned'], { status: 'abandoned', approved: 0, total: 2 }],
[['failed', 'rejected'], { status: 'failed', approved: 0, total: 2 }],
[['approved', 'failed'], { status: 'partial_success', approved: 1, total: 2 }],
[['failed', 'pending'], { status: 'reporting', approved: 0, total: 2 }],
[['waiting_material', 'pending'], { status: 'waiting_material', approved: 0, total: 2 }],
[['abandoned', 'reporting'], { status: 'reporting', approved: 0, total: 2 }],
])('summarizes %j without allowing one failure to override other targets', (statuses, expected) => {
expect(summarizeReportStatuses(statuses)).toEqual(expected);
});
});
+31
View File
@@ -0,0 +1,31 @@
export type ReportStatusSummary = {
status: string;
approved: number;
total: number;
};
const FAILED_REPORT_STATUSES = new Set(['failed', 'rejected']);
export function summarizeReportStatuses(statuses: string[]): ReportStatusSummary {
if (!statuses.length) return { status: 'not_applicable', approved: 0, total: 0 };
const approved = statuses.filter((status) => status === 'approved').length;
const failed = statuses.filter((status) => FAILED_REPORT_STATUSES.has(status)).length;
const abandoned = statuses.filter((status) => status === 'abandoned').length;
if (approved === statuses.length) return { status: 'approved', approved, total: statuses.length };
if (abandoned === statuses.length) return { status: 'abandoned', approved, total: statuses.length };
// Overall failure means every current target failed. A single failed channel must not
// erase successful channels or targets that can still finish reporting.
if (failed === statuses.length) return { status: 'failed', approved, total: statuses.length };
if (approved > 0) return { status: 'partial_success', approved, total: statuses.length };
if (failed > 0) return { status: 'reporting', approved, total: statuses.length };
if (statuses.some((status) => ['reporting', 'exporting', 'partial', 'partial_success'].includes(status))) {
return { status: 'reporting', approved, total: statuses.length };
}
if (statuses.some((status) => status === 'waiting_material')) {
return { status: 'waiting_material', approved, total: statuses.length };
}
return { status: 'pending', approved, total: statuses.length };
}
+4 -1
View File
@@ -8,7 +8,10 @@ export class RequestContextMiddleware implements NestMiddleware {
use(request: RequestLike, _response: unknown, next: () => void) {
const forwarded = request.headers['x-forwarded-for'];
const firstForwarded = Array.isArray(forwarded) ? forwarded[0] : forwarded?.split(',')[0];
const ipAddress = (firstForwarded ?? request.socket?.remoteAddress)?.trim().replace(/^::ffff:/, '');
const remoteAddress = request.socket?.remoteAddress?.trim().replace(/^::ffff:/, '');
const trustedProxies = new Set((process.env.TRUSTED_PROXY_IPS ?? '127.0.0.1,::1').split(',').map((item) => item.trim()).filter(Boolean));
// 仅可信反向代理可以声明客户端地址,防止攻击者伪造 X-Forwarded-For 绕过保护名单或嫁祸他人。
const ipAddress = (remoteAddress && trustedProxies.has(remoteAddress) ? firstForwarded : remoteAddress)?.trim().replace(/^::ffff:/, '');
requestContext.run({ ipAddress }, next);
}
}
@@ -0,0 +1,17 @@
import { BadRequestException } from '@nestjs/common';
import { shanghaiDateRange } from './shanghai-date-range';
describe('shanghaiDateRange', () => {
it('builds an inclusive Asia/Shanghai day range', () => {
expect(shanghaiDateRange('2026-08-01', '2026-08-03')).toEqual({
gte: new Date('2026-08-01T00:00:00+08:00'),
lte: new Date('2026-08-03T23:59:59.999+08:00'),
});
});
it('rejects malformed or reversed ranges', () => {
expect(() => shanghaiDateRange('2026/08/01', undefined)).toThrow(BadRequestException);
expect(() => shanghaiDateRange('2026-02-31', undefined)).toThrow('日期无效');
expect(() => shanghaiDateRange('2026-08-03', '2026-08-01')).toThrow('开始日期不能晚于结束日期');
});
});
+24
View File
@@ -0,0 +1,24 @@
import { BadRequestException } from '@nestjs/common';
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
function parseBoundary(value: string | undefined, endOfDay: boolean) {
if (!value) return undefined;
if (!DATE_PATTERN.test(value)) throw new BadRequestException('日期格式必须为 YYYY-MM-DD');
const [year, month, day] = value.split('-').map(Number);
const calendarDate = new Date(Date.UTC(year, month - 1, day));
if (calendarDate.getUTCFullYear() !== year || calendarDate.getUTCMonth() !== month - 1 || calendarDate.getUTCDate() !== day) {
throw new BadRequestException('日期无效');
}
const parsed = new Date(`${value}T${endOfDay ? '23:59:59.999' : '00:00:00'}+08:00`);
if (Number.isNaN(parsed.getTime())) throw new BadRequestException('日期无效');
return parsed;
}
/** Converts UI calendar dates to an inclusive Asia/Shanghai database range. */
export function shanghaiDateRange(from?: string, to?: string) {
const gte = parseBoundary(from, false);
const lte = parseBoundary(to, true);
if (gte && lte && gte > lte) throw new BadRequestException('开始日期不能晚于结束日期');
return gte || lte ? { gte, lte } : undefined;
}
+9
View File
@@ -0,0 +1,9 @@
import { ValidationPipe } from '@nestjs/common';
export const strictValidationPipe = new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
stopAtFirstError: false,
transformOptions: { enableImplicitConversion: false },
});
@@ -1,8 +1,8 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { CurrentSessionUserId } from '../auth/current-session-user.decorator';
import { CurrentTenantId } from '../auth/current-tenant-id.decorator';
import { RequireRecentAuthentication } from '../auth/require-recent-authentication.decorator';
import { TenantId } from '../common/tenant-id.decorator';
import { DeleteTargetDto, DeletionGovernanceService, DeletionTargetType } from './deletion-governance.service';
@ApiTags('deletion-governance')
@@ -28,13 +28,13 @@ export class ClientDeletionGovernanceController {
constructor(private readonly deletions: DeletionGovernanceService) {}
@Get(':type/:id/preflight')
preflight(@Param('type') type: DeletionTargetType, @Param('id') id: string, @TenantId() tenantId?: string) {
preflight(@Param('type') type: DeletionTargetType, @Param('id') id: string, @CurrentTenantId() tenantId: string) {
return this.deletions.preflight(type, id, tenantId);
}
@Post(':type/:id')
@RequireRecentAuthentication()
delete(@Param('type') type: DeletionTargetType, @Param('id') id: string, @Body() body: DeleteTargetDto, @TenantId() tenantId?: string, @CurrentSessionUserId() operatorId?: string) {
delete(@Param('type') type: DeletionTargetType, @Param('id') id: string, @Body() body: DeleteTargetDto, @CurrentTenantId() tenantId: string, @CurrentSessionUserId() operatorId?: string) {
return this.deletions.delete(type, id, { ...body, operatorId }, tenantId);
}
}
@@ -7,9 +7,13 @@ describe('DeletionGovernanceService', () => {
function setup() {
const tx = {
operationLog: { findFirst: jest.fn(), create: jest.fn() },
smsChannel: { updateMany: jest.fn() },
smsSignature: { updateMany: jest.fn() },
smsTemplate: { updateMany: jest.fn() },
smsChannel: { findUnique: jest.fn(), updateMany: jest.fn() },
smsSignature: { findFirst: jest.fn(), findUnique: jest.fn(), update: jest.fn(), updateMany: jest.fn() },
smsTemplate: { findFirst: jest.fn(), updateMany: jest.fn() },
smsDrainageInfo: { updateMany: jest.fn() },
channelSignatureReportTask: { findMany: jest.fn(), update: jest.fn() },
channelSignatureReportRecord: { create: jest.fn() },
channelRouteRule: { findMany: jest.fn() },
};
const prisma = {
operationLog: { findFirst: jest.fn() },
@@ -35,12 +39,47 @@ describe('DeletionGovernanceService', () => {
expect(result.dependencies[0].items).toEqual(['移动主通道组(优先级 10']);
});
it('allows channel deletion with unfinished report tasks only after the cascade selection is confirmed', async () => {
const { service, prisma, tx } = setup();
const channel = {
id: 'channel-1', name: '移动主通道', code: 'CH-1', status: 'active', updatedAt: now,
groupItems: [], routeRules: [], connectionStates: [],
reportTasks: [{ id: 'report-1', channelId: 'channel-1', signatureId: 'signature-1', reportType: 'signature', status: 'reporting' }],
};
prisma.smsChannel.findUnique.mockResolvedValue(channel);
const preflight = await service.preflight('channel', 'channel-1');
expect(preflight.allowedActions).toEqual(['delete']);
expect(preflight.requiredSelections).toEqual(expect.arrayContaining([
expect.objectContaining({ action: 'abandon_associated_report_tasks', count: 1 }),
]));
prisma.operationLog.findFirst.mockResolvedValue(null);
tx.operationLog.findFirst.mockResolvedValue(null);
tx.smsChannel.findUnique.mockResolvedValue(channel);
tx.channelSignatureReportTask.update.mockResolvedValue({ id: 'report-1' });
tx.channelSignatureReportRecord.create.mockResolvedValue({ id: 'record-1' });
tx.smsChannel.updateMany.mockResolvedValue({ count: 1 });
tx.smsSignature.findUnique.mockResolvedValue({ id: 'signature-1', applicationId: null, auditStatus: 'approved' });
tx.channelSignatureReportTask.findMany.mockResolvedValue([{ channelId: 'channel-1', status: 'abandoned', channel: { id: 'channel-1', status: 'deleted' } }]);
tx.smsSignature.update.mockResolvedValue({ id: 'signature-1' });
tx.operationLog.create.mockResolvedValue({ id: 'operation-1' });
await expect(service.delete('channel', 'channel-1', {
expectedUpdatedAt: now.toISOString(), idempotencyKey: 'delete-channel-1', abandonAssociatedReportTasks: true,
})).resolves.toEqual({ operationId: 'operation-1', status: 'deleted', replayed: false });
expect(tx.channelSignatureReportRecord.create).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ statusAfter: 'abandoned', sourceEntry: 'deletion_governance' }),
}));
expect(tx.smsSignature.update).toHaveBeenCalledWith(expect.objectContaining({ data: { reportStatus: 'not_applicable' } }));
});
it('returns an allowed template preflight scoped to the client tenant', async () => {
const { service, prisma } = setup();
prisma.smsTemplate.findFirst.mockResolvedValue({
id: 'template-1', name: '验证码模板', auditStatus: 'approved', updatedAt: now,
tenant: { name: '示例企业' }, application: { name: '验证码应用' }, signature: { name: '示例签名' },
sendTasks: [], batchTasks: [],
});
const result = await service.preflight('template', 'template-1', 'tenant-1');
@@ -48,30 +87,79 @@ describe('DeletionGovernanceService', () => {
expect(prisma.smsTemplate.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 'template-1', tenantId: 'tenant-1' } }));
expect(result.allowedActions).toEqual(['delete']);
expect(result.identity.tenant).toBe('示例企业');
expect(result.requiredSelections).toEqual([]);
expect(prisma.smsTemplate.findFirst).toHaveBeenCalledWith(expect.objectContaining({
include: expect.not.objectContaining({ sendTasks: expect.anything(), batchTasks: expect.anything() }),
}));
expect(result.impacts).toContain('已创建任务继续使用保存的内容快照');
});
it('blocks signature deletion and exposes the referencing template and drainage items', async () => {
it('turns signature dependencies into mandatory cascade selections', async () => {
const { service, prisma } = setup();
prisma.smsSignature.findFirst.mockResolvedValue({
id: 'signature-1', name: '示例签名', auditStatus: 'approved', updatedAt: now,
tenant: { name: '示例企业' }, application: { name: '验证码应用' },
templates: [{ id: 'template-1', name: '验证码模板' }],
templates: [{ id: 'template-1', name: '验证码模板', sendTasks: [], batchTasks: [] }],
drainageItems: [{ id: 'drainage-1', siteName: '示例站点' }], reportTasks: [],
});
const result = await service.preflight('signature', 'signature-1', 'tenant-1');
expect(result.allowedActions).toEqual([]);
expect(result.allowedActions).toEqual(['delete']);
expect(result.dependencies).toEqual(expect.arrayContaining([
expect.objectContaining({ kind: 'templates', count: 1, items: ['验证码模板(template-1'] }),
expect.objectContaining({ kind: 'drainage', count: 1, items: ['示例站点(drainage-1'] }),
]));
expect(result.requiredSelections.map((item) => item.action)).toEqual([
'delete_associated_templates', 'delete_associated_drainage',
]);
});
it('requires version, idempotency key and a meaningful reason', async () => {
it('does not expose report task ids or statuses to the client but still requires confirmation', async () => {
const { service, prisma } = setup();
prisma.smsSignature.findFirst.mockResolvedValue({
id: 'signature-1', name: '示例签名', auditStatus: 'approved', updatedAt: now,
tenant: { name: '示例企业' }, application: { name: '验证码应用' },
templates: [], drainageItems: [], reportTasks: [{ id: 'internal-task-1', status: 'reporting' }],
});
const result = await service.preflight('signature', 'signature-1', 'tenant-1');
expect(result.dependencies).toEqual(expect.arrayContaining([
expect.objectContaining({ kind: 'report_tasks', count: 1, items: [], detailsVisible: false }),
]));
expect(JSON.stringify(result)).not.toContain('internal-task-1');
expect(result.requiredSelections).toEqual(expect.arrayContaining([
expect.objectContaining({ action: 'abandon_associated_report_tasks' }),
]));
});
it('does not classify approved or abandoned report history as unfinished', async () => {
const { service, prisma } = setup();
prisma.smsSignature.findFirst.mockResolvedValue({
id: 'signature-1', name: '示例签名', auditStatus: 'approved', updatedAt: now,
tenant: { name: '示例企业' }, application: { name: '验证码应用' },
templates: [], drainageItems: [], reportTasks: [],
});
const result = await service.preflight('signature', 'signature-1', 'tenant-1');
expect(prisma.smsSignature.findFirst).toHaveBeenCalledWith(expect.objectContaining({
include: expect.objectContaining({
reportTasks: expect.objectContaining({
where: { status: { notIn: expect.arrayContaining(['approved', 'abandoned']) } },
}),
}),
}));
expect(result.dependencies).toEqual(expect.arrayContaining([
expect.objectContaining({ kind: 'report_tasks', count: 0 }),
]));
expect(result.allowedActions).toEqual(['delete']);
});
it('requires version and idempotency key but allows an omitted reason', async () => {
const { service } = setup();
await expect(service.delete('template', 'template-1', {})).rejects.toBeInstanceOf(BadRequestException);
await expect(service.delete('template', 'template-1', { expectedUpdatedAt: now.toISOString(), idempotencyKey: 'key', reason: '短' })).rejects.toBeInstanceOf(BadRequestException);
});
it('soft deletes once and writes an auditable operation number', async () => {
@@ -80,19 +168,71 @@ describe('DeletionGovernanceService', () => {
prisma.smsTemplate.findFirst.mockResolvedValue({
id: 'template-1', name: '验证码模板', auditStatus: 'approved', updatedAt: now,
tenant: { name: '示例企业' }, application: { name: '验证码应用' }, signature: null,
sendTasks: [], batchTasks: [],
});
tx.operationLog.findFirst.mockResolvedValue(null);
tx.smsTemplate.findFirst.mockResolvedValue({
id: 'template-1', tenantId: 'tenant-1',
});
tx.smsTemplate.updateMany.mockResolvedValue({ count: 1 });
tx.operationLog.create.mockResolvedValue({ id: 'operation-1' });
const result = await service.delete('template', 'template-1', {
expectedUpdatedAt: now.toISOString(), idempotencyKey: 'delete-template-1', reason: '测试删除治理', operatorId: 'user-1',
expectedUpdatedAt: now.toISOString(), idempotencyKey: 'delete-template-1', operatorId: 'user-1',
}, 'tenant-1');
expect(result).toEqual({ operationId: 'operation-1', status: 'deleted', replayed: false });
expect(tx.smsTemplate.findFirst).toHaveBeenCalledWith({
where: { id: 'template-1', tenantId: 'tenant-1' },
select: { id: true, tenantId: true },
});
expect(tx.smsTemplate.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: { auditStatus: 'deleted' } }));
expect(tx.operationLog.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ action: 'governance.delete', userId: 'user-1' }) }));
});
it('cascades all selected signature dependencies in one transaction with task history', async () => {
const { service, prisma, tx } = setup();
const preflightItem = {
id: 'signature-1', tenantId: 'tenant-1', name: '示例签名', auditStatus: 'approved', updatedAt: now,
tenant: { name: '示例企业' }, application: { name: '验证码应用' },
templates: [{ id: 'template-1', name: '验证码模板', sendTasks: [], batchTasks: [] }],
drainageItems: [{ id: 'drainage-1', siteName: '示例站点' }],
reportTasks: [{ id: 'report-1', channelId: 'channel-1', signatureId: 'signature-1', reportType: 'signature', status: 'reporting' }],
};
prisma.operationLog.findFirst.mockResolvedValue(null);
prisma.smsSignature.findFirst.mockResolvedValue(preflightItem);
tx.operationLog.findFirst.mockResolvedValue(null);
tx.smsSignature.findFirst.mockResolvedValue(preflightItem);
tx.smsTemplate.updateMany.mockResolvedValue({ count: 1 });
tx.smsDrainageInfo.updateMany.mockResolvedValue({ count: 1 });
tx.channelSignatureReportTask.update.mockResolvedValue({ id: 'report-1' });
tx.channelSignatureReportRecord.create.mockResolvedValue({ id: 'record-1' });
tx.smsSignature.updateMany.mockResolvedValue({ count: 1 });
tx.operationLog.create.mockResolvedValue({ id: 'operation-1' });
const result = await service.delete('signature', 'signature-1', {
expectedUpdatedAt: now.toISOString(), idempotencyKey: 'delete-signature-1', operatorId: 'user-1',
deleteAssociatedTemplates: true, deleteAssociatedDrainage: true, abandonAssociatedReportTasks: true,
}, 'tenant-1');
expect(result).toEqual({ operationId: 'operation-1', status: 'deleted', replayed: false });
expect(tx.smsTemplate.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: { auditStatus: 'deleted' } }));
expect(tx.operationLog.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ action: 'governance.delete', userId: 'user-1' }) }));
expect(tx.smsDrainageInfo.updateMany).toHaveBeenCalledWith(expect.objectContaining({ data: { auditStatus: 'deleted', pendingReport: false } }));
expect(tx.channelSignatureReportTask.update).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ status: 'abandoned' }) }));
expect(tx.channelSignatureReportRecord.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ statusBefore: 'reporting', statusAfter: 'abandoned', sourceEntry: 'deletion_governance' }) }));
});
it('rejects deletion until every discovered cascade selection is confirmed', async () => {
const { service, prisma } = setup();
prisma.operationLog.findFirst.mockResolvedValue(null);
prisma.smsSignature.findFirst.mockResolvedValue({
id: 'signature-1', name: '示例签名', auditStatus: 'approved', updatedAt: now,
tenant: { name: '示例企业' }, application: { name: '验证码应用' },
templates: [{ id: 'template-1', name: '验证码模板', sendTasks: [], batchTasks: [] }], drainageItems: [], reportTasks: [],
});
await expect(service.delete('signature', 'signature-1', {
expectedUpdatedAt: now.toISOString(), idempotencyKey: 'missing-selection',
}, 'tenant-1')).rejects.toBeInstanceOf(BadRequestException);
});
it('rejects a stale optimistic-lock version', async () => {
@@ -101,7 +241,6 @@ describe('DeletionGovernanceService', () => {
prisma.smsTemplate.findFirst.mockResolvedValue({
id: 'template-1', name: '验证码模板', auditStatus: 'approved', updatedAt: now,
tenant: { name: '示例企业' }, application: { name: '验证码应用' }, signature: null,
sendTasks: [], batchTasks: [],
});
await expect(service.delete('template', 'template-1', {
expectedUpdatedAt: '2026-07-20T10:00:00.000Z', idempotencyKey: 'stale', reason: '测试版本冲突',

Some files were not shown because too many files have changed in this diff Show More