docs(camel_oil): 新增骆驼加油相关功能文档

- 添加骆驼加油API端点设计及系统架构文档
- 新增定时任务模块详细说明及任务流程图
- 完成订单管理服务功能及架构介绍
- 增加账号管理模块设计与状态机说明
- 集成Pig接码平台文档,介绍验证码检测流程
- 详细列出各组件的依赖关系及性能优化措施
- 提供故障排除指南及系统扩展性总结
This commit is contained in:
danial
2025-11-21 15:04:55 +08:00
parent f83fabde5c
commit 80f605877f
12 changed files with 2062 additions and 24 deletions

View File

@@ -0,0 +1,210 @@
# 骆驼加油API端点
<cite>
**本文档中引用的文件**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [account.go](file://api/camel_oil/v1/account.go)
- [order.go](file://api/camel_oil/v1/order.go)
- [camel_oil_v1_list_account.go](file://internal/controller/camel_oil/camel_oil_v1_list_account.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
- [v_1_camel_oil_account.go](file://internal/dao/internal/v_1_camel_oil_account.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了骆驼加油Camel OilAPI模块的端点设计功能实现和系统架构该模块主要服务于JD V2平台的账号与订单管理提供完整的账号生命周期管理和订单处理能力API设计遵循GoFrame框架规范采用分层架构实现高内聚低耦合
## 项目结构
骆驼加油模块位于`api/camel_oil`目录下采用版本化API设计包含v1版本的账号和订单管理接口控制器位于`internal/controller/camel_oil`目录服务层位于`internal/service`数据访问层由GoFrame自动生成
```mermaid
graph TB
subgraph "API层"
A[api/camel_oil]
A1[v1/account.go]
A2[v1/order.go]
A3[camel_oil.go]
end
subgraph "控制层"
B[internal/controller/camel_oil]
B1[camel_oil_v1_list_account.go]
B2[camel_oil_v1_submit_order.go]
end
subgraph "服务层"
C[internal/service]
C1[camel_oil.go]
end
subgraph "数据层"
D[internal/dao/internal]
D1[v_1_camel_oil_account.go]
end
A --> B
B --> C
C --> D
```
**Diagram sources**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_v1_list_account.go](file://internal/controller/camel_oil/camel_oil_v1_list_account.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
- [v_1_camel_oil_account.go](file://internal/dao/internal/v_1_camel_oil_account.go)
**Section sources**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_v1_list_account.go](file://internal/controller/camel_oil/camel_oil_v1_list_account.go)
## 核心组件
骆驼加油模块的核心组件包括账号管理订单处理和状态监控三大功能模块通过`ICamelOilV1`接口定义了11个API端点涵盖账号列表查询状态检测订单提交订单查询等关键业务功能服务层`ICamelOil`接口提供了50多个方法支持完整的业务逻辑处理
**Section sources**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
## 架构概述
系统采用典型的分层架构设计从上至下分为API层控制层服务层和数据访问层API层定义接口契约控制层处理HTTP请求转发服务层实现核心业务逻辑数据访问层负责数据库操作各层之间通过接口解耦确保系统的可维护性和可扩展性
```mermaid
graph TD
Client[客户端] --> API[API层]
API --> Controller[控制层]
Controller --> Service[服务层]
Service --> DAO[数据访问层]
DAO --> DB[(数据库)]
style Client fill:#f9f,stroke:#333
style API fill:#bbf,stroke:#333
style Controller fill:#f96,stroke:#333
style Service fill:#6f9,stroke:#333
style DAO fill:#69f,stroke:#333
style DB fill:#9f9,stroke:#333
```
**Diagram sources**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_v1_list_account.go](file://internal/controller/camel_oil/camel_oil_v1_list_account.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
## 详细组件分析
### 账号管理组件分析
账号管理组件提供完整的账号生命周期管理功能包括账号列表查询状态检测历史记录查询和统计信息获取通过`ListAccountReq`请求结构体定义了分页查询参数支持状态筛选和关键词搜索
#### 对象导向组件
```mermaid
classDiagram
class ListAccountReq {
+path : /jd-v2/account/list
+tags : JD V2 Account
+method : get
+summary : 账号列表
+CommonPageReq
+Status : CamelOilAccountStatus
+Keyword : string
}
class AccountListItem {
+AccountId : int64
+AccountName : string
+Phone : string
+Status : CamelOilAccountStatus
+StatusText : string
+DailyOrderCount : int
+DailyOrderDate : string
+TotalOrderCount : int
+LastUsedAt : gtime.Time
+LastLoginAt : gtime.Time
+TokenExpireAt : gtime.Time
+RemainingOrders : int
+FailureReason : string
+Remark : string
+CreatedAt : gtime.Time
+UpdatedAt : gtime.Time
}
class ListAccountRes {
+CommonPageRes~AccountListItem~
}
ListAccountReq --> ListAccountRes : "返回"
AccountListItem --> ListAccountRes : "包含"
```
**Diagram sources**
- [account.go](file://api/camel_oil/v1/account.go)
**Section sources**
- [account.go](file://api/camel_oil/v1/account.go)
- [camel_oil_v1_list_account.go](file://internal/controller/camel_oil/camel_oil_v1_list_account.go)
### 订单处理组件分析
订单处理组件负责订单的全生命周期管理包括订单提交列表查询详情获取历史记录和手动回调通过`SubmitOrderReq`定义了订单提交的必要参数包括金额商户订单号和附加信息
#### API/服务组件
```mermaid
sequenceDiagram
participant Client as "客户端"
participant API as "API网关"
participant Controller as "ControllerV1"
participant Service as "CamelOil服务"
Client->>API : POST /jd-v2/order/submit
API->>Controller : 转发SubmitOrder请求
Controller->>Service : 调用SubmitOrder方法
Service-->>Controller : 返回SubmitOrderRes
Controller-->>API : 返回响应
API-->>Client : 返回订单号和支付链接
Note over Client,Service : 提交订单流程
```
**Diagram sources**
- [order.go](file://api/camel_oil/v1/order.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
**Section sources**
- [order.go](file://api/camel_oil/v1/order.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
## 依赖分析
骆驼加油模块依赖多个核心组件包括公共API模块常量定义GoFrame框架等通过接口注入方式实现服务层的依赖管理确保各组件之间的松耦合数据库依赖通过GoFrame的DAO模式实现自动生成数据访问代码
```mermaid
graph LR
CamelOil[骆驼加油模块] --> CommonApi[commonApi]
CamelOil --> Consts[consts]
CamelOil --> GoFrame[github.com/gogf/gf/v2]
CamelOil --> Service[service]
Service --> DAO[dao]
DAO --> Database[(数据库)]
style CamelOil fill:#f96,stroke:#333
style CommonApi fill:#69f,stroke:#333
style Consts fill:#69f,stroke:#333
style GoFrame fill:#69f,stroke:#333
style Service fill:#6f9,stroke:#333
style DAO fill:#69f,stroke:#333
```
**Diagram sources**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
**Section sources**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
## 性能考虑
系统在设计时充分考虑了性能因素采用分页查询避免大数据量加载通过缓存机制减少数据库访问账号选择策略采用轮询方式确保负载均衡定时任务用于处理订单支付状态检测和账号日重置避免实时处理带来的性能压力
## 故障排除指南
当遇到API调用失败时首先检查请求参数是否符合验证规则对于未实现的接口如CheckAccount需要查看控制器实现状态数据库相关问题可通过检查DAO层代码和数据库表结构来定位系统提供了详细的错误码机制便于快速定位问题根源
**Section sources**
- [camel_oil_v1_check_account.go](file://internal/controller/camel_oil/camel_oil_v1_check_account.go)
- [camel_oil_v1_account_history.go](file://internal/controller/camel_oil/camel_oil_v1_account_history.go)
## 结论
骆驼加油API模块提供了完整的JD V2平台账号和订单管理功能采用分层架构设计确保代码的可维护性通过接口定义和依赖注入实现组件解耦支持系统的灵活扩展建议完善未实现的接口功能并加强错误处理和日志记录进一步提升系统的稳定性和可观察性

View File

@@ -0,0 +1,320 @@
# 骆驼加油定时任务
<cite>
**本文档引用的文件**
- [main.go](file://main.go)
- [cron.go](file://utility/cron/cron.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
- [cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go)
- [camel_oil.go](file://internal/consts/camel_oil.go)
- [camel_oil_tables.sql](file://sql/camel_oil_tables.sql)
</cite>
## 目录
1. [项目结构](#项目结构)
2. [核心组件](#核心组件)
3. [骆驼加油模块定时任务](#骆驼加油模块定时任务)
4. [定时任务注册机制](#定时任务注册机制)
5. [数据库设计](#数据库设计)
6. [状态管理与枚举](#状态管理与枚举)
7. [业务逻辑分析](#业务逻辑分析)
## 项目结构
```mermaid
graph TD
A[kami_backend] --> B[api]
A --> C[internal]
A --> D[utility]
A --> E[sql]
B --> B1[camel_oil]
B1 --> B11[v1]
B11 --> B111[account.go]
B11 --> B112[order.go]
C --> C1[controller]
C1 --> C11[camel_oil]
C11 --> C111[camel_oil_v1_submit_order.go]
C11 --> C112[camel_oil_v1_order_callback.go]
C --> C2[logic]
C2 --> C21[camel_oil]
C21 --> C211[cron_tasks.go]
C21 --> C212[account_login.go]
C21 --> C213[order.go]
C --> C3[service]
C3 --> C31[camel_oil.go]
C --> C4[consts]
C4 --> C41[camel_oil.go]
C --> C5[dao]
C5 --> C51[v_1_camel_oil_account.go]
C5 --> C52[v_1_camel_oil_order.go]
D --> D1[cron]
D1 --> D11[cron.go]
E --> E1[camel_oil_tables.sql]
```
**Diagram sources**
- [main.go](file://main.go#L1-L56)
- [utility/cron/cron.go](file://utility/cron/cron.go#L1-L96)
**Section sources**
- [main.go](file://main.go#L1-L56)
- [utility/cron/cron.go](file://utility/cron/cron.go#L1-L96)
## 核心组件
骆驼加油模块的核心组件包括定时任务调度器服务接口业务逻辑处理和数据库访问层这些组件协同工作实现了账号管理订单处理和状态监控等功能
**Section sources**
- [internal/service/camel_oil.go](file://internal/service/camel_oil.go#L1-L102)
- [internal/logic/camel_oil/cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L1-L242)
## 骆驼加油模块定时任务
```mermaid
graph TD
A[定时任务调度] --> B[账号登录任务]
A --> C[验证码检测任务]
A --> D[订单支付状态检测任务]
A --> E[账号日重置任务]
B --> B1[每5分钟执行]
B1 --> B2[检查可用订单容量]
B2 --> B3[容量≤50时触发登录]
C --> C1[每5秒执行]
C1 --> C2[查询待验证码账号]
C2 --> C3[从野猪平台检测验证码]
C3 --> C4[调用骆驼加油平台登录]
D --> D1[每10秒执行]
D1 --> D2[查询待支付订单]
D2 --> D3[检测支付状态]
D3 --> D4[更新订单状态]
E --> E1[每日00:00执行]
E1 --> E2[重置在线账号日订单数]
E2 --> E3[处理暂停账号]
E3 --> E4[恢复或标记失效]
```
**Diagram sources**
- [utility/cron/cron.go](file://utility/cron/cron.go#L74-L95)
- [internal/logic/camel_oil/cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L19-L241)
**Section sources**
- [utility/cron/cron.go](file://utility/cron/cron.go#L74-L95)
- [internal/logic/camel_oil/cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L19-L241)
## 定时任务注册机制
```mermaid
sequenceDiagram
participant Main as main.go
participant Cron as cron.go
participant Service as camel_oil.go
participant Logic as cron_tasks.go
Main->>Cron : main()启动
Cron->>Cron : Register(ctx)
Cron->>Cron : registerCamelOilTasks(ctx)
Cron->>Service : 调用CronAccountLoginTask()
Service->>Logic : 执行具体逻辑
Logic->>Logic : 检查容量并触发登录
Cron->>Service : 调用CronVerifyCodeCheckTask()
Service->>Logic : 执行验证码检测
Cron->>Service : 调用CronOrderPaymentCheckTask()
Service->>Logic : 检测订单支付状态
Cron->>Service : 调用CronAccountDailyResetTask()
Service->>Logic : 执行日重置任务
```
**Diagram sources**
- [main.go](file://main.go#L24-L54)
- [utility/cron/cron.go](file://utility/cron/cron.go#L14-L95)
- [internal/service/camel_oil.go](file://internal/service/camel_oil.go#L63-L68)
- [internal/logic/camel_oil/cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L19-L241)
**Section sources**
- [main.go](file://main.go#L24-L54)
- [utility/cron/cron.go](file://utility/cron/cron.go#L14-L95)
## 数据库设计
```mermaid
erDiagram
camel_oil_account {
bigint id PK
varchar(128) account_name
varchar(20) phone UK
text token
tinyint status
datetime token_expire_at
datetime last_login_at
datetime last_used_at
int daily_order_count
date daily_order_date
int total_order_count
text failure_reason
text remark
datetime created_at
datetime updated_at
datetime deleted_at
}
camel_oil_order {
bigint id PK
varchar(64) order_no UK
varchar(128) merchant_order_id
bigint account_id FK
varchar(128) account_name
varchar(128) platform_order_no
decimal(10,2) amount
text alipay_url
tinyint status
tinyint pay_status
tinyint notify_status
int notify_count
datetime last_check_at
datetime paid_at
text attach
text failure_reason
datetime created_at
datetime updated_at
datetime deleted_at
}
camel_oil_account_history {
bigint id PK
varchar(36) history_uuid UK
bigint account_id FK
varchar(32) change_type
tinyint status_before
tinyint status_after
int failure_count
text remark
datetime created_at
datetime updated_at
datetime deleted_at
}
camel_oil_order_history {
bigint id PK
varchar(36) history_uuid UK
varchar(64) order_no FK
varchar(32) change_type
bigint account_id FK
varchar(128) account_name
text raw_data
text remark
datetime created_at
datetime updated_at
datetime deleted_at
}
camel_oil_account ||--o{ camel_oil_order : "1:N"
camel_oil_account ||--o{ camel_oil_account_history : "1:N"
camel_oil_order ||--o{ camel_oil_order_history : "1:N"
```
**Diagram sources**
- [sql/camel_oil_tables.sql](file://sql/camel_oil_tables.sql#L1-L119)
- [internal/consts/camel_oil.go](file://internal/consts/camel_oil.go#L7-L229)
**Section sources**
- [sql/camel_oil_tables.sql](file://sql/camel_oil_tables.sql#L1-L119)
## 状态管理与枚举
```mermaid
classDiagram
class CamelOilAccountStatus {
+Pending : 0
+SendCode : 1
+Online : 2
+Paused : 3
+Invalid : 4
}
class CamelOilOrderStatus {
+Pending : 0
+Processing : 1
+Completed : 2
+Failed : 3
}
class CamelOilPayStatus {
+Unpaid : 0
+Paid : 1
+Refunded : 2
+Timeout : 3
}
class CamelOilNotifyStatus {
+Pending : 0
+Success : 1
+Failed : 2
}
class CamelOilAccountChangeType {
+Create
+Login
+Offline
+LoginFail
+Pause
+Resume
+Invalidate
+OrderBind
+OrderComplete
+Update
+Delete
}
class CamelOilOrderChangeType {
+Create
+Submit
+GetPayUrl
+CheckPay
+Paid
+Timeout
+Fail
+CallbackSuccess
+CallbackFail
}
```
**Diagram sources**
- [internal/consts/camel_oil.go](file://internal/consts/camel_oil.go#L7-L183)
**Section sources**
- [internal/consts/camel_oil.go](file://internal/consts/camel_oil.go#L7-L183)
## 业务逻辑分析
```mermaid
flowchart TD
A[开始] --> B{检查可用订单容量}
B --> |≤50| C[触发账号登录任务]
B --> |>50| D[无需登录]
C --> E[从野猪平台获取手机号]
E --> F[创建账号记录]
F --> G[调用骆驼加油平台发送验证码]
G --> H{发送成功?}
H --> |是| I[更新状态为发送验证码]
H --> |否| J[标记账号失效]
I --> K[验证码检测任务]
K --> L{收到验证码?}
L --> |是| M[调用骆驼加油平台登录]
L --> |否| N[继续等待]
M --> O{登录成功?}
O --> |是| P[保存Token更新状态为在线]
O --> |否| Q[标记账号登录失败]
P --> R[账号可用于下单]
Q --> S[标记账号失效]
T[订单支付状态检测] --> U[查询待支付订单]
U --> V{存在订单?}
V --> |是| W[检测支付状态]
W --> X{已支付?}
X --> |是| Y[更新订单为已支付]
X --> |否| Z{超1小时?}
Z --> |是| AA[标记支付超时]
Z --> |否| AB[继续等待]
Y --> AC[完成]
AA --> AC
AB --> AC
```
**Diagram sources**
- [internal/logic/camel_oil/cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L19-L241)
- [internal/logic/camel_oil/account_login.go](file://internal/logic/camel_oil/account_login.go#L1-L137)
- [internal/logic/camel_oil/order.go](file://internal/logic/camel_oil/order.go#L1-L165)
**Section sources**
- [internal/logic/camel_oil/cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L19-L241)
- [internal/logic/camel_oil/account_login.go](file://internal/logic/camel_oil/account_login.go#L1-L137)
- [internal/logic/camel_oil/order.go](file://internal/logic/camel_oil/order.go#L1-L165)

View File

@@ -0,0 +1,172 @@
# 骆驼油订单管理
<cite>
**本文档引用文件**
- [main.go](file://main.go)
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [order.go](file://api/camel_oil/v1/order.go)
- [account.go](file://api/camel_oil/v1/account.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
- [camel_oil_v1_list_order.go](file://internal/controller/camel_oil/camel_oil_v1_list_order.go)
- [camel_oil_v1_order_detail.go](file://internal/controller/camel_oil/camel_oil_v1_order_detail.go)
- [camel_oil_v1_order_callback.go](file://internal/controller/camel_oil/camel_oil_v1_order_callback.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
- [camel_oil.go](file://internal/consts/camel_oil.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概览](#架构概览)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本系统为骆驼油平台的订单管理服务提供账号管理订单提交状态查询回调处理等核心功能系统基于GoFrame框架构建采用分层架构设计支持高并发订单处理与自动化任务调度
## 项目结构
骆驼油订单管理模块位于`api/camel_oil`目录下包含v1版本API定义控制器位于`internal/controller/camel_oil`服务接口定义在`internal/service/camel_oil.go`相关常量定义于`internal/consts/camel_oil.go`系统通过API层控制器层服务层三层架构实现功能解耦
```mermaid
graph TD
A[API层] --> B[控制器层]
B --> C[服务层]
C --> D[数据访问层]
A --> |HTTP请求| B
B --> |调用| C
C --> |操作| D
```
**图示来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil.go](file://internal/controller/camel_oil/camel_oil.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
**章节来源**
- [main.go](file://main.go#L24-L54)
## 核心组件
系统核心组件包括订单管理账号管理支付回调状态查询等功能通过`ICamelOil`接口定义了完整的业务能力包括订单提交列表查询详情获取回调触发等操作服务层实现具体业务逻辑控制器层负责请求转发
**章节来源**
- [camel_oil.go](file://internal/service/camel_oil.go#L15-L85)
- [order.go](file://api/camel_oil/v1/order.go#L11-L164)
## 架构概览
系统采用典型的分层架构模式从上至下分为API接口层控制器层服务层和数据访问层API层定义RESTful接口规范控制器层处理HTTP请求并调用服务层服务层封装核心业务逻辑数据层负责持久化操作
```mermaid
graph TB
subgraph "API层"
A[SubmitOrder]
B[ListOrder]
C[OrderDetail]
D[OrderCallback]
end
subgraph "控制器层"
E[camel_oil_v1_submit_order]
F[camel_oil_v1_list_order]
G[camel_oil_v1_order_detail]
H[camel_oil_v1_order_callback]
end
subgraph "服务层"
I[SubmitOrder]
J[ListOrder]
K[OrderDetail]
L[TriggerOrderCallback]
end
A --> E
B --> F
C --> G
D --> H
E --> I
F --> J
G --> K
H --> L
```
**图示来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
- [camel_oil_v1_list_order.go](file://internal/controller/camel_oil/camel_oil_v1_list_order.go)
- [camel_oil_v1_order_detail.go](file://internal/controller/camel_oil/camel_oil_v1_order_detail.go)
- [camel_oil_v1_order_callback.go](file://internal/controller/camel_oil/camel_oil_v1_order_callback.go)
## 详细组件分析
### 订单管理组件分析
订单管理组件提供完整的订单生命周期管理功能包括创建查询状态更新和回调处理系统通过`SubmitOrderReq`结构体定义订单提交参数包含金额商户订单号等必要字段
#### 订单提交流程
```mermaid
sequenceDiagram
participant 客户端
participant API
participant 控制器
participant 服务层
客户端->>API : POST /jd-v2/order/submit
API->>控制器 : 转发请求
控制器->>服务层 : 调用SubmitOrder
服务层-->>控制器 : 返回订单信息
控制器-->>API : 返回响应
API-->>客户端 : 返回订单号和支付链接
```
**图示来源**
- [order.go](file://api/camel_oil/v1/order.go#L11-L24)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
#### 订单查询功能
系统提供多种订单查询接口支持按订单号商户订单号账号ID状态等条件进行筛选`ListOrderReq`结构体定义了分页查询参数和过滤条件
**章节来源**
- [order.go](file://api/camel_oil/v1/order.go#L26-L61)
- [camel_oil_v1_list_order.go](file://internal/controller/camel_oil/camel_oil_v1_list_order.go)
### 账号管理组件分析
账号管理组件负责维护骆驼油平台账号的状态和使用情况包括账号创建状态更新历史记录等功能
#### 账号状态管理
系统定义了完整的账号状态机通过`CamelOilAccountStatus`常量管理账号生命周期每个状态变更都会记录到历史表中便于追踪和审计
**章节来源**
- [account.go](file://api/camel_oil/v1/account.go#L11-L40)
- [camel_oil.go](file://internal/consts/camel_oil.go)
## 依赖分析
系统主要依赖GoFrame框架提供的基础能力包括路由数据库访问日志记录等通过`main.go`中的import语句引入必要模块服务注册机制确保各组件正确初始化
```mermaid
graph LR
A[骆驼油服务] --> B[GoFrame框架]
A --> C[MySQL数据库]
A --> D[Redis缓存]
A --> E[OpenTelemetry]
B --> F[路由系统]
B --> G[日志系统]
B --> H[配置管理]
```
**图示来源**
- [main.go](file://main.go#L3-L17)
- [go.mod](file://go.mod)
**章节来源**
- [main.go](file://main.go#L1-L56)
## 性能考虑
系统设计考虑了高并发场景下的性能表现通过连接池缓存机制异步处理等方式提升响应速度定时任务如`CronOrderPaymentCheckTask`定期检查订单支付状态避免实时查询带来的性能压力
## 故障排除指南
常见问题包括订单提交失败支付状态不更新账号登录异常等建议检查服务日志数据库连接状态第三方接口可用性通过`OrderHistory`接口可查询订单变更历史辅助问题定位
**章节来源**
- [order.go](file://api/camel_oil/v1/order.go#L102-L123)
- [camel_oil.go](file://internal/service/camel_oil.go#L75-L78)
## 结论
骆驼油订单管理系统提供了完整的订单处理能力架构清晰功能完备通过分层设计实现了良好的可维护性和扩展性适合处理大规模订单业务场景

View File

@@ -0,0 +1,216 @@
# 骆驼加油账号管理
<cite>
**本文档引用的文件**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [account.go](file://api/camel_oil/v1/account.go)
- [order.go](file://api/camel_oil/v1/order.go)
- [camel_oil_new.go](file://internal/controller/camel_oil/camel_oil_new.go)
- [camel_oil_v1_list_account.go](file://internal/controller/camel_oil/camel_oil_v1_list_account.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
- [camel_oil_v1_list_order.go](file://internal/controller/camel_oil/camel_oil_v1_list_order.go)
- [camel_oil_v1_order_detail.go](file://internal/controller/camel_oil/camel_oil_v1_order_detail.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
- [camel_oil.go](file://internal/consts/camel_oil.go)
- [camel_oil_tables.sql](file://sql/camel_oil_tables.sql)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本系统为骆驼加油平台的账号与订单管理模块提供完整的账号生命周期管理订单处理及状态追踪功能系统通过API接口实现账号查询状态检测订单提交与查询等核心业务功能支持高并发下的稳定运行
## 项目结构
骆驼加油模块采用分层架构设计包含API定义控制器服务层和数据访问层主要目录结构如下
- `api/camel_oil/`API接口定义
- `internal/controller/camel_oil/`控制器层
- `internal/service/camel_oil.go`服务层主入口
- `internal/consts/camel_oil.go`常量定义
- `sql/camel_oil_tables.sql`数据库表结构
```mermaid
graph TD
A[API接口] --> B[Controller]
B --> C[Service]
C --> D[DAO]
D --> E[(数据库)]
```
**图示来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_new.go](file://internal/controller/camel_oil/camel_oil_new.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
**本节来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_new.go](file://internal/controller/camel_oil/camel_oil_new.go)
## 核心组件
系统核心功能包括账号管理订单处理两大模块账号管理支持状态查询历史记录查看订单处理支持提交查询回调等功能所有接口均通过统一的服务入口进行调度
**本节来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil.go](file://internal/consts/camel_oil.go)
## 架构概述
系统采用GoFrame框架构建遵循MVC设计模式前端请求通过API路由进入Controller层由Controller调用Service层处理业务逻辑最终通过DAO层操作数据库Redis用于分布式锁控制并发访问
```mermaid
graph LR
Client[客户端] --> API[API接口]
API --> Controller[控制器]
Controller --> Service[服务层]
Service --> DAO[数据访问层]
DAO --> DB[(MySQL)]
Service --> Cache[(Redis)]
```
**图示来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_new.go](file://internal/controller/camel_oil/camel_oil_new.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
## 详细组件分析
### 账号管理分析
账号管理模块提供账号列表查询状态检测历史记录等功能系统通过状态机管理账号生命周期支持待登录在线暂停失效等多种状态
```mermaid
classDiagram
class AccountListItem {
+int64 AccountId
+string AccountName
+string Phone
+int Status
+string StatusText
+int DailyOrderCount
+string DailyOrderDate
+int TotalOrderCount
+*gtime.Time LastUsedAt
+*gtime.Time LastLoginAt
+*gtime.Time TokenExpireAt
+int RemainingOrders
+string FailureReason
+string Remark
+*gtime.Time CreatedAt
+*gtime.Time UpdatedAt
}
class ListAccountReq {
+CommonPageReq Meta
+int Page
+int Limit
+int Status
+string Keyword
}
class CheckAccountReq {
+CommonMeta Meta
+int64 AccountId
}
ListAccountReq --> AccountListItem : "返回列表"
CheckAccountReq --> AccountListItem : "返回详情"
```
**图示来源**
- [account.go](file://api/camel_oil/v1/account.go)
**本节来源**
- [account.go](file://api/camel_oil/v1/account.go)
- [camel_oil_v1_list_account.go](file://internal/controller/camel_oil/camel_oil_v1_list_account.go)
### 订单处理分析
订单处理模块负责订单的创建查询状态更新和回调通知系统通过分布式锁保证订单处理的原子性防止重复提交
```mermaid
sequenceDiagram
participant Client
participant Controller
participant Service
participant DB
Client->>Controller : SubmitOrder(金额, 商户订单号)
Controller->>Service : 调用SubmitOrder
Service->>DB : 检查可用账号
DB-->>Service : 返回账号信息
Service->>Service : 分配账号并创建订单
Service-->>Controller : 返回订单号和支付链接
Controller-->>Client : 返回响应
Note over Client,DB : 订单提交流程
```
**图示来源**
- [order.go](file://api/camel_oil/v1/order.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
**本节来源**
- [order.go](file://api/camel_oil/v1/order.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
### 状态管理分析
系统定义了完整的状态转换机制涵盖账号状态订单状态支付状态等多个维度状态变更均记录到历史表中便于追踪和审计
```mermaid
stateDiagram-v2
[*] --> 待登录
待登录 --> 登录中 : 开始登录
登录中 --> 在线 : 登录成功
登录中 --> 已失效 : 登录失败
在线 --> 已暂停 : 达到每日上限
已暂停 --> 在线 : 每日重置
在线 --> 已失效 : 长时间未使用
已失效 --> [*]
```
**图示来源**
- [camel_oil.go](file://internal/consts/camel_oil.go)
**本节来源**
- [camel_oil.go](file://internal/consts/camel_oil.go)
## 依赖分析
系统依赖于多个外部组件和内部模块主要依赖关系如下
```mermaid
graph TD
A[骆驼加油API] --> B[用户中心]
A --> C[支付系统]
A --> D[通知服务]
A --> E[Redis缓存]
A --> F[MySQL数据库]
B --> G[认证服务]
C --> H[支付宝网关]
style A fill:#f9f,stroke:#333
style F fill:#bbf,stroke:#333
```
**图示来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
**本节来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil.go](file://internal/service/camel_oil.go)
## 性能考虑
系统在设计时充分考虑了性能因素通过Redis分布式锁控制并发避免热点账号的竞争使用数据库索引优化查询性能设置合理的超时机制防止资源占用
**本节来源**
- [camel_oil.go](file://internal/consts/camel_oil.go)
- [camel_oil_tables.sql](file://sql/camel_oil_tables.sql)
## 故障排除指南
常见问题包括账号无法登录订单提交失败等排查时应首先检查日志中的错误码根据错误码定位问题根源对于分布式锁相关问题需检查Redis连接状态
**本节来源**
- [camel_oil.go](file://internal/consts/camel_oil.go)
- [camel_oil_v1_check_account.go](file://internal/controller/camel_oil/camel_oil_v1_check_account.go)
## 结论
骆驼加油账号管理系统实现了完整的账号与订单管理功能具备良好的扩展性和稳定性通过合理的设计和优化能够满足高并发场景下的业务需求

View File

@@ -0,0 +1,211 @@
# Pig Integration
<cite>
**本文档中引用的文件**
- [api.go](file://utility/integration/pig/api.go)
- [api_test.go](file://utility/integration/pig/api_test.go)
- [account_login.go](file://internal/logic/camel_oil/account_login.go)
- [cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go)
- [cache.go](file://utility/cache/cache.go)
- [camel_oil_api.go](file://utility/integration/camel_oil_api/api.go)
</cite>
## 目录
1. [介绍](#介绍)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 介绍
Pig Integration 文档详细介绍了在 kami_backend 项目中集成 Pig 接码平台的实现该集成主要用于骆驼加油业务场景中的手机号获取和验证码检测系统通过与 Pig 平台的 API 交互自动化完成账号注册验证码接收和登录流程从而支持批量账号管理和订单处理
## 项目结构
该项目是一个基于 Go 语言的后端服务采用模块化设计主要分为 API 接口层业务逻辑层数据访问层和集成服务层Pig 集成位于 `utility/integration/pig` 目录下作为独立的集成模块被业务逻辑层调用
```mermaid
graph TD
subgraph "API Layer"
API[api/]
end
subgraph "Business Logic Layer"
Logic[internal/logic/]
end
subgraph "Integration Layer"
Integration[utility/integration/]
Pig[pig/]
CamelOilApi[camel_oil_api/]
KamiGateway[kami_gateway/]
end
subgraph "Data Access Layer"
DAO[internal/dao/]
end
API --> Logic
Logic --> Integration
Integration --> Pig
Integration --> CamelOilApi
Logic --> DAO
```
**Diagram sources**
- [project_structure](file://project_structure)
**Section sources**
- [project_structure](file://project_structure)
## 核心组件
Pig 集成的核心组件包括 `InternalClient` 结构体及其方法 `NewClient``getToken``GetAccountInfo` `CheckVerifyCode`这些组件共同实现了与 Pig 平台的认证账号信息获取和验证码检测功能
**Section sources**
- [api.go](file://utility/integration/pig/api.go#L1-L116)
## 架构概述
Pig 集成的架构设计遵循了客户端-服务器模式其中 `InternalClient` 作为客户端与 Pig 平台的服务器进行 HTTP 通信该集成通过缓存机制优化了 token 的获取避免了频繁的认证请求提高了系统的整体性能
```mermaid
sequenceDiagram
participant Logic as 骆驼油业务逻辑
participant PigClient as Pig客户端
participant PigServer as Pig服务器
Logic->>PigClient : GetAccountInfo()
PigClient->>PigClient : getToken()
PigClient->>PigClient : 检查缓存中的token
alt 缓存命中
PigClient-->>PigClient : 返回缓存的token
else 缓存未命中
PigClient->>PigServer : POST /sms/?api=login
PigServer-->>PigClient : 返回token
PigClient->>PigClient : 缓存token
end
PigClient->>PigServer : POST /sms?api=getPhone
PigServer-->>PigClient : 返回手机号
PigClient-->>Logic : 返回手机号
```
**Diagram sources**
- [api.go](file://utility/integration/pig/api.go#L1-L116)
## 详细组件分析
### Pig 客户端分析
Pig 客户端实现了与 Pig 接码平台的完整交互流程包括认证账号信息获取和验证码检测
#### Pig 客户端结构
```mermaid
classDiagram
class InternalClient {
+Client *gclient.Client
+NewClient() *InternalClient
+getToken(ctx context.Context) (string, error)
+GetAccountInfo(ctx context.Context) (string, error)
+CheckVerifyCode(ctx context.Context, phone string) (code string, received bool, err error)
}
InternalClient --> gclient.Client : "使用"
```
**Diagram sources**
- [api.go](file://utility/integration/pig/api.go#L1-L116)
#### 账号登录流程
```mermaid
flowchart TD
Start([开始登录]) --> GetPhone["获取手机号 (GetAccountInfo)"]
GetPhone --> SendCaptcha["发送验证码"]
SendCaptcha --> WaitCaptcha["等待验证码"]
WaitCaptcha --> CheckCode["检测验证码 (CheckVerifyCode)"]
CheckCode --> CodeReceived{"验证码已接收?"}
CodeReceived --> |否| WaitCaptcha
CodeReceived --> |是| Login["执行登录"]
Login --> End([登录完成])
```
**Diagram sources**
- [account_login.go](file://internal/logic/camel_oil/account_login.go#L1-L137)
- [cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L1-L242)
**Section sources**
- [api.go](file://utility/integration/pig/api.go#L1-L116)
- [account_login.go](file://internal/logic/camel_oil/account_login.go#L1-L137)
### 验证码检测任务分析
验证码检测任务是骆驼加油业务中的关键定时任务负责定期检查待验证账号的验证码接收情况并完成登录流程
#### 验证码检测任务流程
```mermaid
flowchart TD
Start([开始任务]) --> QueryAccounts["查询待验证码账号"]
QueryAccounts --> Loop{"遍历账号"}
Loop --> GetPhone["获取账号手机号"]
GetPhone --> CheckCode["检测验证码 (CheckVerifyCode)"]
CheckCode --> CodeReceived{"验证码已接收?"}
CodeReceived --> |否| ContinueLoop["继续下一个账号"]
CodeReceived --> |是| ExecuteLogin["执行登录"]
ExecuteLogin --> UpdateStatus["更新账号状态为在线"]
UpdateStatus --> LogSuccess["记录成功日志"]
ContinueLoop --> Loop
Loop --> EndLoop{"遍历完成?"}
EndLoop --> |是| End([任务完成])
```
**Diagram sources**
- [cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L169-L241)
**Section sources**
- [cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L169-L241)
## 依赖分析
Pig 集成依赖于多个内部和外部组件形成了一个复杂的依赖网络
```mermaid
graph TD
PigClient[utility/integration/pig@InternalClient] --> GClient[github.com/gogf/gf/v2/net/gclient]
PigClient --> Cache[utility/cache]
PigClient --> GLog[github.com/gogf/gf/v2/os/glog]
PigClient --> GTime[github.com/gogf/gf/v2/os/gtime]
CamelOilLogic[internal/logic/camel_oil@sCamelOil] --> PigClient
CamelOilLogic --> CamelOilApi[utility/integration/camel_oil_api]
CamelOilLogic --> DAO[internal/dao]
CamelOilLogic --> Config[utility/config]
Cache --> Redis[github.com/gogf/gf/v2/contrib/nosql/redis/v2]
```
**Diagram sources**
- [api.go](file://utility/integration/pig/api.go#L1-L116)
- [account_login.go](file://internal/logic/camel_oil/account_login.go#L1-L137)
- [cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L1-L242)
**Section sources**
- [api.go](file://utility/integration/pig/api.go#L1-L116)
- [account_login.go](file://internal/logic/camel_oil/account_login.go#L1-L137)
- [cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L1-L242)
## 性能考虑
Pig 集成在设计时充分考虑了性能优化主要体现在以下几个方面
1. **Token 缓存**通过 Redis 缓存 Pig 平台的认证 token有效期为 24 小时避免了频繁的认证请求
2. **单例模式**`InternalClient` 使用 sync.OnceFunc 确保全局唯一实例减少了资源消耗
3. **HTTP 客户端复用**使用 g.Client() 创建的客户端实例被复用避免了频繁创建和销毁 HTTP 客户端的开销
**Section sources**
- [api.go](file://utility/integration/pig/api.go#L1-L116)
- [cache.go](file://utility/cache/cache.go#L1-L220)
## 故障排除指南
在使用 Pig 集成时可能遇到以下常见问题及解决方案
1. **获取 token 失败**检查 Pig 平台的用户名和密码是否正确确保网络连接正常
2. **获取手机号失败**确认 Pig 平台是否有可用的手机号资源检查 API 接口是否正常
3. **验证码检测超时**增加检测间隔时间或检查 Pig 平台的短信发送是否正常
4. **登录失败**检查骆驼加油平台的登录接口是否正常确认验证码是否正确
**Section sources**
- [api.go](file://utility/integration/pig/api.go#L1-L116)
- [account_login.go](file://internal/logic/camel_oil/account_login.go#L1-L137)
- [cron_tasks.go](file://internal/logic/camel_oil/cron_tasks.go#L1-L242)
## 结论
Pig Integration kami_backend 项目中扮演着关键角色为骆驼加油业务提供了稳定的手机号获取和验证码检测能力该集成设计合理性能优化到位通过与骆驼加油平台和内部业务逻辑的紧密配合实现了自动化账号管理和订单处理流程未来可以考虑增加更多的错误处理和重试机制进一步提高系统的稳定性和可靠性

View File

@@ -0,0 +1,346 @@
# 骆驼加油数据库模式
<cite>
**本文档中引用的文件**
- [camel_oil_tables.sql](file://sql/camel_oil_tables.sql)
- [v_1_camel_oil_account.go](file://internal/model/entity/v_1_camel_oil_account.go)
- [v_1_camel_oil_order.go](file://internal/model/entity/v_1_camel_oil_order.go)
- [v_1_camel_oil_account_history.go](file://internal/model/entity/v_1_camel_oil_account_history.go)
- [v_1_camel_oil_order_history.go](file://internal/model/entity/v_1_camel_oil_order_history.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
- [camel_oil_v1_order_callback.go](file://internal/controller/camel_oil/camel_oil_v1_order_callback.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
## 简介
本文档详细描述了骆驼加油平台的数据库模式包括账号管理订单处理和历史记录等核心功能该系统主要用于管理骆驼加油平台的账号登录状态订单生命周期以及相关的历史变更记录
## 项目结构
骆驼加油模块的代码结构遵循分层设计原则主要包含API接口控制器数据访问对象DAO和实体模型等组件数据库表结构定义在SQL文件中而对应的Go语言模型则分布在model目录下
```mermaid
graph TB
subgraph "API层"
API[api/camel_oil/v1]
end
subgraph "控制器层"
Controller[internal/controller/camel_oil]
end
subgraph "服务层"
Service[internal/service/camel_oil.go]
end
subgraph "逻辑层"
Logic[internal/logic/camel_oil]
end
subgraph "数据访问层"
DAO[internal/dao]
end
subgraph "模型层"
Model[internal/model/entity]
end
subgraph "数据库"
DB[sql/camel_oil_tables.sql]
end
API --> Controller
Controller --> Service
Service --> Logic
Logic --> DAO
DAO --> Model
Model --> DB
```
**图示来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
- [service.go](file://internal/service/camel_oil.go)
- [v_1_camel_oil_account.go](file://internal/model/entity/v_1_camel_oil_account.go)
- [camel_oil_tables.sql](file://sql/camel_oil_tables.sql)
**节来源**
- [camel_oil.go](file://api/camel_oil/camel_oil.go)
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
## 核心组件
骆驼加油系统的核心组件包括四个主要数据库表账号表订单表账号历史表和订单历史表这些表共同构成了系统的数据基础支持账号管理订单处理和操作审计等功能
**节来源**
- [camel_oil_tables.sql](file://sql/camel_oil_tables.sql)
- [v_1_camel_oil_account.go](file://internal/model/entity/v_1_camel_oil_account.go)
- [v_1_camel_oil_order.go](file://internal/model/entity/v_1_camel_oil_order.go)
## 架构概述
骆驼加油系统的数据架构采用标准的分层设计通过实体-关系模型来管理平台的核心业务数据系统通过外键约束确保数据完整性并使用软删除机制保留历史数据
```mermaid
erDiagram
CAMEL_OIL_ACCOUNT {
bigint id PK
varchar(128) account_name
varchar(20) phone UK
text token
tinyint status
datetime token_expire_at
datetime last_login_at
datetime last_used_at
int daily_order_count
date daily_order_date
int total_order_count
text failure_reason
text remark
datetime created_at
datetime updated_at
datetime deleted_at
}
CAMEL_OIL_ORDER {
bigint id PK
varchar(64) order_no UK
varchar(128) merchant_order_id
bigint account_id FK
varchar(128) account_name
varchar(128) platform_order_no
decimal(10,2) amount
text alipay_url
tinyint status
tinyint pay_status
tinyint notify_status
int notify_count
datetime last_check_at
datetime paid_at
text attach
text failure_reason
datetime created_at
datetime updated_at
datetime deleted_at
}
CAMEL_OIL_ACCOUNT_HISTORY {
bigint id PK
varchar(36) history_uuid UK
bigint account_id FK
varchar(32) change_type
tinyint status_before
tinyint status_after
int failure_count
text remark
datetime created_at
datetime updated_at
datetime deleted_at
}
CAMEL_OIL_ORDER_HISTORY {
bigint id PK
varchar(36) history_uuid UK
varchar(64) order_no FK
varchar(32) change_type
bigint account_id FK
varchar(128) account_name
text raw_data
text remark
datetime created_at
datetime updated_at
datetime deleted_at
}
CAMEL_OIL_ACCOUNT ||--o{ CAMEL_OIL_ORDER : "拥有"
CAMEL_OIL_ACCOUNT ||--o{ CAMEL_OIL_ACCOUNT_HISTORY : "产生"
CAMEL_OIL_ORDER ||--o{ CAMEL_OIL_ORDER_HISTORY : "产生"
```
**图示来源**
- [camel_oil_tables.sql](file://sql/camel_oil_tables.sql)
- [v_1_camel_oil_account.go](file://internal/model/entity/v_1_camel_oil_account.go)
- [v_1_camel_oil_order.go](file://internal/model/entity/v_1_camel_oil_order.go)
## 详细组件分析
### 账号管理组件分析
骆驼加油账号管理组件负责维护平台账号的生命周期包括登录状态Token管理和使用统计等功能
#### 账号实体类图
```mermaid
classDiagram
class V1CamelOilAccount {
+int64 id
+string accountName
+string phone
+string token
+int status
+gtime.Time tokenExpireAt
+gtime.Time lastLoginAt
+gtime.Time lastUsedAt
+int dailyOrderCount
+gtime.Time dailyOrderDate
+int totalOrderCount
+string failureReason
+string remark
+gtime.Time createdAt
+gtime.Time updatedAt
+gtime.Time deletedAt
}
class V1CamelOilAccountHistory {
+int64 id
+string historyUuid
+int64 accountId
+string changeType
+int statusBefore
+int statusAfter
+int failureCount
+string remark
+gtime.Time createdAt
+gtime.Time updatedAt
+gtime.Time deletedAt
}
V1CamelOilAccount --> V1CamelOilAccountHistory : "生成"
```
**图示来源**
- [v_1_camel_oil_account.go](file://internal/model/entity/v_1_camel_oil_account.go)
- [v_1_camel_oil_account_history.go](file://internal/model/entity/v_1_camel_oil_account_history.go)
**节来源**
- [v_1_camel_oil_account.go](file://internal/model/entity/v_1_camel_oil_account.go)
- [v_1_camel_oil_account_history.go](file://internal/model/entity/v_1_camel_oil_account_history.go)
### 订单处理组件分析
订单处理组件负责管理骆驼加油平台的订单生命周期从创建到支付完成或失败的全过程
#### 订单实体类图
```mermaid
classDiagram
class V1CamelOilOrder {
+int64 id
+string orderNo
+string merchantOrderId
+int64 accountId
+string accountName
+string platformOrderNo
+decimal amount
+string alipayUrl
+int status
+int payStatus
+int notifyStatus
+int notifyCount
+gtime.Time lastCheckAt
+gtime.Time paidAt
+string attach
+string failureReason
+gtime.Time createdAt
+gtime.Time updatedAt
+gtime.Time deletedAt
}
class V1CamelOilOrderHistory {
+int64 id
+string historyUuid
+string orderNo
+string changeType
+int64 accountId
+string accountName
+string rawData
+string remark
+gtime.Time createdAt
+gtime.Time updatedAt
+gtime.Time deletedAt
}
V1CamelOilOrder --> V1CamelOilOrderHistory : "生成"
```
**图示来源**
- [v_1_camel_oil_order.go](file://internal/model/entity/v_1_camel_oil_order.go)
- [v_1_camel_oil_order_history.go](file://internal/model/entity/v_1_camel_oil_order_history.go)
**节来源**
- [v_1_camel_oil_order.go](file://internal/model/entity/v_1_camel_oil_order.go)
- [v_1_camel_oil_order_history.go](file://internal/model/entity/v_1_camel_oil_order_history.go)
### API流程分析
骆驼加油系统的API流程展示了订单提交和回调处理的核心业务流程
#### 订单提交流程序列图
```mermaid
sequenceDiagram
participant Client as "客户端"
participant Controller as "ControllerV1"
participant Service as "CamelOil Service"
Client->>Controller : SubmitOrder请求
Controller->>Service : 调用SubmitOrder方法
Service-->>Controller : 返回结果
Controller-->>Client : 返回响应
```
**图示来源**
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
#### 回调处理流程序列图
```mermaid
sequenceDiagram
participant Client as "第三方平台"
participant Controller as "ControllerV1"
Client->>Controller : OrderCallback请求
Controller-->>Client : 返回未实现错误
```
**图示来源**
- [camel_oil_v1_order_callback.go](file://internal/controller/camel_oil/camel_oil_v1_order_callback.go)
**节来源**
- [camel_oil_v1_submit_order.go](file://internal/controller/camel_oil/camel_oil_v1_submit_order.go)
- [camel_oil_v1_order_callback.go](file://internal/controller/camel_oil/camel_oil_v1_order_callback.go)
## 依赖分析
骆驼加油模块与其他系统组件存在明确的依赖关系主要通过服务层进行交互
```mermaid
graph TD
CamelOil[骆驼加油模块] --> GoFrame[GoFrame框架]
CamelOil --> Database[MySQL数据库]
CamelOil --> Utility[工具库]
CamelOil --> Internal[内部其他模块]
subgraph "内部依赖"
Internal --> Service[service模块]
Internal --> Model[model模块]
Internal --> DAO[dao模块]
Internal --> Logic[logic模块]
end
subgraph "外部依赖"
Utility --> Cache[缓存]
Utility --> Notify[通知服务]
Utility --> Monitor[监控服务]
end
```
**图示来源**
- [go.mod](file://go.mod)
- [camel_oil.go](file://internal/service/camel_oil.go)
**节来源**
- [go.mod](file://go.mod)
- [camel_oil.go](file://internal/service/camel_oil.go)
## 性能考虑
骆驼加油系统的数据库设计考虑了性能优化主要体现在以下几个方面
- 在关键字段上创建了适当的索引以提高查询效率
- 使用软删除而非物理删除来保留历史数据
- 对时间敏感的字段建立了复合索引
- 通过外键约束确保数据完整性的同时考虑了查询性能
## 故障排除指南
在使用骆驼加油系统时可能遇到的常见问题及解决方案
1. **账号登录失败**检查账号状态是否为"待登录"确认Token是否过期
2. **订单创建失败**验证商户订单号是否唯一检查账号状态是否正常
3. **回调处理异常**当前回调功能尚未实现需要开发相应的处理逻辑
4. **数据查询缓慢**检查相关字段的索引是否存在优化查询条件
**节来源**
- [camel_oil_tables.sql](file://sql/camel_oil_tables.sql)
- [camel_oil_v1_order_callback.go](file://internal/controller/camel_oil/camel_oil_v1_order_callback.go)
## 结论
骆驼加油系统的数据库模式设计合理通过四个核心表实现了账号管理订单处理和历史记录的完整功能系统采用分层架构代码结构清晰便于维护和扩展建议尽快实现订单回调功能并进一步完善错误处理机制

View File

@@ -0,0 +1,203 @@
# 优雅关闭修复
<cite>
**本文档引用的文件**
- [main.go](file://main.go)
- [cmd.go](file://internal/cmd/cmd.go)
- [pool.go](file://utility/pool/pool.go)
- [cron.go](file://utility/cron/cron.go)
- [config.go](file://utility/config/config.go)
</cite>
## 目录
1. [简介](#简介)
2. [项目结构](#项目结构)
3. [核心组件](#核心组件)
4. [架构概述](#架构概述)
5. [详细组件分析](#详细组件分析)
6. [依赖分析](#依赖分析)
7. [性能考虑](#性能考虑)
8. [故障排除指南](#故障排除指南)
9. [结论](#结论)
10. [附录](#附录)如有必要
## 简介
本文档详细描述了kami_backend项目中优雅关闭功能的实现机制系统在接收到终止信号时能够有序地停止定时任务和关闭线程池确保所有正在进行的任务能够完成避免数据丢失或服务异常中断
## 项目结构
本项目采用GoFrame框架构建的后端服务主要包含API接口内部服务逻辑工具库和配置文件等模块项目结构清晰按功能划分目录便于维护和扩展
```mermaid
graph TB
subgraph "核心模块"
main["main.go<br/>主程序入口"]
cmd["internal/cmd<br/>命令行处理"]
controller["internal/controller<br/>控制器"]
service["internal/service<br/>服务层"]
logic["internal/logic<br/>业务逻辑"]
end
subgraph "工具库"
utility["utility<br/>通用工具"]
pool["utility/pool<br/>线程池管理"]
cron["utility/cron<br/>定时任务"]
config["utility/config<br/>配置管理"]
otel["utility/otel<br/>可观测性"]
end
subgraph "配置与资源"
manifest["manifest<br/>部署配置"]
resource["resource<br/>资源文件"]
sql["sql<br/>数据库脚本"]
end
main --> cmd
cmd --> controller
controller --> service
service --> logic
utility --> cmd
config --> utility
cron --> cmd
pool --> cmd
```
**Diagram sources**
- [main.go](file://main.go#L1-L56)
- [cmd.go](file://internal/cmd/cmd.go#L1-L97)
- [pool.go](file://utility/pool/pool.go#L1-L64)
- [cron.go](file://utility/cron/cron.go#L1-L96)
- [config.go](file://utility/config/config.go#L1-L112)
**Section sources**
- [main.go](file://main.go#L1-L56)
- [internal/cmd/cmd.go](file://internal/cmd/cmd.go#L1-L97)
## 核心组件
系统的核心组件包括主程序入口命令行处理器定时任务管理器和线程池管理器这些组件协同工作确保服务能够正常启动运行和优雅关闭
**Section sources**
- [main.go](file://main.go#L24-L55)
- [internal/cmd/cmd.go](file://internal/cmd/cmd.go#L42-L85)
## 架构概述
系统采用分层架构设计从上到下依次为API层控制器层服务层和数据访问层同时系统集成了定时任务和线程池等辅助组件以支持后台任务处理和并发操作
```mermaid
graph TD
A[客户端] --> B[API接口]
B --> C[控制器层]
C --> D[服务层]
D --> E[业务逻辑层]
E --> F[数据访问层]
F --> G[(数据库)]
H[定时任务] --> D
I[线程池] --> E
J[配置管理] --> 所有层级
K[可观测性] --> 所有层级
```
**Diagram sources**
- [internal/cmd/cmd.go](file://internal/cmd/cmd.go#L47-L76)
- [utility/cron/cron.go](file://utility/cron/cron.go#L13-L71)
- [utility/pool/pool.go](file://utility/pool/pool.go#L30-L33)
## 详细组件分析
### 优雅关闭机制分析
系统实现了完整的优雅关闭流程确保在服务终止时能够有序地清理资源和完成正在进行的任务
#### 优雅关闭流程
```mermaid
sequenceDiagram
participant 系统 as 系统
participant 信号监听 as 信号监听
participant 定时任务 as 定时任务
participant 线程池 as 线程池
系统->>信号监听 : 启动信号监听
信号监听->>系统 : 等待SIGINT/SIGTERM
系统->>系统 : 运行主服务
用户->>系统 : 发送终止信号
信号监听->>系统 : 接收终止信号
系统->>定时任务 : 停止所有定时任务
定时任务-->>系统 : 确认所有任务完成
系统->>线程池 : 关闭所有线程池
线程池-->>系统 : 确认线程池已关闭
系统->>系统 : 服务完全停止
```
**Diagram sources**
- [internal/cmd/cmd.go](file://internal/cmd/cmd.go#L87-L96)
- [utility/cron/cron.go](file://utility/cron/cron.go#L13-L71)
- [utility/pool/pool.go](file://utility/pool/pool.go#L56-L63)
#### 线程池管理
```mermaid
classDiagram
class PoolManager {
+Pools map[Key]*grpool.Pool
+New(key Key, limit... int) *grpool.Pool
+GracefulDown()
}
class Key {
+AppleCardCallBack
+JDCardCallBack
+RedeemCardConsume
+其他任务类型
}
PoolManager "1" *-- "0..*" grpool.Pool
Key ..> PoolManager : 作为键值
```
**Diagram sources**
- [utility/pool/pool.go](file://utility/pool/pool.go#L30-L63)
**Section sources**
- [internal/cmd/cmd.go](file://internal/cmd/cmd.go#L87-L96)
- [utility/pool/pool.go](file://utility/pool/pool.go#L1-L64)
- [utility/cron/cron.go](file://utility/cron/cron.go#L1-L96)
## 依赖分析
系统各组件之间的依赖关系清晰主要依赖GoFrame框架提供的功能以及OpenTelemetry用于可观测性
```mermaid
graph TD
A[main.go] --> B[cmd.go]
B --> C[gogf/gf框架]
B --> D[pool.go]
B --> E[cron.go]
B --> F[otel]
D --> G[grpool]
E --> H[gcron]
F --> I[OpenTelemetry]
C --> J[数据库驱动]
C --> K[Redis驱动]
```
**Diagram sources**
- [go.mod](file://go.mod#L5-L100)
- [main.go](file://main.go#L3-L16)
- [internal/cmd/cmd.go](file://internal/cmd/cmd.go#L28-L40)
**Section sources**
- [go.mod](file://go.mod#L1-L101)
- [main.go](file://main.go#L3-L16)
- [internal/cmd/cmd.go](file://internal/cmd/cmd.go#L28-L40)
## 性能考虑
系统在设计时考虑了性能和资源管理通过线程池和定时任务的合理配置确保系统在高并发场景下的稳定运行优雅关闭机制避免了 abrupt termination 可能导致的资源泄漏和数据不一致问题
## 故障排除指南
当遇到服务无法正常关闭的问题时可以按照以下步骤进行排查
1. 检查是否有长时间运行的定时任务未完成
2. 确认线程池中的任务是否都能在合理时间内完成
3. 查看日志中是否有任务执行失败的记录
4. 检查系统资源使用情况确保没有资源瓶颈
**Section sources**
- [internal/cmd/cmd.go](file://internal/cmd/cmd.go#L87-L96)
- [utility/pool/pool.go](file://utility/pool/pool.go#L56-L63)
- [utility/cron/cron.go](file://utility/cron/cron.go#L13-L71)
## 结论
kami_backend项目的优雅关闭实现是完整且可靠的通过有序地停止定时任务和关闭线程池系统能够在接收到终止信号时安全地停止服务确保数据一致性和系统稳定性这种设计模式值得在其他微服务中推广使用
## 附录
本文档基于项目当前代码库生成随着项目的演进相关实现可能会有所变化建议定期更新文档以保持与代码的一致性

File diff suppressed because one or more lines are too long

View File

@@ -3,11 +3,6 @@ package card_apple_order
import (
"context"
"fmt"
"github.com/duke-git/lancet/v2/slice"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/os/glog"
"github.com/shopspring/decimal"
"kami/internal/consts"
"kami/internal/errHandler"
"kami/internal/model"
@@ -18,9 +13,17 @@ import (
"kami/utility/integration/apple"
"kami/utility/pool"
"time"
"github.com/duke-git/lancet/v2/slice"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/os/gcron"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/glog"
"github.com/shopspring/decimal"
)
// HandleRedeemResult 处理核销结果,根据不同的状态进行相应的业务操作
// handleRedeemResult 处理核销结果,根据状态码分类进行对应处理
func (h *sAppleOrder) handleRedeemResult(ctx context.Context, orderEntity *entity.V1CardAppleRechargeInfo, accountInfo *entity.V1CardAppleAccountInfo) error {
// 调用 Apple 服务进行核销(同步等待)
redeemClient := apple.NewClient()
@@ -31,12 +34,41 @@ func (h *sAppleOrder) handleRedeemResult(ctx context.Context, orderEntity *entit
OrderId: orderEntity.OrderNo,
RedemptionCode: orderEntity.CardPass,
}
_, _ = redeemClient.Redeem(ctx, redeemReq)
return nil
resp, err := redeemClient.Redeem(ctx, redeemReq)
if err != nil {
return err
}
// 根据状态码分类处理
switch {
// 1. 成功状态CodeSuccess = 0
case resp.Code == apple.CodeSuccess:
return h.handleRedeemSuccess(ctx, orderEntity, accountInfo, resp.Data.Amount, resp.Data.BalanceBefore, resp.Data.BalanceAfter)
// 2. 网络请求或系统资源错误5000-5999
case resp.Code >= 5000 && resp.Code < 6000:
return h.handleSystemError(ctx, orderEntity, accountInfo, resp.Code, resp.Message)
// 3. 苹果账户原因错误8001-8005
case resp.Code >= 8001 && resp.Code <= 8005:
return h.handleAccountError(ctx, orderEntity, accountInfo, resp.Code, resp.Message)
// 4. 充值限制错误8010-8012
case resp.Code >= 8010 && resp.Code <= 8012:
return h.handleRedeemLimitError(ctx, orderEntity, accountInfo, resp.Code, resp.Message)
// 5. 卡密错误8013-8014
case resp.Code >= 8013 && resp.Code <= 8014:
return h.handleCardCodeError(ctx, orderEntity, accountInfo, resp.Code, resp.Message)
// 未知错误
default:
return h.handleRedeemFailed(ctx, orderEntity, accountInfo, resp.Message)
}
}
// handleRedeemSuccess 处理核销成功的情况
func (h *sAppleOrder) handleRedeemSuccess(ctx context.Context, orderEntity *entity.V1CardAppleRechargeInfo, accountInfo *entity.V1CardAppleAccountInfo, balanceBefore, balanceAfter float64) error {
func (h *sAppleOrder) handleRedeemSuccess(ctx context.Context, orderEntity *entity.V1CardAppleRechargeInfo, accountInfo *entity.V1CardAppleAccountInfo, amount, balanceBefore, balanceAfter float64) error {
// 将返回的金额字符串转换为 float64假数据处理
actualAmount := orderEntity.CardAmount // 使用卡密面额作为默认金额
@@ -135,6 +167,178 @@ func (h *sAppleOrder) handleAccountInvalid(ctx context.Context, orderEntity *ent
return nil
}
// handleSystemError 处理系统资源错误5000-5999
// 订单退回待处理,等待系统重新调度重试
func (h *sAppleOrder) handleSystemError(ctx context.Context, orderEntity *entity.V1CardAppleRechargeInfo, accountInfo *entity.V1CardAppleAccountInfo, code apple.Code, message string) error {
// 订单退回待处理状态
err := h.ModifyOrderStatus(ctx, orderEntity.OrderNo, consts.AppleRechargeOrderWaiting, fmt.Sprintf("系统错误:%s", message), nil)
if err != nil {
glog.Error(ctx, fmt.Sprintf("更新订单状态失败 - 订单号: %s, 错误: %v", orderEntity.OrderNo, err))
return err
}
// 减少分配计数
_ = h.DecrementDistributionCount(ctx, orderEntity.OrderNo)
// 添加历史记录
_ = h.AddHistory(ctx, &model.AppleCardRechargeHistoryInput{
AccountID: accountInfo.Id,
OrderNo: orderEntity.OrderNo,
RechargeId: int(orderEntity.Id),
AccountName: accountInfo.Account,
Operation: consts.AppleRechargeOperationItunesFail,
Remark: fmt.Sprintf("系统错误(状态码: %d%s", code, message),
}, nil)
glog.Warning(ctx, fmt.Sprintf("系统错误,订单已退回待处理 - 订单号: %s, 状态码: %d", orderEntity.OrderNo, code))
return nil
}
// handleAccountError 处理苹果账户原因错误8001-8005
// 标记账户失效,订单退回待处理,等待重新分配其他有效账户
func (h *sAppleOrder) handleAccountError(ctx context.Context, orderEntity *entity.V1CardAppleRechargeInfo, accountInfo *entity.V1CardAppleAccountInfo, code apple.Code, message string) error {
// 根据错误码标记不同的账户失效状态
var accountStatus consts.AppleAccountStatus
switch code {
case apple.CodeApplePasswordError, apple.CodeApplePasswordExpired:
accountStatus = consts.AppleAccountWrongPassword // 账号密码错误
case apple.CodeAppleAccountForbidden:
accountStatus = consts.AppleAccountForbidden // 账号被禁用
case apple.CodeAppleAccountLocked:
accountStatus = consts.AppleAccountLimited // 账号被封锁(作为受限处理)
case apple.CodeAppleStatusUnknown:
accountStatus = consts.AppleAccountNormal // 状态未知,保持正常以便后续重试
default:
accountStatus = consts.AppleAccountWrongPassword
}
// 标记账户为失效状态
_ = service.AppleAccount().ModifyStatus(ctx, accountInfo.Id, accountStatus, nil)
// 订单重新设为待调度状态
err := h.ModifyOrderStatus(ctx, orderEntity.OrderNo, consts.AppleRechargeOrderWaiting, "苹果账户原因导致失效,待重新分配", nil)
if err != nil {
glog.Error(ctx, fmt.Sprintf("更新订单状态失败 - 订单号: %s, 错误: %v", orderEntity.OrderNo, err))
return err
}
// 减少分配计数,允许重新分配
_ = h.DecrementDistributionCount(ctx, orderEntity.OrderNo)
// 添加历史记录
_ = h.AddHistory(ctx, &model.AppleCardRechargeHistoryInput{
AccountID: accountInfo.Id,
OrderNo: orderEntity.OrderNo,
RechargeId: int(orderEntity.Id),
AccountName: accountInfo.Account,
Operation: consts.AppleRechargeOperationWrongPassword,
Remark: fmt.Sprintf("苹果账户错误(状态码: %d%s", code, message),
}, nil)
glog.Warning(ctx, fmt.Sprintf("苹果账户原因导致失效,订单已退回待重新分配 - 订单号: %s, 账号: %s, 状态码: %d", orderEntity.OrderNo, accountInfo.Account, code))
return nil
}
// handleRedeemLimitError 处理充值限制错误8010-8012
// 根据限制类型标记账户,订单根据业务规则决定重试或失败
func (h *sAppleOrder) handleRedeemLimitError(ctx context.Context, orderEntity *entity.V1CardAppleRechargeInfo, accountInfo *entity.V1CardAppleAccountInfo, code apple.Code, message string) error {
// 根据限制类型标记账户状态
var accountStatus consts.AppleAccountStatus
var accountRemark string
switch code {
case apple.CodeAppleRedeemLimitExceeded:
// 充值次数限制 - 永久受限
accountStatus = consts.AppleAccountForbiddenByTooManyRecharge
accountRemark = "苹果账户充值次数限制(永久)"
case apple.CodeAppleRedeemLimitExceededTemporarily:
// 临时限制 - 标记为临时冻结,暂停兑换
accountStatus = consts.AppleAccountTmpStoppedByTooManyRequest
_, _ = gcron.AddOnce(gctx.GetInitCtx(), "@every 2m", func(ctx2 context.Context) {
// 获取追踪能力
_ = service.AppleAccount().ModifyStatus(ctx2, orderEntity.AccountId, consts.AppleAccountNormal, nil)
})
accountRemark = "苹果账户临时充值限制2分钟后恢复"
case apple.CodeAppleRedeemLimitExceededPerMinute:
// 一分钟限制 - 标记为临时冻结
_, _ = gcron.AddOnce(gctx.GetInitCtx(), "@every 1m", func(ctx2 context.Context) {
// 获取追踪能力
_ = service.AppleAccount().ModifyStatus(ctx2, orderEntity.AccountId, consts.AppleAccountNormal, nil)
})
accountStatus = consts.AppleAccountTmpLimited
accountRemark = "苹果账户一分钟充值限制1分钟后恢复"
default:
accountStatus = consts.AppleAccountLimited
accountRemark = fmt.Sprintf("苹果账户充值限制(状态码: %d", code)
}
// 标记账户限制状态
_ = service.AppleAccount().ModifyStatus(ctx, accountInfo.Id, accountStatus, nil)
// 订单退回待处理,后续可根据限制类型进行重试或转移到其他账户
err := h.ModifyOrderStatus(ctx, orderEntity.OrderNo, consts.AppleRechargeOrderWaiting, fmt.Sprintf("账户受限:%s", message), nil)
if err != nil {
glog.Error(ctx, fmt.Sprintf("更新订单状态失败 - 订单号: %s, 错误: %v", orderEntity.OrderNo, err))
return err
}
// 减少分配计数
_ = h.DecrementDistributionCount(ctx, orderEntity.OrderNo)
// 添加历史记录
_ = h.AddHistory(ctx, &model.AppleCardRechargeHistoryInput{
AccountID: accountInfo.Id,
OrderNo: orderEntity.OrderNo,
RechargeId: int(orderEntity.Id),
AccountName: accountInfo.Account,
Operation: consts.AppleRechargeOperationItunesFail,
Remark: fmt.Sprintf("%s - %s", accountRemark, message),
}, nil)
glog.Warning(ctx, fmt.Sprintf("账户充值限制,订单已退回待处理 - 订单号: %s, 账号: %s, 限制类型: %d", orderEntity.OrderNo, accountInfo.Account, code))
return nil
}
// handleCardCodeError 处理卡密错误8013-8014
// 直接按订单失败处理,更新订单状态为失败
func (h *sAppleOrder) handleCardCodeError(ctx context.Context, orderEntity *entity.V1CardAppleRechargeInfo, accountInfo *entity.V1CardAppleAccountInfo, code apple.Code, message string) error {
// 根据卡密错误类型确定订单失败状态
var orderStatus consts.AppleRechargeOrderStatus = consts.AppleRechargeOrderFail
var operationRemark string
switch code {
case apple.CodeAppleRedeemAlreadyClaimed:
operationRemark = "卡密已被兑换"
case apple.CodeAppleRedeemNotFound:
operationRemark = "卡密不存在"
default:
operationRemark = fmt.Sprintf("卡密错误(状态码: %d", code)
}
// 更新订单为失败状态
err := h.ModifyOrderStatus(ctx, orderEntity.OrderNo, orderStatus, operationRemark, nil)
if err != nil {
glog.Error(ctx, fmt.Sprintf("更新订单失败状态失败 - 订单号: %s, 错误: %v", orderEntity.OrderNo, err))
return err
}
// 减少分配计数(卡密错误不再重试)
_ = h.DecrementDistributionCount(ctx, orderEntity.OrderNo)
// 添加历史记录
_ = h.AddHistory(ctx, &model.AppleCardRechargeHistoryInput{
AccountID: accountInfo.Id,
OrderNo: orderEntity.OrderNo,
RechargeId: int(orderEntity.Id),
AccountName: accountInfo.Account,
Operation: consts.AppleRechargeOperationItunesFail,
Remark: fmt.Sprintf("卡密错误 - %s", message),
}, nil)
glog.Warning(ctx, fmt.Sprintf("卡密错误,订单已失败 - 订单号: %s, 账号: %s, 错误: %s", orderEntity.OrderNo, accountInfo.Account, operationRemark))
return nil
}
// ProcessOrderWithPush 处理订单:根据订单类型判断是立即进行核销处理还是创建定时任务异步处理
// 参数说明:
// - orderEntity: 待处理的订单信息
@@ -174,6 +378,7 @@ func (h *sAppleOrder) processOrderWithAccount(ctx context.Context, orderInfo *en
if err == nil && !cacheVar.IsNil() {
glog.Warning(ctx, "账户正在处理中", accountInfo.Account)
}
//3分钟超时
_ = cache.NewCache().Set(ctx, cache.PrefixAppleAccount.Key(accountInfo.Id), 1, time.Minute*3)
defer func() {
_, _ = cache.NewCache().Remove(ctx, cache.PrefixAppleAccount.Key(accountInfo.Id))
@@ -198,8 +403,7 @@ func (h *sAppleOrder) processOrderWithAccount(ctx context.Context, orderInfo *en
return err
})
if err != nil {
glog.Error(ctx, "修改订单状态失败", err)
return err
}
_ = h.handleRedeemResult(ctx, orderInfo, accountInfo)
return
return h.handleRedeemResult(ctx, orderInfo, accountInfo)
}

View File

@@ -0,0 +1,158 @@
package apple
// ==================== API 错误码枚举 ====================
// 统一的REST API错误码包含标准错误码和Apple特定错误码
type Code int
const (
// ==================== 成功 (0) ====================
CodeSuccess Code = 0 // 成功
// ==================== 认证与授权错误 (1000-1999) ====================
CodeLoginFailed Code = 1001 // 登录失败
CodeTokenExpired Code = 1002 // token过期
CodeInsufficientPermissions Code = 1003 // 权限不足
CodeInvalidToken Code = 1004 // token无效
// ==================== 业务逻辑错误 (2000-2999) ====================
CodeOrderCreationFailed Code = 2001 // 订单创建失败
CodePaymentFailed Code = 2002 // 支付失败
CodeInsufficientBalance Code = 2003 // 余额不足
CodeOperationNotAllowed Code = 2004 // 操作不允许
// ==================== 验证错误 (3000-3999) ====================
CodeInvalidInput Code = 3001 // 输入无效
CodeMissingRequiredField Code = 3002 // 缺失必填字段
CodeInvalidFormat Code = 3003 // 格式无效
CodeValidationError Code = 3004 // 验证错误
// ==================== 资源错误 (4000-4999) ====================
CodeResourceNotFound Code = 4001 // 资源不存在
CodeResourceAlreadyExists Code = 4002 // 资源已存在
CodeResourceConflict Code = 4003 // 资源冲突
// ==================== 系统错误 (5000-5999) ====================
CodeDatabaseError Code = 5001 // 数据库错误
CodeExternalServiceError Code = 5002 // 外部服务错误
CodeCacheError Code = 5003 // 缓存错误
CodeInternalError Code = 5004 // 内部系统错误
CodeNotImplemented Code = 5005 // 功能未实现
// ==================== Apple 特定错误 (8000-8099) ====================
// Apple 账户错误 (8001-8005)
CodeAppleAccountForbidden Code = 8001 // 苹果账户被禁用
CodeAppleAccountLocked Code = 8002 // 苹果账户被封锁
CodeApplePasswordError Code = 8003 // 苹果账号密码错误
CodeAppleStatusUnknown Code = 8004 // 苹果核销状态未知
CodeApplePasswordExpired Code = 8005 // 苹果账号密码失效,需要重新登录
// Apple 充值限制错误 (8010-8012)
CodeAppleRedeemLimitExceeded Code = 8010 // 充值次数限制
CodeAppleRedeemLimitExceededTemporarily Code = 8011 // 充值次数临时限制
CodeAppleRedeemLimitExceededPerMinute Code = 8012 // 充值次数一分钟限制
// Apple 卡密错误 (8013-8014)
CodeAppleRedeemAlreadyClaimed Code = 8013 // 卡密已经被兑换
CodeAppleRedeemNotFound Code = 8014 // 卡密不存在
// ==================== 未知错误 (9000-9999) ====================
CodeUnknownError Code = 9000 // 未知错误
)
// String 返回错误码的文字描述
func (c Code) String() string {
switch c {
case CodeSuccess:
return "成功"
case CodeLoginFailed:
return "登录失败"
case CodeTokenExpired:
return "token过期"
case CodeInsufficientPermissions:
return "权限不足"
case CodeInvalidToken:
return "token无效"
case CodeOrderCreationFailed:
return "订单创建失败"
case CodePaymentFailed:
return "支付失败"
case CodeInsufficientBalance:
return "余额不足"
case CodeOperationNotAllowed:
return "操作不允许"
case CodeInvalidInput:
return "输入无效"
case CodeMissingRequiredField:
return "缺失必填字段"
case CodeInvalidFormat:
return "格式无效"
case CodeValidationError:
return "验证错误"
case CodeResourceNotFound:
return "资源不存在"
case CodeResourceAlreadyExists:
return "资源已存在"
case CodeResourceConflict:
return "资源冲突"
case CodeDatabaseError:
return "数据库错误"
case CodeExternalServiceError:
return "外部服务错误"
case CodeCacheError:
return "缓存错误"
case CodeInternalError:
return "内部系统错误"
case CodeNotImplemented:
return "功能未实现"
case CodeAppleAccountForbidden:
return "苹果账户被禁用"
case CodeAppleAccountLocked:
return "苹果账户被封锁"
case CodeApplePasswordError:
return "苹果账号密码错误"
case CodeAppleStatusUnknown:
return "苹果核销状态未知"
case CodeApplePasswordExpired:
return "苹果账号密码失效,需要重新登录"
case CodeAppleRedeemLimitExceeded:
return "充值次数限制"
case CodeAppleRedeemLimitExceededTemporarily:
return "充值次数临时限制"
case CodeAppleRedeemLimitExceededPerMinute:
return "充值次数一分钟限制"
case CodeAppleRedeemAlreadyClaimed:
return "卡密已经被兑换"
case CodeAppleRedeemNotFound:
return "卡密不存在"
case CodeUnknownError:
return "未知错误"
default:
return "未知错误"
}
}
// IsSuccess 判断是否成功
func (c Code) IsSuccess() bool {
return c == CodeSuccess
}
// IsAppleAccountError 判断是否是苹果账户相关错误
func (c Code) IsAppleAccountError() bool {
return c >= 8001 && c <= 8005
}
// IsAppleRedeemLimitError 判断是否是苹果充值限制错误
func (c Code) IsAppleRedeemLimitError() bool {
return c >= 8010 && c <= 8012
}
// IsAppleCardError 判断是否是苹果卡密相关错误
func (c Code) IsAppleCardError() bool {
return c >= 8013 && c <= 8014
}
// IsAppleError 判断是否是苹果特定错误
func (c Code) IsAppleError() bool {
return c >= 8001 && c <= 8099
}

View File

@@ -8,10 +8,9 @@ type RedeemReq struct {
}
type RedeemResp struct {
StatusDescription string `json:"status_description" description:"状态描述"`
BalanceBefore string `json:"balance_before" description:"兑换账户余额"`
BalanceAfter string `json:"balance_after" description:"兑换后账户余额"`
Amount string `json:"amount" description:"本次兑换金额"`
BalanceBefore float64 `json:"balance_before" description:"兑换前账户余额"`
BalanceAfter float64 `json:"balance_after" description:"兑换账户余额"`
Amount float64 `json:"amount" description:"本次兑换金额"`
OrderId string `json:"order_id" description:"订单ID"`
}
@@ -23,7 +22,6 @@ type QueryBalanceReq struct {
type QueryBalanceResp struct {
Status int `json:"status" description:"查询状态0成功其他"`
StatusDescription string `json:"status_description" description:"状态描述"`
Balance string `json:"balance" description:"当前账户余额"`
OrderId string `json:"order_id" description:"订单ID"`
}
@@ -35,8 +33,8 @@ type HeartBeatResp struct {
}
type Resp[T any] struct {
Data *T `json:"data"`
Code int `json:"code"`
Data *T `json:"data,omitempty"`
Code Code `json:"code"`
Message string `json:"message"`
TraceId string `json:"trace_id"`
}