AI规范准则生成 README.md初始化

This commit is contained in:
2025-11-10 15:48:47 +08:00
parent eb8a759d4d
commit 2413baf945
5 changed files with 456 additions and 60 deletions

View File

@@ -1,50 +1,225 @@
# [PROJECT_NAME] Constitution
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
<!--
SYNC IMPACT REPORT - Constitution Amendment
============================================
Version Change: INITIAL → 1.0.0
Date: 2025-11-10
NEW PRINCIPLES ESTABLISHED:
- I. Tech Stack Adherence (Fiber 生态系统)
- II. Code Quality Standards (代码质量标准)
- III. Testing Standards (测试标准)
- IV. User Experience Consistency (用户体验一致性)
- V. Performance Requirements (性能要求)
SECTIONS ADDED:
- Development Workflow (开发工作流程)
- Quality Gates (质量关卡)
TEMPLATES REQUIRING UPDATES:
✅ .specify/templates/plan-template.md - Constitution Check section aligned
✅ .specify/templates/spec-template.md - Requirements section aligned with principles
✅ .specify/templates/tasks-template.md - Task organization reflects quality gates
FOLLOW-UP ACTIONS:
- None - all placeholders resolved
RATIONALE:
Initial constitution establishment for 君鸿卡管系统 project. Major version 1.0.0
as this is the first formal governance document defining core development principles.
-->
# 君鸿卡管系统 Constitution
## Core Principles
### [PRINCIPLE_1_NAME]
<!-- Example: I. Library-First -->
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### I. Tech Stack Adherence (技术栈遵守)
### [PRINCIPLE_2_NAME]
<!-- Example: II. CLI Interface -->
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
**规则 (RULES):**
### [PRINCIPLE_3_NAME]
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
- 开发时 **MUST** 严格遵守项目定义的技术栈Fiber + GORM + Viper + Zap + Lumberjack.v2 + Validator + sonic JSON + Asynq + PostgreSQL
- **MUST NOT** 使用原生调用或绕过框架的快捷方式(禁止 `database/sql` 直接调用、禁止 `net/http` 替代 Fiber、禁止 `encoding/json` 替代 sonic
- 所有 HTTP 路由和中间件 **MUST** 使用 Fiber 框架
- 所有数据库操作 **MUST** 通过 GORM 进行
- 所有配置管理 **MUST** 使用 Viper
- 所有日志记录 **MUST** 使用 Zap + Lumberjack.v2
- 所有 JSON 序列化 **MUST** 使用 sonic
- 所有异步任务 **MUST** 使用 Asynq
### [PRINCIPLE_4_NAME]
<!-- Example: IV. Integration Testing -->
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
**理由 (RATIONALE):**
### [PRINCIPLE_5_NAME]
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
[PRINCIPLE_5_DESCRIPTION]
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
一致的技术栈使用确保代码可维护性、团队协作效率和长期技术债务可控。绕过框架的"快捷方式"会导致代码碎片化、难以调试、性能不一致和安全漏洞。框架选择已经过深思熟虑,必须信任并充分利用其生态系统。
## [SECTION_2_NAME]
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
---
[SECTION_2_CONTENT]
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
### II. Code Quality Standards (代码质量标准)
## [SECTION_3_NAME]
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
**规则 (RULES):**
[SECTION_3_CONTENT]
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
- 代码 **MUST** 遵循项目分层架构:`Handler → Service → Store → Model`
- Handler 层 **MUST ONLY** 处理 HTTP 请求/响应,不得包含业务逻辑
- Service 层 **MUST** 包含所有业务逻辑,支持跨模块调用
- Store 层 **MUST** 统一管理所有数据访问,支持事务处理
- Model 层 **MUST** 定义清晰的数据结构和 DTO
- 所有依赖 **MUST** 通过 `Service``Store` 结构体进行依赖注入
- 所有公共错误 **MUST**`pkg/errors/` 中定义,使用统一错误码
- 所有 API 响应 **MUST** 使用 `pkg/response/` 的统一格式
- **MUST** 为所有公共函数编写清晰的注释(英文或中文)
- **MUST** 避免 magic numbers 和 magic strings使用常量定义
**理由 (RATIONALE):**
清晰的分层架构和代码组织使代码易于理解、测试和维护。统一的错误处理和响应格式提升 API 一致性和客户端集成体验。依赖注入模式便于单元测试和模块替换。
---
### III. Testing Standards (测试标准)
**规则 (RULES):**
- 所有核心业务逻辑Service 层)**MUST** 有单元测试覆盖
- 所有 API 端点 **MUST** 有集成测试覆盖
- 所有数据库操作 **SHOULD** 有事务回滚测试
- 测试 **MUST** 使用 Go 标准测试框架(`testing` 包)
- 测试文件 **MUST** 与源文件同目录,命名为 `*_test.go`
- 测试 **MUST** 可独立运行,不依赖外部服务(使用 mock 或 testcontainers
- 单元测试 **MUST** 在 100ms 内完成
- 集成测试 **SHOULD** 在 1s 内完成
- 测试覆盖率 **SHOULD** 达到 70% 以上(核心业务代码必须 90% 以上)
**理由 (RATIONALE):**
高质量的测试是代码质量的基石。单元测试确保业务逻辑正确性,集成测试确保模块间协作正常。快速的测试执行时间保证开发效率。测试独立性避免环境依赖导致的 flaky tests。
---
### IV. User Experience Consistency (用户体验一致性)
**规则 (RULES):**
- 所有 API 响应 **MUST** 使用统一的 JSON 格式:
```json
{
"code": 0,
"message": "success",
"data": {},
"timestamp": "2025-11-10T15:30:00Z"
}
```
- 所有错误响应 **MUST** 包含明确的错误码和错误消息(中英文双语)
- 所有 API 端点 **MUST** 遵循 RESTful 设计原则
- 所有分页 API **MUST** 使用统一的分页参数:`page`、`page_size`、`total`
- 所有时间字段 **MUST** 使用 ISO 8601 格式RFC3339
- 所有货币金额 **MUST** 使用整数表示(分为单位),避免浮点精度问题
- 所有布尔字段 **MUST** 使用 `true`/`false`,不使用 `0`/`1`
- API 版本 **MUST** 通过 URL 路径管理(如 `/api/v1/...`
**理由 (RATIONALE):**
一致的 API 设计降低客户端开发成本,减少集成错误。统一的数据格式和错误处理提升系统可预测性。清晰的时间和金额表示避免常见的数据处理错误。
---
### V. Performance Requirements (性能要求)
**规则 (RULES):**
- API 响应时间P95**MUST** < 200ms数据库查询 < 50ms
- API 响应时间P99**MUST** < 500ms
- 批量操作 **MUST** 使用批量查询/插入,避免 N+1 查询问题
- 所有数据库查询 **MUST** 有适当的索引支持
- 列表查询 **MUST** 实现分页,默认 `page_size=20`,最大 `page_size=100`
- 异步任务 **MUST** 用于非实时操作(批量同步、分佣计算等)
- 内存使用API 服务)**SHOULD** < 500MB正常负载
- 内存使用Worker 服务)**SHOULD** < 1GB正常负载
- 数据库连接池 **MUST** 配置合理(`MaxOpenConns=25`, `MaxIdleConns=10`, `ConnMaxLifetime=5m`
- Redis 连接池 **MUST** 配置合理(`PoolSize=10`, `MinIdleConns=5`
**理由 (RATIONALE):**
性能要求确保系统在生产环境下的稳定性和用户体验。批量操作和异步任务避免阻塞主流程。合理的连接池配置平衡性能和资源消耗。明确的性能指标便于监控和优化。
---
## Development Workflow (开发工作流程)
### 分支管理
- **MUST** 从 `main` 分支创建功能分支
- 功能分支命名格式:`feature/###-brief-description` 或 `fix/###-brief-description`
- **MUST** 在合并前保持分支与 `main` 同步rebase 或 merge
- 合并到 `main` **MUST** 通过 Pull Request 并经过代码审查
### 提交规范
- 提交信息 **MUST** 遵循 Conventional Commits 格式:
- `feat: 新功能描述`
- `fix: 修复问题描述`
- `refactor: 重构描述`
- `test: 测试相关`
- `docs: 文档更新`
- `chore: 构建/工具相关`
- 提交信息 **SHOULD** 简洁明了(中文或英文)
### 代码审查
- 所有 PR **MUST** 至少有一人审查通过
- 审查者 **MUST** 验证:
- 代码符合本宪章所有原则
- 测试覆盖充分且通过
- 无安全漏洞SQL 注入、XSS、命令注入等
- 性能影响可接受
---
## Quality Gates (质量关卡)
### 代码合并前检查
- [ ] 所有测试通过(`go test ./...`
- [ ] 代码格式化(`gofmt` 或 `goimports`
- [ ] 代码静态检查通过(`go vet` 和 `golangci-lint`
- [ ] 测试覆盖率符合标准
- [ ] 无 TODO/FIXME 遗留(或已记录 Issue
- [ ] API 文档已更新(如有 API 变更)
- [ ] 数据库迁移文件已创建(如有 schema 变更)
### 上线前检查
- [ ] 所有功能在 staging 环境测试通过
- [ ] 性能测试通过(响应时间、内存使用、并发能力)
- [ ] 数据库迁移在 staging 环境验证通过
- [ ] 监控和告警配置完成
- [ ] 回滚方案已准备
---
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
本宪章是所有开发实践的最高指导原则,优先级高于个人偏好或临时便利。
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
### 修订流程
- 宪章修订 **MUST** 经过团队讨论并达成共识
- 修订 **MUST** 包含明确的理由和影响分析
- 修订 **MUST** 更新版本号(遵循语义化版本)
- 修订 **MUST** 同步更新相关模板plan-template.md、spec-template.md、tasks-template.md
### 版本策略
- **MAJOR**: 移除或重新定义核心原则(不兼容变更)
- **MINOR**: 新增原则或显著扩展指导内容
- **PATCH**: 澄清说明、措辞优化、错误修正
### 合规审查
- 所有 PR 审查 **MUST** 验证是否符合本宪章
- 违反宪章的代码 **MUST** 在合并前修正
- 任何复杂性增加(新依赖、新架构层)**MUST** 在设计文档中明确说明必要性
### 运行时开发指导
开发时参考本宪章确保一致性。如有疑问,优先遵守原则,再讨论例外情况。
---
**Version**: 1.0.0 | **Ratified**: 2025-11-10 | **Last Amended**: 2025-11-10

View File

@@ -31,7 +31,44 @@
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
[Gates determined based on constitution file]
**Tech Stack Adherence**:
- [ ] Feature uses Fiber + GORM + Viper + Zap + Lumberjack.v2 + Validator + sonic JSON + Asynq + PostgreSQL
- [ ] No native calls bypass framework (no `database/sql`, `net/http`, `encoding/json` direct use)
- [ ] All HTTP operations use Fiber framework
- [ ] All database operations use GORM
- [ ] All async tasks use Asynq
**Code Quality Standards**:
- [ ] Follows Handler → Service → Store → Model architecture
- [ ] Handler layer only handles HTTP, no business logic
- [ ] Service layer contains business logic with cross-module support
- [ ] Store layer manages all data access with transaction support
- [ ] Uses dependency injection via Service/Store structs
- [ ] Unified error codes in `pkg/errors/`
- [ ] Unified API responses via `pkg/response/`
**Testing Standards**:
- [ ] Unit tests for all core business logic (Service layer)
- [ ] Integration tests for all API endpoints
- [ ] Tests use Go standard testing framework
- [ ] Tests are independent (no external service dependencies)
- [ ] Target coverage: 70%+ overall, 90%+ for core business
**User Experience Consistency**:
- [ ] All APIs use unified JSON response format
- [ ] Error responses include clear error codes and bilingual messages
- [ ] RESTful design principles followed
- [ ] Unified pagination parameters (page, page_size, total)
- [ ] Time fields use ISO 8601 format (RFC3339)
- [ ] Currency amounts use integers (cents) to avoid float precision issues
**Performance Requirements**:
- [ ] API response time (P95) < 200ms, (P99) < 500ms
- [ ] Batch operations use bulk queries/inserts
- [ ] All database queries have appropriate indexes
- [ ] List queries implement pagination (default 20, max 100)
- [ ] Non-realtime operations use async tasks
- [ ] Database and Redis connection pools properly configured
## Project Structure

View File

@@ -95,6 +95,43 @@
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
### Technical Requirements (Constitution-Driven)
**Tech Stack Compliance**:
- [ ] All HTTP operations use Fiber framework (no `net/http` shortcuts)
- [ ] All database operations use GORM (no `database/sql` direct calls)
- [ ] All JSON operations use sonic (no `encoding/json` usage)
- [ ] All async tasks use Asynq
- [ ] All logging uses Zap + Lumberjack.v2
- [ ] All configuration uses Viper
**Architecture Requirements**:
- [ ] Implementation follows Handler → Service → Store → Model layers
- [ ] Dependencies injected via Service/Store structs
- [ ] Unified error codes defined in `pkg/errors/`
- [ ] Unified API responses via `pkg/response/`
**API Design Requirements**:
- [ ] All APIs follow RESTful principles
- [ ] All responses use unified JSON format with code/message/data/timestamp
- [ ] All error messages include error codes and bilingual descriptions
- [ ] All pagination uses standard parameters (page, page_size, total)
- [ ] All time fields use ISO 8601 format (RFC3339)
- [ ] All currency amounts use integers (cents)
**Performance Requirements**:
- [ ] API response time (P95) < 200ms
- [ ] Database queries < 50ms
- [ ] Batch operations use bulk queries
- [ ] List queries implement pagination (default 20, max 100)
- [ ] Non-realtime operations delegated to async tasks
**Testing Requirements**:
- [ ] Unit tests for all Service layer business logic
- [ ] Integration tests for all API endpoints
- [ ] Tests are independent and use mocks/testcontainers
- [ ] Target coverage: 70%+ overall, 90%+ for core business logic
### Key Entities *(include if feature involves data)*
- **[Entity 1]**: [What it represents, key attributes without implementation]

View File

@@ -48,9 +48,11 @@ description: "Task list template for feature implementation"
**Purpose**: Project initialization and basic structure
- [ ] T001 Create project structure per implementation plan
- [ ] T002 Initialize [language] project with [framework] dependencies
- [ ] T003 [P] Configure linting and formatting tools
- [ ] T001 Create project structure per implementation plan (internal/, pkg/, cmd/)
- [ ] T002 Initialize Go project with Fiber + GORM + Viper + Zap + Asynq dependencies
- [ ] T003 [P] Configure linting (golangci-lint) and formatting tools (gofmt/goimports)
- [ ] T004 [P] Setup unified error codes in pkg/errors/
- [ ] T005 [P] Setup unified API response in pkg/response/
---
@@ -60,14 +62,20 @@ description: "Task list template for feature implementation"
**⚠️ CRITICAL**: No user story work can begin until this phase is complete
Examples of foundational tasks (adjust based on your project):
Foundational tasks for 君鸿卡管系统 tech stack:
- [ ] T004 Setup database schema and migrations framework
- [ ] T005 [P] Implement authentication/authorization framework
- [ ] T006 [P] Setup API routing and middleware structure
- [ ] T007 Create base models/entities that all stories depend on
- [ ] T008 Configure error handling and logging infrastructure
- [ ] T009 Setup environment configuration management
- [ ] T006 Setup PostgreSQL database connection via GORM with connection pool (MaxOpenConns=25, MaxIdleConns=10)
- [ ] T007 Setup Redis connection with connection pool (PoolSize=10, MinIdleConns=5)
- [ ] T008 [P] Setup database migrations framework (golang-migrate or GORM AutoMigrate)
- [ ] T009 [P] Implement Fiber routing structure in internal/router/
- [ ] T010 [P] Implement Fiber middleware (authentication, logging, recovery, validation) in internal/handler/middleware/
- [ ] T011 [P] Setup Zap logger with Lumberjack rotation in pkg/logger/
- [ ] T012 [P] Setup Viper configuration management in pkg/config/
- [ ] T013 [P] Setup Asynq task queue client and server in pkg/queue/
- [ ] T014 [P] Setup Validator integration in pkg/validator/
- [ ] T015 Create base Store structure with transaction support in internal/store/
- [ ] T016 Create base Service structure with dependency injection in internal/service/
- [ ] T017 Setup sonic JSON as default serializer for Fiber
**Checkpoint**: Foundation ready - user story implementation can now begin in parallel
@@ -79,21 +87,28 @@ Examples of foundational tasks (adjust based on your project):
**Independent Test**: [How to verify this story works on its own]
### Tests for User Story 1 (OPTIONAL - only if tests requested) ⚠️
### Tests for User Story 1 (REQUIRED per Constitution - Testing Standards) ⚠️
> **NOTE: Write these tests FIRST, ensure they FAIL before implementation**
- [ ] T010 [P] [US1] Contract test for [endpoint] in tests/contract/test_[name].py
- [ ] T011 [P] [US1] Integration test for [user journey] in tests/integration/test_[name].py
- [ ] T020 [P] [US1] Unit tests for Service layer business logic in internal/service/[service]_test.go
- [ ] T021 [P] [US1] Integration tests for API endpoints in internal/handler/[handler]_test.go
- [ ] T022 [P] [US1] Transaction rollback tests for Store layer in internal/store/[store]_test.go
### Implementation for User Story 1
- [ ] T012 [P] [US1] Create [Entity1] model in src/models/[entity1].py
- [ ] T013 [P] [US1] Create [Entity2] model in src/models/[entity2].py
- [ ] T014 [US1] Implement [Service] in src/services/[service].py (depends on T012, T013)
- [ ] T015 [US1] Implement [endpoint/feature] in src/[location]/[file].py
- [ ] T016 [US1] Add validation and error handling
- [ ] T017 [US1] Add logging for user story 1 operations
- [ ] T023 [P] [US1] Create [Entity1] model with GORM tags in internal/model/[entity1].go
- [ ] T024 [P] [US1] Create [Entity2] model with GORM tags in internal/model/[entity2].go
- [ ] T025 [P] [US1] Create DTOs and request/response structs in internal/model/dto/[feature].go
- [ ] T026 [US1] Implement Store methods with GORM in internal/store/postgres/[store].go (depends on T023, T024)
- [ ] T027 [US1] Implement Service business logic in internal/service/[service].go (depends on T026)
- [ ] T028 [US1] Implement Fiber Handler in internal/handler/[handler].go (depends on T027)
- [ ] T029 [US1] Register routes in internal/router/router.go
- [ ] T030 [US1] Add validation rules using Validator in Handler
- [ ] T031 [US1] Add unified error handling using pkg/errors/ and pkg/response/
- [ ] T032 [US1] Add Zap logging with structured fields
- [ ] T033 [US1] Add database indexes for queries (if needed)
- [ ] T034 [US1] Create Asynq tasks for async operations (if needed) in internal/task/[task].go
**Checkpoint**: At this point, User Story 1 should be fully functional and testable independently
@@ -146,16 +161,24 @@ Examples of foundational tasks (adjust based on your project):
---
## Phase N: Polish & Cross-Cutting Concerns
## Phase N: Polish & Quality Gates
**Purpose**: Improvements that affect multiple user stories
**Purpose**: Improvements that affect multiple user stories and final quality checks
- [ ] TXXX [P] Documentation updates in docs/
- [ ] TXXX Code cleanup and refactoring
- [ ] TXXX Performance optimization across all stories
- [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/
- [ ] TXXX Security hardening
- [ ] TXXX Performance optimization and load testing (verify P95 < 200ms, P99 < 500ms)
- [ ] TXXX [P] Additional unit tests to reach 70%+ coverage (90%+ for core business)
- [ ] TXXX Security audit (SQL injection, XSS, command injection prevention)
- [ ] TXXX Run quickstart.md validation
- [ ] TXXX Quality Gate: Run `go test ./...` (all tests pass)
- [ ] TXXX Quality Gate: Run `gofmt -l .` (no formatting issues)
- [ ] TXXX Quality Gate: Run `go vet ./...` (no issues)
- [ ] TXXX Quality Gate: Run `golangci-lint run` (no issues)
- [ ] TXXX Quality Gate: Verify test coverage with `go test -cover ./...`
- [ ] TXXX Quality Gate: Check no TODO/FIXME remains (or documented in issues)
- [ ] TXXX Quality Gate: Verify database migrations work correctly
- [ ] TXXX Quality Gate: Verify API documentation updated (if API changes)
---

124
READEME.md Normal file
View File

@@ -0,0 +1,124 @@
# 君鸿卡管系统
## 系统简介
物联网卡 + 号卡全生命周期管理平台,支持代理商体系和分佣结算。
**技术栈**Fiber + GORM + Viper + Zap + Lumberjack.v2 + Validator + sonic JSON + Asynq + PostgreSQL
**核心功能**
- 物联网卡/号卡生命周期管理(开卡、激活、停机、复机、销户)
- 代理商层级管理和分佣结算
- 批量状态同步(卡状态、实名状态、流量使用情况)
- 与外部 Gateway 服务通过 RESTful API 交互
---
## 项目结构
```
junhong_cmp_fiber/
├── cmd/ # 应用程序入口
│ ├── api/ # HTTP API 服务
│ └── worker/ # Asynq 异步任务 Worker
├── internal/ # 私有业务代码
│ ├── handler/ # HTTP 处理层
│ │ └── middleware/ # 中间件(认证、日志、恢复、验证)
│ ├── service/ # 业务逻辑层(核心业务)
│ ├── store/ # 数据访问层
│ │ └── postgres/ # PostgreSQL 实现
│ ├── model/ # 数据模型实体、DTO
│ ├── task/ # Asynq 任务定义和处理
│ ├── gateway/ # Gateway 服务 HTTP 客户端
│ └── router/ # 路由注册
├── pkg/ # 公共工具库
│ ├── config/ # 配置管理Viper
│ ├── logger/ # 日志Zap + Lumberjack
│ ├── database/ # 数据库初始化PostgreSQL + Redis
│ ├── queue/ # 队列封装Asynq
│ ├── response/ # 统一响应格式
│ ├── errors/ # 错误码定义
│ └── validator/ # 验证器封装
├── config/ # 配置文件yaml
├── migrations/ # 数据库迁移文件
├── scripts/ # 脚本工具
└── docs/ # 文档
```
---
## 架构设计
### 分层架构
```
Handler (HTTP) → Service (业务逻辑) → Store (数据访问) → Model (数据模型)
```
### 双服务架构
- **API 服务**:处理 HTTP 请求,快速响应
- **Worker 服务**:处理异步任务(批量同步、分佣计算等),独立部署
### 核心模块
- **Service 层**:统一管理所有业务逻辑,支持跨模块调用
- **Store 层**:统一管理所有数据访问,支持事务
- **Task 层**Asynq 任务处理器,支持定时任务和事件触发
---
## 开发规范
### 依赖注入
通过 `Service``Store` 结构体统一管理依赖:
```go
// 初始化
st := store.New(db)
svc := service.New(st, queueClient, logger)
// 使用
svc.SIM.Activate(...)
svc.Commission.Calculate(...)
```
### 事务处理
```go
store.Transaction(ctx, func(tx *store.Store) error {
tx.SIM.UpdateStatus(...)
tx.Commission.Create(...)
return nil
})
```
### 异步任务
- 高频任务:批量状态同步、流量同步、实名检查
- 业务任务:分佣计算、生命周期变更通知
- 任务优先级critical > default > low
---
## 快速开始
### 配置
编辑 `config/config.yaml` 配置数据库和 Redis 连接
### 启动 API 服务
```bash
go run cmd/api/main.go
```
### 启动 Worker 服务
```bash
go run cmd/worker/main.go
```
---
## 设计原则
- **简单实用**:不过度设计,够用就好
- **直接实现**:避免不必要的接口抽象
- **统一管理**:依赖集中初始化,避免参数传递
- **职责分离**API 和 Worker 独立部署,便于扩展