阶段四:收口查询依赖与应用服务装配
This commit is contained in:
1 parent
67e245d143
commit
e81c003601
26 files changed
+2229
-2224
No files matched your search
+1201
-1681
File diff suppressed because it is too large.
Load diff
@@ -93,8 +93,8 @@ app shell / routes
|
||||
| 1. PR CI 与测试基础 | 已完成 | 独立 CI、测试 DB 模板、可执行 race | CI、独立模板、server smoke race 和完整 race 均有验证 |
|
||||
| 2. 敏感数据访问边界 | 已完成 | 摘要、凭证、登录秘密分离 | 生产完整详情白名单、所有权/凭证锁审计、SQLite/MySQL/Postgres 窄查询回归和全量门禁已完成 |
|
||||
| 3. HTTP API 契约 | 已完成 | 统一错误、具名 DTO、版本化路径 | 统一错误 DTO、具名成功 DTO、所有前端业务调用方版本化、旧路径兼容和最终审计均已完成 |
|
||||
| 4. Server 应用服务 | 进行中 | 订单、发布、登录、聊天纵向抽取 | 订单核心用例已进入应用服务,下一步收敛统一 DTO 映射 |
|
||||
| 5. 应用生命周期装配 | 未开始 | 消除必需依赖 setter 回填 | 构造验证与幂等关闭测试 |
|
||||
| 4. Server 应用服务 | 已完成 | 订单、发布、登录、聊天纵向抽取 | 应用服务、事务边界、后台生命周期和 Server 查询依赖均已收口,handler 不再直接访问数据库 |
|
||||
| 5. 应用生命周期装配 | 进行中 | 消除必需依赖 setter 回填 | 构造验证与幂等关闭测试 |
|
||||
| 6. Engine 与 Automation | 未开始 | facade + 独立状态组件 | race、生命周期与冻结规范测试 |
|
||||
| 7. React Feature 化 | 未开始 | 页面、Hook、API、类型按领域拆分 | 行为测试、懒加载和 bundle 记录 |
|
||||
| 8. DB 与事务治理 | 未开始 | 窄接口、事务执行器、方言门禁 | 上层无裸 DB,多数据库回归 |
|
||||
@@ -103,7 +103,7 @@ app shell / routes
|
||||
|
||||
### 当前执行入口
|
||||
|
||||
- 当前阶段:阶段 4“Server 应用服务”(进行中);阶段 3 HTTP API 契约已完成最终审计;
|
||||
- 当前阶段:阶段 5“应用生命周期装配”(进行中);阶段 4 Server 应用服务与阶段 3 HTTP API 契约已完成最终审计;
|
||||
- 已完成:总计划、依赖规则、中文注释规范、`AGENTS.md` 强约束,以及 Go/TypeScript AST 注释检查器和历史基线;
|
||||
- 阶段 1 已完成:server 测试模板预置管理员和账号 cookie,普通测试约 21.3 秒,完整 server race 约 194.3 秒通过;
|
||||
- 已完成阶段 2 逻辑切片一“Repository 敏感数据边界”:建立 `CookieSummary`、`ListOwnedIDs`、`ExistsOwned`、`GetOwnerID`、`GetSummaryOwned` 和原子 `GetValueOwned`,覆盖跨用户、无效 user ID 及无效密文回归;
|
||||
@@ -159,7 +159,8 @@ app shell / routes
|
||||
- 已完成阶段 4 第四个 PR 切片“账号登录应用服务边界提取”:新增不依赖 `net/http` 的账号登录应用服务,覆盖扫码结果幂等持久化、Cookie Jar/扁平 Cookie 合并、账号新增与更新、资料刷新、登录审计和运行时重启;HTTP handler 仅保留请求解析、所有权校验和契约映射,保留扫码会话锁与账号凭证锁不变量;新增服务层测试并通过全量门禁,合并为一个可回滚提交;
|
||||
- 已完成阶段 4 第五个 PR 切片“聊天与通知应用服务边界提取”:新增不依赖 `net/http` 的通信应用服务,覆盖账号任务设置/执行/记录、聊天文字与图片发送、聊天历史读取/已读、通知渠道 CRUD、账号绑定和删除;保留 WebSocket 订阅、聊天事件广播、通知 outbox 与失败状态语义;新增服务层测试并通过全量门禁,合并为一个可回滚提交;
|
||||
- 已完成阶段 4 第六个 PR 切片“Server 事务与生命周期边界收口”:新增 Server 统一 Unit of Work,订单更新与导入不再直接管理事务;新增后台任务生命周期登记入口,HTTP 优雅关闭与批量发布恢复扫描器统一纳入等待流程;修复服务不可用时 handler 先做资源归属校验导致状态码变化的问题;新增事务提交/回滚测试并通过全量门禁,合并为一个可回滚提交;
|
||||
- 阶段 4 下一 PR 切片为“Server 直接依赖清理与应用服务装配收口”:继续迁移剩余跨 repository handler 操作,统一应用服务创建入口,但不把单个查询拆成独立提交;
|
||||
- 已完成阶段 4 第七个 PR 切片“Server 直接依赖清理与应用服务装配收口”:统一装配订单、发布、登录、通信和分析应用服务;默认回复、账号设置、AI 设置、通知绑定、管理员查询及订单分析查询均迁移到 repository 或应用服务边界;handler 不再直接访问 `Store.DB`,新增装配一致性测试并通过全量门禁,合并为一个可回滚提交;
|
||||
- 阶段 5 下一 PR 切片为“应用构造依赖验证与生命周期接口”:围绕 Server/应用服务构造参数、必需依赖校验、幂等 Start/Stop 和 worker 等待建立显式生命周期入口,不把 setter 替换拆成多个提交;
|
||||
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
|
||||
|
||||
## 6. 阶段 0:治理文档与强约束
|
||||
@@ -568,3 +569,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-14 | 完成阶段 4 第四个 PR 切片“账号登录应用服务边界提取” | 新增不依赖 `net/http` 的账号登录应用服务,覆盖扫码结果幂等持久化、Cookie Jar/扁平 Cookie 合并、账号新增与更新、资料刷新、登录审计和运行时重启;保留扫码会话锁、账号凭证锁和旧/版本化 HTTP 契约;新增服务层测试,Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:聊天与通知应用服务边界提取 |
|
||||
| 2026-08-14 | 完成阶段 4 第五个 PR 切片“聊天与通知应用服务边界提取” | 新增不依赖 `net/http` 的通信应用服务,覆盖账号任务设置/执行/记录、聊天文字与图片发送、聊天历史读取/已读、通知渠道 CRUD、账号绑定和删除;保留 WebSocket 订阅、聊天事件广播、通知 outbox 与失败状态语义;新增服务层测试,Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:Server 事务与生命周期边界收口 |
|
||||
| 2026-08-14 | 完成阶段 4 第六个 PR 切片“Server 事务与生命周期边界收口” | 新增 Server 统一 Unit of Work,订单更新与导入不再直接管理事务;新增后台任务生命周期登记入口,HTTP 优雅关闭与批量发布恢复扫描器统一纳入等待流程;修复服务不可用时 handler 先做资源归属校验导致状态码变化的问题;事务测试、Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:Server 直接依赖清理与应用服务装配收口 |
|
||||
| 2026-08-14 | 完成阶段 4 第七个 PR 切片“Server 直接依赖清理与应用服务装配收口” | 统一装配订单、发布、登录、通信和分析应用服务;默认回复、账号设置、AI 设置、通知绑定、管理员查询及订单分析查询迁移到 repository 或应用服务边界;handler 不再直接访问 `Store.DB`;装配测试、Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 5:应用构造依赖验证与生命周期接口 |
|
||||
@@ -0,0 +1,145 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// AdminUserSummary 是管理员用户列表的持久化查询结果。
|
||||
type AdminUserSummary struct {
|
||||
// ID 是用户标识。
|
||||
ID int64
|
||||
// Username 是用户名。
|
||||
Username string
|
||||
// Email 是用户邮箱。
|
||||
Email string
|
||||
// IsActive 表示用户是否启用。
|
||||
IsActive bool
|
||||
// IsAdmin 表示用户是否为管理员。
|
||||
IsAdmin bool
|
||||
// CreatedAt 是用户创建时间文本。
|
||||
CreatedAt string
|
||||
// CookieCount 是用户拥有的账号数量。
|
||||
CookieCount int
|
||||
}
|
||||
|
||||
// AdminCookieSummary 是管理员账号列表的持久化查询结果。
|
||||
type AdminCookieSummary struct {
|
||||
// ID 是账号标识。
|
||||
ID string
|
||||
// UserID 是账号所属用户标识。
|
||||
UserID int64
|
||||
// Remark 是账号备注。
|
||||
Remark string
|
||||
// CreatedAt 是账号创建时间文本。
|
||||
CreatedAt string
|
||||
// Owner 是所属用户名。
|
||||
Owner string
|
||||
}
|
||||
|
||||
// AdminStats 是管理员仪表盘的聚合计数。
|
||||
type AdminStats struct {
|
||||
// TotalUsers 是用户总数。
|
||||
TotalUsers int64
|
||||
// TotalCookies 是账号总数。
|
||||
TotalCookies int64
|
||||
// ActiveCookies 是启用账号总数。
|
||||
ActiveCookies int64
|
||||
// TotalCards 是卡密组总数。
|
||||
TotalCards int64
|
||||
// TotalKeywords 是关键词规则总数。
|
||||
TotalKeywords int64
|
||||
// TotalOrders 是未删除订单总数。
|
||||
TotalOrders int64
|
||||
}
|
||||
|
||||
// AdminQueries 提供管理员专用的聚合查询。
|
||||
type AdminQueries struct {
|
||||
// DB 是管理员查询使用的数据库连接。
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// ListUsers 查询管理员用户列表及其账号数量。
|
||||
func (q *AdminQueries) ListUsers(ctx context.Context) ([]AdminUserSummary, error) {
|
||||
// rows 和 err 是用户列表查询结果集及错误。
|
||||
rows, err := q.DB.QueryContext(ctx, `
|
||||
SELECT u.id, u.username, u.email, u.is_active, u.is_admin, u.created_at,
|
||||
(SELECT COUNT(*) FROM cookies c WHERE c.user_id=u.id)
|
||||
FROM users u ORDER BY u.id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 是转换后的管理员用户摘要列表。
|
||||
var out []AdminUserSummary
|
||||
for rows.Next() {
|
||||
// item 是当前用户摘要。
|
||||
var item AdminUserSummary
|
||||
// active 和 admin 是数据库中的布尔整数。
|
||||
var active, admin int
|
||||
// err 是当前用户行扫描错误。
|
||||
if err := rows.Scan(&item.ID, &item.Username, &item.Email, &active, &admin, &item.CreatedAt, &item.CookieCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.IsActive = active != 0
|
||||
item.IsAdmin = admin != 0
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ListCookies 查询管理员账号列表及所属用户名。
|
||||
func (q *AdminQueries) ListCookies(ctx context.Context) ([]AdminCookieSummary, error) {
|
||||
// rows 和 err 是管理员账号查询结果集及错误。
|
||||
rows, err := q.DB.QueryContext(ctx, `
|
||||
SELECT c.id, c.user_id, COALESCE(c.remark,''), c.created_at, COALESCE(u.username,'')
|
||||
FROM cookies c LEFT JOIN users u ON c.user_id=u.id ORDER BY c.created_at DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 是转换后的管理员账号摘要列表。
|
||||
var out []AdminCookieSummary
|
||||
for rows.Next() {
|
||||
// item 是当前账号摘要。
|
||||
var item AdminCookieSummary
|
||||
// err 是当前账号行扫描错误。
|
||||
if err := rows.Scan(&item.ID, &item.UserID, &item.Remark, &item.CreatedAt, &item.Owner); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Stats 查询管理员仪表盘全部计数。
|
||||
func (q *AdminQueries) Stats(ctx context.Context) (AdminStats, error) {
|
||||
// stats 是管理员统计结果。
|
||||
var stats AdminStats
|
||||
// queries 是管理员统计使用的固定 SQL 与目标字段。
|
||||
queries := []struct {
|
||||
query string
|
||||
dest *int64
|
||||
}{
|
||||
{`SELECT COUNT(*) FROM users`, &stats.TotalUsers},
|
||||
{`SELECT COUNT(*) FROM cookies`, &stats.TotalCookies},
|
||||
{`SELECT COUNT(*) FROM cards`, &stats.TotalCards},
|
||||
{`SELECT COUNT(*) FROM orders WHERE deleted_at IS NULL`, &stats.TotalOrders},
|
||||
{`SELECT COUNT(*) FROM keywords`, &stats.TotalKeywords},
|
||||
}
|
||||
// item 是当前固定统计查询。
|
||||
for _, item := range queries {
|
||||
// err 是当前统计项查询错误。
|
||||
if err := q.DB.QueryRowContext(ctx, item.query).Scan(item.dest); err != nil {
|
||||
return AdminStats{}, err
|
||||
}
|
||||
}
|
||||
// err 是活跃账号统计查询错误。
|
||||
if err := q.DB.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM cookies c
|
||||
WHERE NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0)
|
||||
`).Scan(&stats.ActiveCookies); err != nil {
|
||||
return AdminStats{}, err
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
+52
-2
@@ -29,8 +29,9 @@ type AIReplySettings struct {
|
||||
|
||||
// AIReply 操作。
|
||||
type AIReply struct {
|
||||
DB *sql.DB
|
||||
codec *secretCodec
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// Get 取某账号 AI 回复配置。
|
||||
@@ -65,6 +66,55 @@ func (a *AIReply) Get(ctx context.Context, cookieID string) (*AIReplySettings, e
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// ListForUser 查询用户账号的 AI 回复配置,不读取或返回 API 密钥。
|
||||
func (a *AIReply) ListForUser(ctx context.Context, userID int64) ([]AIReplySettings, error) {
|
||||
rows, err := a.DB.QueryContext(ctx, `
|
||||
SELECT a.cookie_id, a.ai_enabled, a.max_discount_percent, a.max_discount_amount,
|
||||
a.max_bargain_rounds, COALESCE(a.custom_prompts, '')
|
||||
FROM ai_reply_settings a JOIN cookies c ON c.id=a.cookie_id WHERE c.user_id=?`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []AIReplySettings
|
||||
for rows.Next() {
|
||||
var item AIReplySettings
|
||||
var enabled int
|
||||
if err := rows.Scan(&item.CookieID, &enabled, &item.MaxDiscountPercent, &item.MaxDiscountAmount, &item.MaxBargainRounds, &item.CustomPrompts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.AIEnabled = enabled != 0
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpsertSettings 保存指定账号的 AI 回复开关和砍价约束。
|
||||
func (a *AIReply) UpsertSettings(ctx context.Context, cookieID string, settings AIReplySettings) error {
|
||||
_, err := a.DB.ExecContext(ctx,
|
||||
`INSERT INTO ai_reply_settings
|
||||
(cookie_id, ai_enabled, max_discount_percent, max_discount_amount,
|
||||
max_bargain_rounds, custom_prompts, updated_at)
|
||||
VALUES (?,?,?,?,?,?,CURRENT_TIMESTAMP)`+dialectUpsert(a.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
"ai_enabled": "EXCLUDED.ai_enabled",
|
||||
"max_discount_percent": "EXCLUDED.max_discount_percent",
|
||||
"max_discount_amount": "EXCLUDED.max_discount_amount",
|
||||
"max_bargain_rounds": "EXCLUDED.max_bargain_rounds",
|
||||
"custom_prompts": "EXCLUDED.custom_prompts",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}), cookieID, boolToInt(settings.AIEnabled), settings.MaxDiscountPercent,
|
||||
settings.MaxDiscountAmount, settings.MaxBargainRounds, nullableAIString(settings.CustomPrompts))
|
||||
return err
|
||||
}
|
||||
|
||||
// nullableAIString 将空的自定义提示词转换为数据库 NULL。
|
||||
func nullableAIString(value string) any {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// ConversationHistory 返回最近的会话消息,结果按时间正序排列。
|
||||
func (a *AIReply) ConversationHistory(ctx context.Context, cookieID, chatID, itemID string, limit int) ([]AIConversationMessage, error) {
|
||||
if limit <= 0 || limit > 20 {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// AnalyticsQueries 提供订单分析应用服务使用的只读查询执行边界。
|
||||
type AnalyticsQueries struct {
|
||||
// DB 是订单分析查询使用的数据库连接。
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// QueryRowContext 执行单行订单分析查询。
|
||||
func (q *AnalyticsQueries) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row {
|
||||
return q.DB.QueryRowContext(ctx, query, args...)
|
||||
}
|
||||
|
||||
// QueryContext 执行多行订单分析查询。
|
||||
func (q *AnalyticsQueries) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
|
||||
return q.DB.QueryContext(ctx, query, args...)
|
||||
}
|
||||
@@ -24,6 +24,16 @@ type AutomationRules struct {
|
||||
Dialect Dialect
|
||||
}
|
||||
|
||||
// ExistsPublishRule 判断指定发布自动化规则是否已经存在,避免重复创建同一规则。
|
||||
func (a *AutomationRules) ExistsPublishRule(ctx context.Context, input AutomationRuleInput) (bool, error) {
|
||||
var exists bool
|
||||
err := a.DB.QueryRowContext(ctx, `SELECT EXISTS(
|
||||
SELECT 1 FROM automation_rules
|
||||
WHERE user_id=? AND cookie_id=? AND item_id=? AND trigger_type=? AND name=? AND deleted_at IS NULL
|
||||
)`, input.UserID, input.CookieID, input.ItemID, input.TriggerType, input.Name).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
// AutomationRule 是一条自动化规则。规则只描述“什么时候、对哪个商品生效”,
|
||||
// 具体做什么放在 AutomationAction 中,便于组合付款发货、评价赠品、求评价等流程。
|
||||
type AutomationRule struct {
|
||||
|
||||
@@ -23,6 +23,15 @@ type Notifications struct {
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// OwnsChannel 判断通知渠道是否归属于指定用户。
|
||||
func (n *Notifications) OwnsChannel(ctx context.Context, channelID, userID int64) (bool, error) {
|
||||
var exists bool
|
||||
err := n.DB.QueryRowContext(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`,
|
||||
channelID, userID).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
type NotificationOutboxInput struct {
|
||||
ChannelID int64
|
||||
EventType string
|
||||
@@ -37,6 +46,72 @@ type NotificationOutboxMessage struct {
|
||||
AttemptCount int
|
||||
}
|
||||
|
||||
// NotificationBindingRow 是用户账号与通知渠道的绑定摘要。
|
||||
type NotificationBindingRow struct {
|
||||
// ID 是绑定记录标识。
|
||||
ID int64
|
||||
// CookieID 是账号标识。
|
||||
CookieID string
|
||||
// ChannelID 是通知渠道标识。
|
||||
ChannelID int64
|
||||
// ChannelName 是通知渠道名称。
|
||||
ChannelName string
|
||||
// Enabled 表示绑定是否启用。
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// ListBindingsForUser 查询用户所有账号的通知渠道绑定。
|
||||
func (n *Notifications) ListBindingsForUser(ctx context.Context, userID int64) ([]NotificationBindingRow, error) {
|
||||
rows, err := n.DB.QueryContext(ctx, `
|
||||
SELECT mn.id, mn.cookie_id, mn.channel_id, COALESCE(nc.name, ''), mn.enabled
|
||||
FROM message_notifications mn
|
||||
JOIN cookies c ON c.id=mn.cookie_id
|
||||
JOIN notification_channels nc ON nc.id=mn.channel_id AND nc.user_id=c.user_id
|
||||
WHERE c.user_id=? ORDER BY mn.id DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []NotificationBindingRow
|
||||
for rows.Next() {
|
||||
var item NotificationBindingRow
|
||||
var enabled int
|
||||
if err := rows.Scan(&item.ID, &item.CookieID, &item.ChannelID, &item.ChannelName, &enabled); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.Enabled = enabled != 0
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SetSingleBinding 更新单个账号通知渠道的启用状态。
|
||||
func (n *Notifications) SetSingleBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error {
|
||||
if !enabled {
|
||||
_, err := n.DB.ExecContext(ctx, `DELETE FROM message_notifications WHERE cookie_id=? AND channel_id=?`, cookieID, channelID)
|
||||
return err
|
||||
}
|
||||
_, err := n.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES (?, ?, ?)`+
|
||||
dialectUpsert(n.Dialect, []string{"cookie_id", "channel_id"}, map[string]string{"enabled": "EXCLUDED.enabled", "updated_at": "CURRENT_TIMESTAMP"}),
|
||||
cookieID, channelID, 1)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteBinding 删除用户账号下的一条通知绑定。
|
||||
func (n *Notifications) DeleteBinding(ctx context.Context, userID, bindingID int64) error {
|
||||
_, err := n.DB.ExecContext(ctx, `
|
||||
DELETE FROM message_notifications WHERE id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, bindingID, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteAccountBindings 删除用户账号下的全部通知绑定。
|
||||
func (n *Notifications) DeleteAccountBindings(ctx context.Context, userID int64, cookieID string) error {
|
||||
_, err := n.DB.ExecContext(ctx, `
|
||||
DELETE FROM message_notifications WHERE cookie_id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, cookieID, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
// AccountChannels 取某账号已启用的通知渠道(message_notifications JOIN notification_channels)。
|
||||
// 移植自 get_account_notifications。
|
||||
func (n *Notifications) AccountChannels(ctx context.Context, cookieID string) ([]NotificationChannel, error) {
|
||||
|
||||
@@ -310,6 +310,13 @@ type CardFull struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
}
|
||||
|
||||
// ExistsOwned 判断卡密组是否属于指定用户。
|
||||
func (c *Cards) ExistsOwned(ctx context.Context, cardID, userID int64) (bool, error) {
|
||||
var exists bool
|
||||
err := c.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, cardID, userID).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
// Get 取单个卡券。
|
||||
func (c *Cards) Get(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
var cf CardFull
|
||||
|
||||
@@ -24,6 +24,20 @@ type DefaultReply struct {
|
||||
ReplyOnce bool
|
||||
}
|
||||
|
||||
// DefaultReplySummary 是按账号查询默认回复列表时使用的带账号标识视图。
|
||||
type DefaultReplySummary struct {
|
||||
// CookieID 是默认回复所属账号标识。
|
||||
CookieID string
|
||||
// Enabled 表示默认回复是否启用。
|
||||
Enabled bool
|
||||
// ReplyContent 是默认回复文字。
|
||||
ReplyContent string
|
||||
// ReplyImageURL 是默认回复图片地址。
|
||||
ReplyImageURL string
|
||||
// ReplyOnce 表示同一聊天是否只发送一次。
|
||||
ReplyOnce bool
|
||||
}
|
||||
|
||||
// DefaultReplyRecord 记录 reply_once 消息各部分的投递状态。
|
||||
type DefaultReplyRecord struct {
|
||||
Status string
|
||||
@@ -91,6 +105,64 @@ func (d *DefaultReplies) Get(ctx context.Context, cookieID string) (*DefaultRepl
|
||||
return &dr, nil
|
||||
}
|
||||
|
||||
// Upsert 保存或覆盖指定账号的默认回复配置。
|
||||
func (d *DefaultReplies) Upsert(ctx context.Context, cookieID string, reply DefaultReply) error {
|
||||
_, err := d.DB.ExecContext(ctx,
|
||||
`INSERT INTO default_replies (cookie_id, enabled, reply_content, reply_image_url, reply_once, updated_at)
|
||||
VALUES (?,?,?,?,?,CURRENT_TIMESTAMP)`+dialectUpsert(d.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
"enabled": "EXCLUDED.enabled",
|
||||
"reply_content": "EXCLUDED.reply_content",
|
||||
"reply_image_url": "EXCLUDED.reply_image_url",
|
||||
"reply_once": "EXCLUDED.reply_once",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cookieID, boolToInt(reply.Enabled), reply.ReplyContent, defaultReplyNullableString(reply.ReplyImageURL), boolToInt(reply.ReplyOnce))
|
||||
return err
|
||||
}
|
||||
|
||||
// defaultReplyNullableString 将空图片地址转换为数据库 NULL,保持历史存储语义。
|
||||
func defaultReplyNullableString(value string) any {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// ListForUser 查询用户所有账号的默认回复配置。
|
||||
func (d *DefaultReplies) ListForUser(ctx context.Context, userID int64) ([]DefaultReplySummary, error) {
|
||||
rows, err := d.DB.QueryContext(ctx, `
|
||||
SELECT dr.cookie_id, dr.enabled, COALESCE(dr.reply_content,''), dr.reply_once, COALESCE(dr.reply_image_url,'')
|
||||
FROM default_replies dr JOIN cookies c ON c.id=dr.cookie_id WHERE c.user_id=?`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []DefaultReplySummary
|
||||
for rows.Next() {
|
||||
var item DefaultReplySummary
|
||||
var enabled, replyOnce int
|
||||
if err := rows.Scan(&item.CookieID, &enabled, &item.ReplyContent, &replyOnce, &item.ReplyImageURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.Enabled = enabled != 0
|
||||
item.ReplyOnce = replyOnce != 0
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Delete 删除指定账号的默认回复配置。
|
||||
func (d *DefaultReplies) Delete(ctx context.Context, cookieID string) error {
|
||||
_, err := d.DB.ExecContext(ctx, `DELETE FROM default_replies WHERE cookie_id=?`, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ClearRecords 清空指定账号的默认回复投递记录。
|
||||
func (d *DefaultReplies) ClearRecords(ctx context.Context, cookieID string) error {
|
||||
_, err := d.DB.ExecContext(ctx, `DELETE FROM default_reply_records WHERE cookie_id=?`, cookieID)
|
||||
return err
|
||||
}
|
||||
|
||||
// HasRecord 是否已对该 chat_id 回复过(reply_once 用)。
|
||||
func (d *DefaultReplies) HasRecord(ctx context.Context, cookieID, chatID string) bool {
|
||||
var n int
|
||||
|
||||
@@ -22,6 +22,7 @@ type Store struct {
|
||||
AIReply *AIReply
|
||||
Notifications *Notifications
|
||||
Settings *SystemSettings
|
||||
UserSettings *UserSettings
|
||||
WSMessages *WSMessageStore
|
||||
PublishBatches *ItemPublishBatches
|
||||
Tokens *AccountTokens
|
||||
@@ -30,6 +31,8 @@ type Store struct {
|
||||
RiskLogs *RiskControlLogs
|
||||
Chats *ChatStore
|
||||
AccountTasks *AccountTaskStore
|
||||
Admin *AdminQueries
|
||||
Analytics *AnalyticsQueries
|
||||
|
||||
credentialMu sync.Mutex
|
||||
credentialLocks map[string]*sync.Mutex
|
||||
@@ -51,9 +54,10 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
Keywords: &Keywords{DB: db, Dialect: dialect},
|
||||
DefaultReps: &DefaultReplies{DB: db, Dialect: dialect},
|
||||
ItemReps: &ItemReplies{DB: db, Dialect: dialect},
|
||||
AIReply: &AIReply{DB: db, codec: codec},
|
||||
AIReply: &AIReply{DB: db, Dialect: dialect, codec: codec},
|
||||
Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec},
|
||||
Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec},
|
||||
UserSettings: &UserSettings{DB: db, Dialect: dialect},
|
||||
WSMessages: &WSMessageStore{DB: db},
|
||||
PublishBatches: &ItemPublishBatches{DB: db},
|
||||
Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec},
|
||||
@@ -62,6 +66,8 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
|
||||
Chats: &ChatStore{DB: db, Dialect: dialect},
|
||||
AccountTasks: &AccountTaskStore{DB: db, Dialect: dialect},
|
||||
Admin: &AdminQueries{DB: db},
|
||||
Analytics: &AnalyticsQueries{DB: db},
|
||||
credentialLocks: make(map[string]*sync.Mutex),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// UserSettings 保存用户级界面与偏好设置。
|
||||
type UserSettings struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
}
|
||||
|
||||
// AllForUser 查询指定用户的全部设置。
|
||||
func (s *UserSettings) AllForUser(ctx context.Context, userID int64) (map[string]string, error) {
|
||||
// keyColumn 是当前 SQL 方言中安全引用的 key 列名。
|
||||
keyColumn := dialectQuote(s.Dialect, "key")
|
||||
// rows 和 err 是用户设置查询结果集及错误。
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT `+keyColumn+`, value FROM user_settings WHERE user_id=?`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// result 是用户设置键值映射。
|
||||
result := make(map[string]string)
|
||||
for rows.Next() {
|
||||
// key 和 value 是当前设置行的键和值。
|
||||
var key, value string
|
||||
// err 是当前设置行扫描错误。
|
||||
if err := rows.Scan(&key, &value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[key] = value
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// GetForUser 查询用户单项设置,不存在时返回空字符串。
|
||||
func (s *UserSettings) GetForUser(ctx context.Context, userID int64, key string) (string, error) {
|
||||
// keyColumn 是当前 SQL 方言中安全引用的 key 列名。
|
||||
keyColumn := dialectQuote(s.Dialect, "key")
|
||||
// value 是用户设置值。
|
||||
var value string
|
||||
// err 是用户单项设置查询错误。
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT value FROM user_settings WHERE user_id=? AND `+keyColumn+`=?`, userID, key).Scan(&value)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", nil
|
||||
}
|
||||
return value, err
|
||||
}
|
||||
|
||||
// SetForUser 保存或覆盖用户单项设置。
|
||||
func (s *UserSettings) SetForUser(ctx context.Context, userID int64, key, value string) error {
|
||||
// keyColumn 是当前 SQL 方言中安全引用的 key 列名。
|
||||
keyColumn := dialectQuote(s.Dialect, "key")
|
||||
// err 是用户设置写入错误。
|
||||
_, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO user_settings (user_id, `+keyColumn+`, value, updated_at) VALUES (?,?,?,CURRENT_TIMESTAMP)`+
|
||||
dialectUpsert(s.Dialect, []string{"user_id", keyColumn}, map[string]string{
|
||||
"value": "EXCLUDED.value", "updated_at": "CURRENT_TIMESTAMP",
|
||||
}), userID, key, value)
|
||||
return err
|
||||
}
|
||||
@@ -54,7 +54,7 @@ type accountProfileResult struct {
|
||||
|
||||
// accountLoginApplication 返回当前 Server 绑定的账号登录应用服务。
|
||||
func (s *Server) accountLoginApplication() *accountLoginService {
|
||||
return &accountLoginService{server: s}
|
||||
return s.applicationServiceSet().accountLogin
|
||||
}
|
||||
|
||||
// CreateCookie 创建账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
|
||||
@@ -16,39 +16,19 @@ func (s *Server) mountAdminReal(r chi.Router) {
|
||||
}
|
||||
|
||||
func (s *Server) adminListUsers(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT id, username, email, is_active, is_admin, created_at FROM users ORDER BY id`)
|
||||
rows, err := s.Store.Admin.ListUsers(r.Context())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []adminUserResponse
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
var username, email, createdAt string
|
||||
var isActive, isAdmin int
|
||||
if err := rows.Scan(&id, &username, &email, &isActive, &isAdmin, &createdAt); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取用户数据失败")
|
||||
return
|
||||
}
|
||||
// 统计每个用户的账号数。
|
||||
var cookieCount int
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(),
|
||||
`SELECT COUNT(*) FROM cookies WHERE user_id=?`, id).Scan(&cookieCount); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计用户账号失败")
|
||||
return
|
||||
}
|
||||
for _, row := range rows {
|
||||
out = append(out, adminUserResponse{
|
||||
ID: id, Username: username, Email: email,
|
||||
IsActive: isActive != 0, IsAdmin: isAdmin != 0,
|
||||
CreatedAt: createdAt, CookieCount: cookieCount,
|
||||
ID: row.ID, Username: row.Username, Email: row.Email,
|
||||
IsActive: row.IsActive, IsAdmin: row.IsAdmin,
|
||||
CreatedAt: row.CreatedAt, CookieCount: row.CookieCount,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取用户数据失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
@@ -79,70 +59,33 @@ func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (s *Server) adminListCookies(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT c.id, c.user_id, COALESCE(c.remark,''), c.created_at, u.username
|
||||
FROM cookies c LEFT JOIN users u ON c.user_id=u.id ORDER BY c.created_at DESC`)
|
||||
rows, err := s.Store.Admin.ListCookies(r.Context())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []adminCookieResponse
|
||||
for rows.Next() {
|
||||
var id string
|
||||
var uid int64
|
||||
var remark, createdAt, username string
|
||||
if err := rows.Scan(&id, &uid, &remark, &createdAt, &username); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号数据失败")
|
||||
return
|
||||
}
|
||||
for _, row := range rows {
|
||||
out = append(out, adminCookieResponse{
|
||||
ID: id, UserID: uid, Remark: remark,
|
||||
CreatedAt: createdAt, Owner: username,
|
||||
Enabled: s.Store.Cookies.GetStatus(r.Context(), id),
|
||||
ID: row.ID, UserID: row.UserID, Remark: row.Remark,
|
||||
CreatedAt: row.CreatedAt, Owner: row.Owner,
|
||||
Enabled: s.Store.Cookies.GetStatus(r.Context(), row.ID),
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号数据失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) {
|
||||
// 字段名与前端 AdminStats 接口对齐:
|
||||
// total_users / total_cookies / active_cookies / total_cards / total_keywords / total_orders
|
||||
var totalUsers, totalCookies, totalCards, totalOrders, totalKeywords int64
|
||||
counts := []struct {
|
||||
query string
|
||||
dest *int64
|
||||
}{
|
||||
{`SELECT COUNT(*) FROM users`, &totalUsers},
|
||||
{`SELECT COUNT(*) FROM cookies`, &totalCookies},
|
||||
{`SELECT COUNT(*) FROM cards`, &totalCards},
|
||||
{`SELECT COUNT(*) FROM orders WHERE deleted_at IS NULL`, &totalOrders},
|
||||
{`SELECT COUNT(*) FROM keywords`, &totalKeywords},
|
||||
}
|
||||
for _, count := range counts {
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), count.query).Scan(count.dest); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计数据失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 活跃账号:cookie_status.enabled=1 的数量(无记录默认启用,故统计 enabled=1 或无记录的)。
|
||||
var activeCookies int64
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), `
|
||||
SELECT COUNT(*) FROM cookies c
|
||||
WHERE NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0)
|
||||
`).Scan(&activeCookies); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计活跃账号失败")
|
||||
// stats 是管理员仪表盘的数据库聚合结果。
|
||||
stats, err := s.Store.Admin.Stats(r.Context())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计数据失败")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, adminStatsResponse{
|
||||
TotalUsers: totalUsers, TotalCookies: totalCookies, ActiveCookies: activeCookies,
|
||||
TotalCards: totalCards, TotalKeywords: totalKeywords, TotalOrders: totalOrders,
|
||||
TotalUsers: stats.TotalUsers, TotalCookies: stats.TotalCookies, ActiveCookies: stats.ActiveCookies,
|
||||
TotalCards: stats.TotalCards, TotalKeywords: stats.TotalKeywords, TotalOrders: stats.TotalOrders,
|
||||
// 统计响应继续保留原有字段名称,兼容管理员仪表盘。
|
||||
// DTO 字段由具名结构统一维护,避免动态 map 漏字段。
|
||||
// 所有统计值均来自当前数据库快照。
|
||||
|
||||
@@ -2,7 +2,6 @@ package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -23,68 +22,15 @@ func (s *Server) mountAnalyticsReal(r chi.Router) {
|
||||
// dashboardStats 返回当前登录用户的数据概览。管理员全局统计仍由 /admin/stats 提供,
|
||||
// 避免普通用户访问管理员接口,也避免把全局资源数和用户自己的订单收益混在一起。
|
||||
func (s *Server) dashboardStats(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 是当前请求的认证会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess == nil {
|
||||
writeErr(w, http.StatusUnauthorized, "未登录")
|
||||
return
|
||||
}
|
||||
|
||||
counts := map[string]int64{
|
||||
"total_cookies": 0,
|
||||
"active_cookies": 0,
|
||||
"total_cards": 0,
|
||||
"available_card_stock": 0,
|
||||
"total_keywords": 0,
|
||||
"total_orders": 0,
|
||||
}
|
||||
queries := []struct {
|
||||
key string
|
||||
query string
|
||||
}{
|
||||
{"total_cookies", `SELECT COUNT(*) FROM cookies WHERE user_id=?`},
|
||||
{"total_cards", `SELECT COUNT(*) FROM cards WHERE user_id=?`},
|
||||
{"total_keywords", `SELECT COUNT(*) FROM keywords k WHERE EXISTS (
|
||||
SELECT 1 FROM cookies c WHERE c.id=k.cookie_id AND c.user_id=?)`},
|
||||
{"total_orders", `SELECT COUNT(*) FROM orders o WHERE o.deleted_at IS NULL AND EXISTS (
|
||||
SELECT 1 FROM cookies c WHERE c.id=o.cookie_id AND c.user_id=?)`},
|
||||
}
|
||||
for _, item := range queries {
|
||||
var count int64
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), item.query, sess.UserID).Scan(&count); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计数据失败")
|
||||
return
|
||||
}
|
||||
counts[item.key] = count
|
||||
}
|
||||
|
||||
var activeCookies int64
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), `
|
||||
SELECT COUNT(*) FROM cookies c
|
||||
WHERE c.user_id=?
|
||||
AND NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0)
|
||||
`, sess.UserID).Scan(&activeCookies); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计活跃账号失败")
|
||||
return
|
||||
}
|
||||
counts["active_cookies"] = activeCookies
|
||||
cards, err := s.Store.Cards.AllForUser(r.Context(), sess.UserID)
|
||||
// result 和 err 是订单分析应用服务返回的仪表盘摘要。
|
||||
result, err := s.analyticsApplication().DashboardStats(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "统计卡密库存失败")
|
||||
writeErr(w, http.StatusInternalServerError, "统计数据失败")
|
||||
return
|
||||
}
|
||||
var available int64
|
||||
for _, card := range cards {
|
||||
if card.Enabled && card.Type == "data" {
|
||||
for _, line := range strings.Split(strings.ReplaceAll(card.DataContent, "\r\n", "\n"), "\n") {
|
||||
if strings.TrimSpace(line) != "" {
|
||||
available++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
counts["available_card_stock"] = available
|
||||
|
||||
writeJSON(w, http.StatusOK, dashboardStatsResponse{TotalCookies: counts["total_cookies"], ActiveCookies: counts["active_cookies"], TotalCards: counts["total_cards"], AvailableCardStock: counts["available_card_stock"], TotalKeywords: counts["total_keywords"], TotalOrders: counts["total_orders"]})
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// 有效订单状态只统计以下几种。
|
||||
@@ -92,202 +38,40 @@ var validOrderStatuses = []string{"pending_ship", "paid", "2", "shipped", "3", "
|
||||
|
||||
// orderAnalytics 汇总指定日期范围内的收益以及按日、状态、城市和商品分布。
|
||||
func (s *Server) orderAnalytics(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 是当前请求的认证会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// startDate、endDate 和 location 是订单分析的日期范围及时区参数。
|
||||
startDate := r.URL.Query().Get("start_date")
|
||||
endDate := r.URL.Query().Get("end_date")
|
||||
location := analyticsLocation(r.URL.Query().Get("timezone_offset_minutes"))
|
||||
|
||||
// 构建 WHERE 条件(user_id 通过 cookies 关联过滤)。
|
||||
// where 和 params 是按用户、日期和状态归一化后的查询条件。
|
||||
where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses, location)
|
||||
// 金额先做方言相关的格式校验再转换,避免 PostgreSQL 遇到历史脏数据时整页 500。
|
||||
amountClean := analyticsAmountExpression(s.Store.Dialect, "amount")
|
||||
amountFilter := ` AND ` + amountClean + ` IS NOT NULL`
|
||||
|
||||
// 1. 收益统计。
|
||||
var rev struct {
|
||||
TotalOrders int
|
||||
TotalAmount float64
|
||||
AvgAmount float64
|
||||
UniqueBuyers int
|
||||
UniqueItems int
|
||||
}
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), `
|
||||
SELECT COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0),
|
||||
COALESCE(AVG(`+amountClean+`),0), COUNT(DISTINCT buyer_id), COUNT(DISTINCT item_id)
|
||||
FROM orders `+where+amountFilter, params...).Scan(
|
||||
&rev.TotalOrders, &rev.TotalAmount, &rev.AvgAmount, &rev.UniqueBuyers, &rev.UniqueItems); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询收益统计失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 2. 按用户本地日期统计。数据库统一保存 UTC,分组在 Go 中完成,避免三种方言
|
||||
// 的时区转换函数不同以及 SQLite DATE(created_at) 把凌晨订单归到前一天。
|
||||
daily := []analyticsDailyStatsResponse{}
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(), `
|
||||
SELECT order_id,amount,created_at FROM orders `+where+amountFilter, params...)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询每日统计失败")
|
||||
return
|
||||
}
|
||||
type dailyValue struct {
|
||||
count int
|
||||
amount float64
|
||||
}
|
||||
dailyMap := map[string]dailyValue{}
|
||||
for rows.Next() {
|
||||
var orderID, amountRaw, createdAt string
|
||||
if rows.Scan(&orderID, &amountRaw, &createdAt) != nil {
|
||||
continue
|
||||
}
|
||||
created := parseAnalyticsDBTime(createdAt)
|
||||
if created.IsZero() {
|
||||
continue
|
||||
}
|
||||
date := created.In(location).Format("2006-01-02")
|
||||
value := dailyMap[date]
|
||||
value.count++
|
||||
value.amount += parseAnalyticsAmount(amountRaw)
|
||||
dailyMap[date] = value
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
writeErr(w, http.StatusInternalServerError, "查询每日统计失败")
|
||||
return
|
||||
}
|
||||
_ = rows.Close()
|
||||
dates := make([]string, 0, len(dailyMap))
|
||||
for date := range dailyMap {
|
||||
dates = append(dates, date)
|
||||
}
|
||||
sort.Strings(dates)
|
||||
for _, date := range dates {
|
||||
value := dailyMap[date]
|
||||
daily = append(daily, analyticsDailyStatsResponse{Date: date, OrderCount: value.count, Amount: round2(value.amount)})
|
||||
}
|
||||
|
||||
// 3. 按状态统计。
|
||||
statusStats := []analyticsStatusStatsResponse{}
|
||||
type statusValue struct {
|
||||
count int
|
||||
amount float64
|
||||
}
|
||||
statusMap := map[string]statusValue{}
|
||||
rows, err = s.Store.DB.QueryContext(r.Context(), `
|
||||
SELECT COALESCE(order_status,'unknown'), COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0)
|
||||
FROM orders `+where+amountFilter+`
|
||||
GROUP BY order_status ORDER BY COUNT(DISTINCT order_id) DESC`, params...)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询状态统计失败")
|
||||
return
|
||||
}
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var count int
|
||||
var amount float64
|
||||
if rows.Scan(&status, &count, &amount) == nil {
|
||||
status = db.NormalizeOrderStatus(status)
|
||||
value := statusMap[status]
|
||||
value.count += count
|
||||
value.amount += amount
|
||||
statusMap[status] = value
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
writeErr(w, http.StatusInternalServerError, "查询状态统计失败")
|
||||
return
|
||||
}
|
||||
_ = rows.Close()
|
||||
statusNames := make([]string, 0, len(statusMap))
|
||||
for status := range statusMap {
|
||||
statusNames = append(statusNames, status)
|
||||
}
|
||||
sort.Slice(statusNames, func(i, j int) bool {
|
||||
return statusMap[statusNames[i]].count > statusMap[statusNames[j]].count
|
||||
// amountClean 和 amountFilter 是按数据库方言生成的金额过滤条件。
|
||||
amountClean, amountFilter := analyticsQueryAmountFilter(s.Store, "amount")
|
||||
// result 和 err 是订单分析应用服务返回的具名统计结果。
|
||||
result, err := s.analyticsApplication().OrderAnalytics(r.Context(), analyticsQuery{
|
||||
Where: where, Params: analyticsQueryParamsCopy(params), AmountClean: amountClean, AmountFilter: amountFilter, Location: location,
|
||||
})
|
||||
for _, status := range statusNames {
|
||||
value := statusMap[status]
|
||||
statusStats = append(statusStats, analyticsStatusStatsResponse{Status: status, Count: value.count, Amount: round2(value.amount)})
|
||||
}
|
||||
|
||||
// 4. 按城市统计。
|
||||
cityStats := []analyticsCityStatsResponse{}
|
||||
rows, err = s.Store.DB.QueryContext(r.Context(), `
|
||||
SELECT receiver_city, COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0)
|
||||
FROM orders `+where+amountFilter+`
|
||||
AND receiver_city IS NOT NULL AND receiver_city != ''
|
||||
GROUP BY receiver_city ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 50`, params...)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询城市统计失败")
|
||||
writeErr(w, http.StatusInternalServerError, analyticsErrorMessage(err))
|
||||
return
|
||||
}
|
||||
for rows.Next() {
|
||||
var city string
|
||||
var count int
|
||||
var amount float64
|
||||
if rows.Scan(&city, &count, &amount) == nil {
|
||||
cityStats = append(cityStats, analyticsCityStatsResponse{
|
||||
City: city, OrderCount: count, TotalAmount: round2(amount),
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
writeErr(w, http.StatusInternalServerError, "查询城市统计失败")
|
||||
return
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
// 5. 商品排行。
|
||||
itemStats := []analyticsItemStatsResponse{}
|
||||
rows, err = s.Store.DB.QueryContext(r.Context(), `
|
||||
SELECT item_id, COUNT(DISTINCT order_id), COALESCE(SUM(`+amountClean+`),0), COALESCE(AVG(`+amountClean+`),0)
|
||||
FROM orders `+where+amountFilter+`
|
||||
AND item_id IS NOT NULL AND item_id != ''
|
||||
GROUP BY item_id ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 20`, params...)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询商品统计失败")
|
||||
return
|
||||
}
|
||||
for rows.Next() {
|
||||
var itemID string
|
||||
var count int
|
||||
var total, avg float64
|
||||
if rows.Scan(&itemID, &count, &total, &avg) == nil {
|
||||
itemStats = append(itemStats, analyticsItemStatsResponse{
|
||||
ItemID: itemID, OrderCount: count,
|
||||
TotalAmount: round2(total), AvgAmount: round2(avg),
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
writeErr(w, http.StatusInternalServerError, "查询商品统计失败")
|
||||
return
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
writeJSON(w, http.StatusOK, orderAnalyticsResponse{
|
||||
RevenueStats: analyticsRevenueStatsResponse{
|
||||
TotalOrders: rev.TotalOrders, TotalAmount: round2(rev.TotalAmount),
|
||||
AvgAmount: round2(rev.AvgAmount), UniqueBuyers: rev.UniqueBuyers,
|
||||
UniqueItems: rev.UniqueItems,
|
||||
},
|
||||
DailyStats: daily, StatusStats: statusStats, CityStats: cityStats, ItemStats: itemStats,
|
||||
// 各统计维度分别使用具名 DTO,避免前端依赖动态键值。
|
||||
// daily_stats 保留用户本地日期,兼容已有图表横轴。
|
||||
// status_stats、city_stats 和 item_stats 保留旧字段名称。
|
||||
})
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// validOrders 有效订单明细列表(用于统计中的订单明细)。
|
||||
func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 是当前请求的认证会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// startDate、endDate 和 location 是有效订单的日期范围及时区参数。
|
||||
startDate := r.URL.Query().Get("start_date")
|
||||
endDate := r.URL.Query().Get("end_date")
|
||||
location := analyticsLocation(r.URL.Query().Get("timezone_offset_minutes"))
|
||||
// where 和 params 是按用户、日期和状态归一化后的查询条件。
|
||||
where, params := buildAnalyticsWhere(startDate, endDate, sess.UserID, validOrderStatuses, location)
|
||||
amountFilter := ` AND ` + analyticsAmountExpression(s.Store.Dialect, "orders.amount") + ` IS NOT NULL`
|
||||
// amountClean 和 amountFilter 是按数据库方言生成的金额过滤条件。
|
||||
amountClean, amountFilter := analyticsQueryAmountFilter(s.Store, "orders.amount")
|
||||
// page 和 pageSize 是已经限制在安全范围内的分页参数。
|
||||
page := atoiDefault(r.URL.Query().Get("page"), 1)
|
||||
pageSize := atoiDefault(r.URL.Query().Get("page_size"), 500)
|
||||
if page < 1 {
|
||||
@@ -296,47 +80,15 @@ func (s *Server) validOrders(w http.ResponseWriter, r *http.Request) {
|
||||
if pageSize < 1 || pageSize > 500 {
|
||||
pageSize = 500
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
var total int
|
||||
if err := s.Store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM orders `+where+amountFilter, params...).Scan(&total); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
queryParams := append(append([]any{}, params...), pageSize, offset)
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(), `
|
||||
SELECT orders.order_id, COALESCE(orders.item_id,''), COALESCE(item_info.item_title, ''),
|
||||
COALESCE(item_info.item_detail, ''), COALESCE(orders.buyer_id,''), COALESCE(orders.quantity, '1'),
|
||||
orders.amount, COALESCE(orders.order_status,'unknown'), COALESCE(orders.cookie_id,''), orders.created_at
|
||||
FROM orders
|
||||
LEFT JOIN item_info ON item_info.cookie_id = orders.cookie_id AND item_info.item_id = orders.item_id
|
||||
`+where+amountFilter+` ORDER BY orders.created_at DESC LIMIT ? OFFSET ?`, queryParams...)
|
||||
// result 和 err 是订单分析应用服务返回的分页结果。
|
||||
result, err := s.analyticsApplication().ValidOrders(r.Context(), analyticsQuery{
|
||||
Where: where, Params: analyticsQueryParamsCopy(params), AmountClean: amountClean, AmountFilter: amountFilter,
|
||||
}, page, pageSize)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
writeErr(w, http.StatusInternalServerError, analyticsErrorMessage(err))
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []validOrderResponse{}
|
||||
for rows.Next() {
|
||||
var orderID, itemID, itemTitle, itemDetail, buyerID, quantity, amount, status, cookieID, createdAt string
|
||||
if rows.Scan(&orderID, &itemID, &itemTitle, &itemDetail, &buyerID, &quantity, &amount, &status, &cookieID, &createdAt) == nil {
|
||||
status = db.NormalizeOrderStatus(status)
|
||||
out = append(out, validOrderResponse{
|
||||
OrderID: orderID, ItemID: itemID, BuyerID: buyerID,
|
||||
ItemTitle: itemTitle, ItemImage: itemImageFromDetail(itemDetail),
|
||||
Quantity: quantity, Amount: amount, OrderStatus: status,
|
||||
Status: status, CookieID: cookieID, CreatedAt: createdAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, validOrdersResponse{
|
||||
Orders: out, Total: total, Page: page, PageSize: pageSize,
|
||||
Truncated: offset+len(out) < total,
|
||||
})
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// buildAnalyticsWhere 构建 WHERE 子句(user_id 经 cookies 关联过滤 + 日期 + 状态)。
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// analyticsQuery 描述订单分析查询已经归一化的数据库过滤条件。
|
||||
type analyticsQuery struct {
|
||||
// Where 是包含 WHERE 前缀的订单过滤子句。
|
||||
Where string
|
||||
// Params 是 Where 对应的数据库参数。
|
||||
Params []any
|
||||
// AmountClean 是按数据库方言生成的金额表达式。
|
||||
AmountClean string
|
||||
// AmountFilter 是排除非法金额后的附加条件。
|
||||
AmountFilter string
|
||||
// Location 是用户选择的本地时区。
|
||||
Location *time.Location
|
||||
}
|
||||
|
||||
// analyticsStage 标识订单分析失败的查询阶段。
|
||||
type analyticsStage string
|
||||
|
||||
const (
|
||||
// analyticsStageRevenue 表示收益汇总查询失败。
|
||||
analyticsStageRevenue analyticsStage = "revenue"
|
||||
// analyticsStageDaily 表示每日统计查询失败。
|
||||
analyticsStageDaily analyticsStage = "daily"
|
||||
// analyticsStageStatus 表示状态统计查询失败。
|
||||
analyticsStageStatus analyticsStage = "status"
|
||||
// analyticsStageCity 表示城市统计查询失败。
|
||||
analyticsStageCity analyticsStage = "city"
|
||||
// analyticsStageItem 表示商品统计查询失败。
|
||||
analyticsStageItem analyticsStage = "item"
|
||||
// analyticsStageValidCount 表示有效订单总数查询失败。
|
||||
analyticsStageValidCount analyticsStage = "valid_count"
|
||||
// analyticsStageValidRows 表示有效订单明细查询失败。
|
||||
analyticsStageValidRows analyticsStage = "valid_rows"
|
||||
)
|
||||
|
||||
// analyticsServiceError 保留订单分析失败阶段,供 HTTP 层映射兼容错误消息。
|
||||
type analyticsServiceError struct {
|
||||
// stage 是失败的查询阶段。
|
||||
stage analyticsStage
|
||||
// err 是底层数据库错误。
|
||||
err error
|
||||
}
|
||||
|
||||
// Error 返回订单分析错误文本。
|
||||
func (e *analyticsServiceError) Error() string { return e.err.Error() }
|
||||
|
||||
// Unwrap 暴露底层数据库错误。
|
||||
func (e *analyticsServiceError) Unwrap() error { return e.err }
|
||||
|
||||
// analyticsService 承载订单分析的数据库编排,不依赖 HTTP 请求或响应对象。
|
||||
type analyticsService struct {
|
||||
// server 提供订单仓储和数据库方言依赖。
|
||||
server *Server
|
||||
}
|
||||
|
||||
// DashboardStats 查询当前用户的数据概览和可用卡密库存。
|
||||
func (svc *analyticsService) DashboardStats(ctx context.Context, userID int64) (dashboardStatsResponse, error) {
|
||||
// s 是当前订单分析应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// counts 保存仪表盘各项计数。
|
||||
counts := map[string]int64{"total_cookies": 0, "active_cookies": 0, "total_cards": 0, "available_card_stock": 0, "total_keywords": 0, "total_orders": 0}
|
||||
// queries 保存用户范围内的固定统计查询。
|
||||
queries := []struct {
|
||||
query string
|
||||
key string
|
||||
}{
|
||||
{`SELECT COUNT(*) FROM cookies WHERE user_id=?`, "total_cookies"},
|
||||
{`SELECT COUNT(*) FROM cards WHERE user_id=?`, "total_cards"},
|
||||
{`SELECT COUNT(*) FROM keywords k WHERE EXISTS (SELECT 1 FROM cookies c WHERE c.id=k.cookie_id AND c.user_id=?)`, "total_keywords"},
|
||||
{`SELECT COUNT(*) FROM orders o WHERE o.deleted_at IS NULL AND EXISTS (SELECT 1 FROM cookies c WHERE c.id=o.cookie_id AND c.user_id=?)`, "total_orders"},
|
||||
}
|
||||
// item 是当前固定统计查询。
|
||||
for _, item := range queries {
|
||||
// count 是当前统计项的数据库结果。
|
||||
var count int64
|
||||
// err 是当前统计项查询错误。
|
||||
if err := s.Store.Analytics.QueryRowContext(ctx, item.query, userID).Scan(&count); err != nil {
|
||||
return dashboardStatsResponse{}, err
|
||||
}
|
||||
counts[item.key] = count
|
||||
}
|
||||
// activeCookies 是没有明确禁用记录的账号数量。
|
||||
var activeCookies int64
|
||||
// err 是活跃账号统计查询错误。
|
||||
if err := s.Store.Analytics.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM cookies c WHERE c.user_id=?
|
||||
AND NOT EXISTS (SELECT 1 FROM cookie_status cs WHERE cs.cookie_id=c.id AND cs.enabled=0)
|
||||
`, userID).Scan(&activeCookies); err != nil {
|
||||
return dashboardStatsResponse{}, err
|
||||
}
|
||||
counts["active_cookies"] = activeCookies
|
||||
// cards 和 err 是当前用户的卡密组列表及查询错误。
|
||||
cards, err := s.Store.Cards.AllForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return dashboardStatsResponse{}, err
|
||||
}
|
||||
// card 是当前遍历到的卡密组。
|
||||
for _, card := range cards {
|
||||
if !card.Enabled || card.Type != "data" {
|
||||
continue
|
||||
}
|
||||
// line 是卡密组内容中的一行卡密。
|
||||
for _, line := range strings.Split(strings.ReplaceAll(card.DataContent, "\r\n", "\n"), "\n") {
|
||||
if strings.TrimSpace(line) != "" {
|
||||
counts["available_card_stock"]++
|
||||
}
|
||||
}
|
||||
}
|
||||
return dashboardStatsResponse{TotalCookies: counts["total_cookies"], ActiveCookies: counts["active_cookies"], TotalCards: counts["total_cards"], AvailableCardStock: counts["available_card_stock"], TotalKeywords: counts["total_keywords"], TotalOrders: counts["total_orders"]}, nil
|
||||
}
|
||||
|
||||
// analyticsApplication 返回当前 Server 绑定的订单分析应用服务。
|
||||
func (s *Server) analyticsApplication() *analyticsService {
|
||||
return s.applicationServiceSet().analytics
|
||||
}
|
||||
|
||||
// OrderAnalytics 查询收益及按日、状态、城市和商品维度聚合的订单分析结果。
|
||||
func (svc *analyticsService) OrderAnalytics(ctx context.Context, query analyticsQuery) (orderAnalyticsResponse, error) {
|
||||
// s 是当前订单分析应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// amountFilter 是已经排除非法金额的查询条件。
|
||||
amountFilter := query.AmountFilter
|
||||
// revenue 保存订单收益汇总结果。
|
||||
var revenue analyticsRevenueStatsResponse
|
||||
// err 是收益汇总查询错误。
|
||||
if err := s.Store.Analytics.QueryRowContext(ctx, `
|
||||
SELECT COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0),
|
||||
COALESCE(AVG(`+query.AmountClean+`),0), COUNT(DISTINCT buyer_id), COUNT(DISTINCT item_id)
|
||||
FROM orders `+query.Where+amountFilter, query.Params...).Scan(
|
||||
&revenue.TotalOrders, &revenue.TotalAmount, &revenue.AvgAmount, &revenue.UniqueBuyers, &revenue.UniqueItems); err != nil {
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageRevenue, err: err}
|
||||
}
|
||||
|
||||
// daily 保存按用户本地日期聚合的统计结果。
|
||||
daily := make([]analyticsDailyStatsResponse, 0)
|
||||
// rows 和 err 是每日统计查询结果集及错误。
|
||||
rows, err := s.Store.Analytics.QueryContext(ctx, `
|
||||
SELECT order_id,amount,created_at FROM orders `+query.Where+amountFilter, query.Params...)
|
||||
if err != nil {
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageDaily, err: err}
|
||||
}
|
||||
// dailyValue 保存同一天的订单数和金额累计值。
|
||||
type dailyValue struct {
|
||||
count int
|
||||
amount float64
|
||||
}
|
||||
// dailyMap 按日期聚合订单数据,避免依赖数据库方言的日期函数。
|
||||
dailyMap := map[string]dailyValue{}
|
||||
for rows.Next() {
|
||||
// orderID、amountRaw 和 createdAt 是当前订单的原始字段。
|
||||
var orderID, amountRaw, createdAt string
|
||||
if rows.Scan(&orderID, &amountRaw, &createdAt) != nil {
|
||||
continue
|
||||
}
|
||||
// created 是转换后的订单创建时间。
|
||||
created := parseAnalyticsDBTime(createdAt)
|
||||
if created.IsZero() {
|
||||
continue
|
||||
}
|
||||
// date 是订单在用户时区中的日期。
|
||||
if query.Location != nil {
|
||||
created = created.In(query.Location)
|
||||
}
|
||||
// date 是订单在用户时区中的日期。
|
||||
date := created.Format("2006-01-02")
|
||||
// value 是当前日期的累计统计值。
|
||||
value := dailyMap[date]
|
||||
value.count++
|
||||
value.amount += parseAnalyticsAmount(amountRaw)
|
||||
dailyMap[date] = value
|
||||
}
|
||||
// err 是每日统计游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageDaily, err: err}
|
||||
}
|
||||
_ = rows.Close()
|
||||
// dates 是排序后的日期列表。
|
||||
dates := make([]string, 0, len(dailyMap))
|
||||
// date 是当前待排序的日期。
|
||||
for date := range dailyMap {
|
||||
dates = append(dates, date)
|
||||
}
|
||||
sort.Strings(dates)
|
||||
// date 是当前输出日期。
|
||||
for _, date := range dates {
|
||||
// value 是当前日期的累计统计值。
|
||||
value := dailyMap[date]
|
||||
daily = append(daily, analyticsDailyStatsResponse{Date: date, OrderCount: value.count, Amount: round2(value.amount)})
|
||||
}
|
||||
|
||||
// statusStats 保存按订单状态聚合的结果。
|
||||
statusStats := make([]analyticsStatusStatsResponse, 0)
|
||||
// statusValue 保存单个状态的累计统计值。
|
||||
type statusValue struct {
|
||||
count int
|
||||
amount float64
|
||||
}
|
||||
// statusMap 按归一化状态聚合订单数据。
|
||||
statusMap := map[string]statusValue{}
|
||||
// rows 和 err 是状态统计查询结果集及错误。
|
||||
rows, err = s.Store.Analytics.QueryContext(ctx, `
|
||||
SELECT COALESCE(order_status,'unknown'), COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0)
|
||||
FROM orders `+query.Where+amountFilter+`
|
||||
GROUP BY order_status ORDER BY COUNT(DISTINCT order_id) DESC`, query.Params...)
|
||||
if err != nil {
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageStatus, err: err}
|
||||
}
|
||||
for rows.Next() {
|
||||
// status、count 和 amount 是当前状态的数据库聚合值。
|
||||
var status string
|
||||
// count 和 amount 是当前状态的订单数和金额。
|
||||
var count int
|
||||
// amount 是当前状态的订单金额。
|
||||
var amount float64
|
||||
if rows.Scan(&status, &count, &amount) == nil {
|
||||
status = db.NormalizeOrderStatus(status)
|
||||
// value 是当前状态的累计统计值。
|
||||
value := statusMap[status]
|
||||
value.count += count
|
||||
value.amount += amount
|
||||
statusMap[status] = value
|
||||
}
|
||||
}
|
||||
// err 是状态统计游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageStatus, err: err}
|
||||
}
|
||||
_ = rows.Close()
|
||||
// statusNames 是按订单数量降序排列的状态名称。
|
||||
statusNames := make([]string, 0, len(statusMap))
|
||||
// status 是当前待排序的状态名称。
|
||||
for status := range statusMap {
|
||||
statusNames = append(statusNames, status)
|
||||
}
|
||||
sort.Slice(statusNames, func(i, j int) bool { return statusMap[statusNames[i]].count > statusMap[statusNames[j]].count })
|
||||
// status 是当前输出状态。
|
||||
for _, status := range statusNames {
|
||||
// value 是当前状态的累计统计值。
|
||||
value := statusMap[status]
|
||||
statusStats = append(statusStats, analyticsStatusStatsResponse{Status: status, Count: value.count, Amount: round2(value.amount)})
|
||||
}
|
||||
|
||||
// cityStats 保存按收货城市聚合的结果。
|
||||
cityStats := make([]analyticsCityStatsResponse, 0)
|
||||
// rows 和 err 是城市统计查询结果集及错误。
|
||||
rows, err = s.Store.Analytics.QueryContext(ctx, `
|
||||
SELECT receiver_city, COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0)
|
||||
FROM orders `+query.Where+amountFilter+`
|
||||
AND receiver_city IS NOT NULL AND receiver_city != ''
|
||||
GROUP BY receiver_city ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 50`, query.Params...)
|
||||
if err != nil {
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageCity, err: err}
|
||||
}
|
||||
for rows.Next() {
|
||||
// city、count 和 amount 是当前城市的数据库聚合值。
|
||||
var city string
|
||||
// count 和 amount 是当前城市的订单数和金额。
|
||||
var count int
|
||||
// amount 是当前城市的订单金额。
|
||||
var amount float64
|
||||
if rows.Scan(&city, &count, &amount) == nil {
|
||||
cityStats = append(cityStats, analyticsCityStatsResponse{City: city, OrderCount: count, TotalAmount: round2(amount)})
|
||||
}
|
||||
}
|
||||
// err 是城市统计游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageCity, err: err}
|
||||
}
|
||||
_ = rows.Close()
|
||||
|
||||
// itemStats 保存按商品标识聚合的排行结果。
|
||||
itemStats := make([]analyticsItemStatsResponse, 0)
|
||||
// rows 和 err 是商品统计查询结果集及错误。
|
||||
rows, err = s.Store.Analytics.QueryContext(ctx, `
|
||||
SELECT item_id, COUNT(DISTINCT order_id), COALESCE(SUM(`+query.AmountClean+`),0), COALESCE(AVG(`+query.AmountClean+`),0)
|
||||
FROM orders `+query.Where+amountFilter+`
|
||||
AND item_id IS NOT NULL AND item_id != ''
|
||||
GROUP BY item_id ORDER BY COUNT(DISTINCT order_id) DESC LIMIT 20`, query.Params...)
|
||||
if err != nil {
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageItem, err: err}
|
||||
}
|
||||
for rows.Next() {
|
||||
// itemID、count、total 和 average 是当前商品的数据库聚合值。
|
||||
var itemID string
|
||||
// count、total 和 average 是当前商品的订单数、总金额和平均金额。
|
||||
var count int
|
||||
// total 和 average 是当前商品的总金额和平均金额。
|
||||
var total, average float64
|
||||
if rows.Scan(&itemID, &count, &total, &average) == nil {
|
||||
itemStats = append(itemStats, analyticsItemStatsResponse{ItemID: itemID, OrderCount: count, TotalAmount: round2(total), AvgAmount: round2(average)})
|
||||
}
|
||||
}
|
||||
// err 是商品统计游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return orderAnalyticsResponse{}, &analyticsServiceError{stage: analyticsStageItem, err: err}
|
||||
}
|
||||
_ = rows.Close()
|
||||
return orderAnalyticsResponse{
|
||||
RevenueStats: analyticsRevenueStatsResponse{
|
||||
TotalOrders: revenue.TotalOrders, TotalAmount: round2(revenue.TotalAmount), AvgAmount: round2(revenue.AvgAmount),
|
||||
UniqueBuyers: revenue.UniqueBuyers, UniqueItems: revenue.UniqueItems,
|
||||
},
|
||||
DailyStats: daily, StatusStats: statusStats, CityStats: cityStats, ItemStats: itemStats,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidOrders 查询有效订单分页明细。
|
||||
func (svc *analyticsService) ValidOrders(ctx context.Context, query analyticsQuery, page, pageSize int) (validOrdersResponse, error) {
|
||||
// s 是当前订单分析应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// amountFilter 是已经排除非法金额的查询条件。
|
||||
amountFilter := query.AmountFilter
|
||||
// total 是符合筛选条件的订单总数。
|
||||
var total int
|
||||
// err 是有效订单总数查询错误。
|
||||
if err := s.Store.Analytics.QueryRowContext(ctx, `SELECT COUNT(*) FROM orders `+query.Where+amountFilter, query.Params...).Scan(&total); err != nil {
|
||||
return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidCount, err: err}
|
||||
}
|
||||
// queryParams 是分页查询附加的 LIMIT/OFFSET 参数。
|
||||
queryParams := append(append([]any{}, query.Params...), pageSize, (page-1)*pageSize)
|
||||
// rows 和 err 是有效订单明细查询结果集及错误。
|
||||
rows, err := s.Store.Analytics.QueryContext(ctx, `
|
||||
SELECT orders.order_id, COALESCE(orders.item_id,''), COALESCE(item_info.item_title,''),
|
||||
COALESCE(item_info.item_detail,''), COALESCE(orders.buyer_id,''), COALESCE(orders.quantity,'1'),
|
||||
orders.amount, COALESCE(orders.order_status,'unknown'), COALESCE(orders.cookie_id,''), orders.created_at
|
||||
FROM orders LEFT JOIN item_info ON item_info.cookie_id=orders.cookie_id AND item_info.item_id=orders.item_id
|
||||
`+query.Where+amountFilter+` ORDER BY orders.created_at DESC LIMIT ? OFFSET ?`, queryParams...)
|
||||
if err != nil {
|
||||
return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidRows, err: err}
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 是有效订单响应列表。
|
||||
out := make([]validOrderResponse, 0)
|
||||
for rows.Next() {
|
||||
// orderID、itemID、itemTitle、itemDetail、buyerID、quantity、amount、status、cookieID 和 createdAt 是订单字段。
|
||||
var orderID, itemID, itemTitle, itemDetail, buyerID, quantity, amount, status, cookieID, createdAt string
|
||||
if rows.Scan(&orderID, &itemID, &itemTitle, &itemDetail, &buyerID, &quantity, &amount, &status, &cookieID, &createdAt) == nil {
|
||||
status = db.NormalizeOrderStatus(status)
|
||||
out = append(out, validOrderResponse{OrderID: orderID, ItemID: itemID, BuyerID: buyerID, ItemTitle: itemTitle, ItemImage: itemImageFromDetail(itemDetail), Quantity: quantity, Amount: amount, OrderStatus: status, Status: status, CookieID: cookieID, CreatedAt: createdAt})
|
||||
}
|
||||
}
|
||||
// err 是有效订单游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return validOrdersResponse{}, &analyticsServiceError{stage: analyticsStageValidRows, err: err}
|
||||
}
|
||||
return validOrdersResponse{Orders: out, Total: total, Page: page, PageSize: pageSize, Truncated: (page-1)*pageSize+len(out) < total}, nil
|
||||
}
|
||||
|
||||
// analyticsStageOf 读取分析服务错误阶段。
|
||||
func analyticsStageOf(err error) (analyticsStage, bool) {
|
||||
// serviceErr 是带查询阶段的应用服务错误。
|
||||
var serviceErr *analyticsServiceError
|
||||
if !errors.As(err, &serviceErr) {
|
||||
return "", false
|
||||
}
|
||||
return serviceErr.stage, true
|
||||
}
|
||||
|
||||
// analyticsErrorMessage 将分析服务阶段映射为原有 HTTP 错误消息。
|
||||
func analyticsErrorMessage(err error) string {
|
||||
// stage 是应用服务错误对应的查询阶段。
|
||||
switch stage, _ := analyticsStageOf(err); stage {
|
||||
case analyticsStageRevenue:
|
||||
return "查询收益统计失败"
|
||||
case analyticsStageDaily:
|
||||
return "查询每日统计失败"
|
||||
case analyticsStageStatus:
|
||||
return "查询状态统计失败"
|
||||
case analyticsStageCity:
|
||||
return "查询城市统计失败"
|
||||
case analyticsStageItem:
|
||||
return "查询商品统计失败"
|
||||
default:
|
||||
return "查询失败"
|
||||
}
|
||||
}
|
||||
|
||||
// analyticsQueryAmountFilter 根据订单分析查询构造金额过滤条件。
|
||||
func analyticsQueryAmountFilter(store *db.Store, column string) (string, string) {
|
||||
// clean 是按数据库方言清洗后的金额表达式。
|
||||
clean := analyticsAmountExpression(store.Dialect, column)
|
||||
return clean, " AND " + clean + " IS NOT NULL"
|
||||
}
|
||||
|
||||
// analyticsQueryParamsCopy 复制查询参数,避免服务层修改 handler 持有的切片。
|
||||
func analyticsQueryParamsCopy(params []any) []any {
|
||||
return append([]any(nil), params...)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package server
|
||||
|
||||
// applicationServices 聚合 Server 使用的应用服务实例,统一管理共享基础设施依赖。
|
||||
type applicationServices struct {
|
||||
// orders 是订单应用服务。
|
||||
orders *orderApplicationService
|
||||
// itemPublish 是商品发布应用服务。
|
||||
itemPublish *itemPublishService
|
||||
// accountLogin 是账号登录应用服务。
|
||||
accountLogin *accountLoginService
|
||||
// communication 是聊天、通知和账号任务应用服务。
|
||||
communication *communicationService
|
||||
// analytics 是订单分析应用服务。
|
||||
analytics *analyticsService
|
||||
}
|
||||
|
||||
// newApplicationServices 为指定 Server 装配全部应用服务实例。
|
||||
func newApplicationServices(server *Server) *applicationServices {
|
||||
return &applicationServices{
|
||||
orders: &orderApplicationService{server: server},
|
||||
itemPublish: &itemPublishService{server: server},
|
||||
accountLogin: &accountLoginService{server: server},
|
||||
communication: &communicationService{server: server},
|
||||
analytics: &analyticsService{server: server},
|
||||
}
|
||||
}
|
||||
|
||||
// applicationServiceSet 返回当前 Server 的应用服务集合,并兼容测试 Server。
|
||||
func (s *Server) applicationServiceSet() *applicationServices {
|
||||
if s.applications != nil {
|
||||
return s.applications
|
||||
}
|
||||
return newApplicationServices(s)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package server
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestNewServerAssemblesApplicationServices 验证 Server 构造时统一装配全部应用服务。
|
||||
func TestNewServerAssemblesApplicationServices(t *testing.T) {
|
||||
// srv 是使用测试依赖创建的 Server。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
if srv.applications == nil {
|
||||
t.Fatal("Server 应在构造时装配应用服务集合")
|
||||
}
|
||||
// services 是统一应用服务集合。
|
||||
services := srv.applicationServiceSet()
|
||||
if services.orders == nil || services.itemPublish == nil || services.accountLogin == nil || services.communication == nil || services.analytics == nil {
|
||||
t.Fatal("应用服务集合存在未装配的服务")
|
||||
}
|
||||
if srv.orders() != services.orders || srv.itemPublishApplication() != services.itemPublish || srv.accountLoginApplication() != services.accountLogin || srv.communicationApplication() != services.communication || srv.analyticsApplication() != services.analytics {
|
||||
t.Fatal("应用服务访问器未返回统一装配实例")
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ type notificationBindingRow struct {
|
||||
|
||||
// communicationApplication 返回当前 Server 绑定的通信应用服务。
|
||||
func (s *Server) communicationApplication() *communicationService {
|
||||
return &communicationService{server: s}
|
||||
return s.applicationServiceSet().communication
|
||||
}
|
||||
|
||||
// GetAccountTaskSettings 读取指定账号的任务设置。
|
||||
@@ -180,31 +180,18 @@ func (svc *communicationService) TestNotificationChannel(ctx context.Context, ch
|
||||
// ListNotificationBindings 查询用户账号的通知绑定。
|
||||
func (svc *communicationService) ListNotificationBindings(ctx context.Context, userID int64) (map[string][]notificationBindingRow, error) {
|
||||
// rows 和 err 保存绑定查询结果集。
|
||||
rows, err := svc.server.Store.DB.QueryContext(ctx, `
|
||||
SELECT mn.id, mn.cookie_id, mn.channel_id, COALESCE(nc.name, ''), mn.enabled
|
||||
FROM message_notifications mn
|
||||
JOIN cookies c ON c.id=mn.cookie_id
|
||||
JOIN notification_channels nc ON nc.id=mn.channel_id AND nc.user_id=c.user_id
|
||||
WHERE c.user_id=? ORDER BY mn.id DESC`, userID)
|
||||
rows, err := svc.server.Store.Notifications.ListBindingsForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
// result 是按账号分组的通知绑定列表。
|
||||
result := make(map[string][]notificationBindingRow)
|
||||
for rows.Next() {
|
||||
for _, row := range rows {
|
||||
// binding 保存当前扫描到的通知绑定记录。
|
||||
var binding notificationBindingRow
|
||||
// enabled 保存数据库中的整数布尔值。
|
||||
var enabled int
|
||||
// err 表示当前绑定行扫描错误。
|
||||
if err := rows.Scan(&binding.ID, &binding.CookieID, &binding.ChannelID, &binding.ChannelName, &enabled); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
binding.Enabled = enabled != 0
|
||||
binding := notificationBindingRow{ID: row.ID, CookieID: row.CookieID, ChannelID: row.ChannelID, ChannelName: row.ChannelName, Enabled: row.Enabled}
|
||||
result[binding.CookieID] = append(result[binding.CookieID], binding)
|
||||
}
|
||||
return result, rows.Err()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SetNotificationBindings 覆盖保存账号的通知渠道绑定。
|
||||
@@ -220,32 +207,19 @@ func (svc *communicationService) GetNotificationBindingIDs(ctx context.Context,
|
||||
// SetSingleNotificationBinding 更新单个账号通知渠道的启用状态。
|
||||
func (svc *communicationService) SetSingleNotificationBinding(ctx context.Context, cookieID string, channelID int64, enabled bool) error {
|
||||
if !enabled {
|
||||
// err 表示删除单个通知绑定的错误。
|
||||
_, err := svc.server.Store.DB.ExecContext(ctx, `DELETE FROM message_notifications WHERE cookie_id=? AND channel_id=?`, cookieID, channelID)
|
||||
return err
|
||||
return svc.server.Store.Notifications.SetSingleBinding(ctx, cookieID, channelID, false)
|
||||
}
|
||||
// err 表示写入单个通知绑定的错误。
|
||||
_, err := svc.server.Store.DB.ExecContext(ctx,
|
||||
`INSERT INTO message_notifications (cookie_id, channel_id, enabled) VALUES (?, ?, ?)`+
|
||||
db.DialectUpsert(svc.server.Store.Dialect, []string{"cookie_id", "channel_id"}, map[string]string{"enabled": "EXCLUDED.enabled", "updated_at": "CURRENT_TIMESTAMP"}),
|
||||
cookieID, channelID, 1)
|
||||
return err
|
||||
return svc.server.Store.Notifications.SetSingleBinding(ctx, cookieID, channelID, true)
|
||||
}
|
||||
|
||||
// DeleteNotificationBinding 删除用户账号下的一条通知绑定。
|
||||
func (svc *communicationService) DeleteNotificationBinding(ctx context.Context, userID, bindingID int64) error {
|
||||
// err 表示删除指定通知绑定的错误。
|
||||
_, err := svc.server.Store.DB.ExecContext(ctx, `
|
||||
DELETE FROM message_notifications WHERE id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, bindingID, userID)
|
||||
return err
|
||||
return svc.server.Store.Notifications.DeleteBinding(ctx, userID, bindingID)
|
||||
}
|
||||
|
||||
// DeleteAccountNotificationBindings 删除用户账号的全部通知绑定。
|
||||
func (svc *communicationService) DeleteAccountNotificationBindings(ctx context.Context, userID int64, cookieID string) error {
|
||||
// err 表示删除账号通知绑定的错误。
|
||||
_, err := svc.server.Store.DB.ExecContext(ctx, `
|
||||
DELETE FROM message_notifications WHERE cookie_id=? AND cookie_id IN (SELECT id FROM cookies WHERE user_id=?)`, cookieID, userID)
|
||||
return err
|
||||
return svc.server.Store.Notifications.DeleteAccountBindings(ctx, userID, cookieID)
|
||||
}
|
||||
|
||||
// SendChatText 创建并发送一条文字消息,失败时保留可重试的本地失败状态。
|
||||
|
||||
@@ -656,12 +656,11 @@ func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
v := 0
|
||||
if req.AutoConfirm {
|
||||
v = 1
|
||||
}
|
||||
if _, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`UPDATE cookies SET auto_confirm=? WHERE id=?`, v, cid); err != nil {
|
||||
// sess 是当前请求的认证会话,用于让 repository 再次确认账号归属。
|
||||
sess := authSess(r)
|
||||
if _, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{
|
||||
UserID: sess.UserID, AutoConfirm: &req.AutoConfirm,
|
||||
}); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存自动确认设置失败")
|
||||
return
|
||||
}
|
||||
@@ -691,8 +690,11 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if _, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`UPDATE cookies SET remark=? WHERE id=?`, req.Remark, cid); err != nil {
|
||||
// sess 是当前请求的认证会话,用于让 repository 再次确认账号归属。
|
||||
sess := authSess(r)
|
||||
if _, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, db.AccountSettingsUpdate{
|
||||
UserID: sess.UserID, Remark: &req.Remark,
|
||||
}); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存账号备注失败")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -72,16 +72,10 @@ func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
// err 是默认回复写入错误。
|
||||
_, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`INSERT INTO default_replies (cookie_id, enabled, reply_content, reply_image_url, reply_once, updated_at)
|
||||
VALUES (?,?,?,?,?,CURRENT_TIMESTAMP)`+db.DialectUpsert(s.Store.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
"enabled": "EXCLUDED.enabled",
|
||||
"reply_content": "EXCLUDED.reply_content",
|
||||
"reply_image_url": "EXCLUDED.reply_image_url",
|
||||
"reply_once": "EXCLUDED.reply_once",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cid, btoi(req.Enabled), req.ReplyContent, nullIfEmpty(req.ReplyImageURL), btoi(req.ReplyOnce))
|
||||
err := s.Store.DefaultReps.Upsert(r.Context(), cid, db.DefaultReply{
|
||||
Enabled: req.Enabled, ReplyContent: req.ReplyContent,
|
||||
ReplyImageURL: req.ReplyImageURL, ReplyOnce: req.ReplyOnce,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
@@ -93,39 +87,21 @@ func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 是当前登录用户会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// err 是默认回复列表查询错误,rows 是查询结果游标。
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT dr.cookie_id, dr.enabled, COALESCE(dr.reply_content,''), dr.reply_once, COALESCE(dr.reply_image_url,'')
|
||||
FROM default_replies dr
|
||||
JOIN cookies c ON c.id=dr.cookie_id
|
||||
WHERE c.user_id=?`, sess.UserID)
|
||||
// rows 和 err 是当前用户的默认回复列表及查询错误。
|
||||
rows, err := s.Store.DefaultReps.ListForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 是默认回复列表响应。
|
||||
var out []defaultReplyResponse
|
||||
for rows.Next() {
|
||||
// cid、content 和 imageURL 是当前默认回复的文本字段。
|
||||
var cid, content, imageURL string
|
||||
// enabled 和 replyOnce 是数据库中的布尔数值字段。
|
||||
var enabled, replyOnce int
|
||||
// err 是当前默认回复行扫描错误。
|
||||
if err := rows.Scan(&cid, &enabled, &content, &replyOnce, &imageURL); err != nil {
|
||||
continue
|
||||
}
|
||||
for _, row := range rows {
|
||||
out = append(out, defaultReplyResponse{
|
||||
CookieID: cid, Enabled: enabled != 0, ReplyContent: content, ReplyOnce: replyOnce != 0,
|
||||
ReplyImageURL: imageURL,
|
||||
CookieID: row.CookieID, Enabled: row.Enabled, ReplyContent: row.ReplyContent, ReplyOnce: row.ReplyOnce,
|
||||
ReplyImageURL: row.ReplyImageURL,
|
||||
// 列表 DTO 保留账号标识,前端可直接建立按账号索引。
|
||||
})
|
||||
}
|
||||
// err 是默认回复游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
@@ -133,42 +109,24 @@ func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 是当前登录用户会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// err 是默认回复映射查询错误,rows 是查询结果游标。
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT dr.cookie_id, dr.enabled, COALESCE(dr.reply_content, ''), dr.reply_once, COALESCE(dr.reply_image_url, '')
|
||||
FROM default_replies dr
|
||||
JOIN cookies c ON c.id=dr.cookie_id
|
||||
WHERE c.user_id=?`, sess.UserID)
|
||||
// rows 和 err 是当前用户的默认回复列表及查询错误。
|
||||
rows, err := s.Store.DefaultReps.ListForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
// out 是按账号标识索引的默认回复映射。
|
||||
out := make(map[string]defaultReplyResponse)
|
||||
for rows.Next() {
|
||||
// cid、content 和 imageURL 是当前默认回复的文本字段。
|
||||
var cid, content, imageURL string
|
||||
// enabled 和 replyOnce 是数据库中的布尔数值字段。
|
||||
var enabled, replyOnce int
|
||||
// err 是当前默认回复行扫描错误。
|
||||
if err := rows.Scan(&cid, &enabled, &content, &replyOnce, &imageURL); err != nil {
|
||||
continue
|
||||
}
|
||||
out[cid] = defaultReplyResponse{
|
||||
CookieID: cid,
|
||||
Enabled: enabled != 0,
|
||||
ReplyContent: content,
|
||||
ReplyOnce: replyOnce != 0,
|
||||
ReplyImageURL: imageURL,
|
||||
for _, row := range rows {
|
||||
out[row.CookieID] = defaultReplyResponse{
|
||||
CookieID: row.CookieID,
|
||||
Enabled: row.Enabled,
|
||||
ReplyContent: row.ReplyContent,
|
||||
ReplyOnce: row.ReplyOnce,
|
||||
ReplyImageURL: row.ReplyImageURL,
|
||||
// map 键与 cookie_id 同时保留,兼容旧前端索引方式。
|
||||
}
|
||||
}
|
||||
// err 是默认回复映射游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
@@ -180,7 +138,7 @@ func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
// err 是默认回复删除错误。
|
||||
_, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_replies WHERE cookie_id=?`, cid)
|
||||
err := s.Store.DefaultReps.Delete(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
@@ -196,7 +154,7 @@ func (s *Server) clearDefaultReplyRecords(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
// err 是默认回复记录清理错误。
|
||||
if _, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_reply_records WHERE cookie_id=?`, cid); err != nil {
|
||||
if err := s.Store.DefaultReps.ClearRecords(r.Context(), cid); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "清空失败")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1064,11 +1064,7 @@ func (s *Server) createPublishAutomationRules(ctx context.Context, userID int64,
|
||||
}
|
||||
|
||||
func (s *Server) ensurePublishAutomationRule(ctx context.Context, input db.AutomationRuleInput) error {
|
||||
var exists bool
|
||||
err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS(
|
||||
SELECT 1 FROM automation_rules
|
||||
WHERE user_id=? AND cookie_id=? AND item_id=? AND trigger_type=? AND name=? AND deleted_at IS NULL
|
||||
)`, input.UserID, input.CookieID, input.ItemID, input.TriggerType, input.Name).Scan(&exists)
|
||||
exists, err := s.Store.Automation.ExistsPublishRule(ctx, input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1364,10 +1360,8 @@ func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID
|
||||
|
||||
// cardOwnedByUser 判断指定卡券组是否属于用户。
|
||||
func (s *Server) cardOwnedByUser(ctx context.Context, userID int64, cardID int64) bool {
|
||||
// exists 表示数据库中是否存在匹配用户和卡券组 ID 的记录。
|
||||
var exists bool
|
||||
// err 表示卡券组所有权查询失败的原因。
|
||||
err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, cardID, userID).Scan(&exists)
|
||||
// exists 和 err 表示卡券组所有权查询结果及错误。
|
||||
exists, err := s.Store.Cards.ExistsOwned(ctx, cardID, userID)
|
||||
return err == nil && exists
|
||||
}
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ type itemPublishService struct {
|
||||
|
||||
// itemPublishApplication 返回当前 Server 绑定的商品发布应用服务。
|
||||
func (s *Server) itemPublishApplication() *itemPublishService {
|
||||
return &itemPublishService{server: s}
|
||||
return s.applicationServiceSet().itemPublish
|
||||
}
|
||||
|
||||
// PublishSingle 执行单商品发布、响应 Cookie 持久化和本地商品落库。
|
||||
|
||||
@@ -61,7 +61,7 @@ func orderErrorKindOf(err error) (orderErrorKind, bool) {
|
||||
|
||||
// orders 返回当前 Server 绑定的订单应用服务。
|
||||
func (s *Server) orders() *orderApplicationService {
|
||||
return &orderApplicationService{server: s}
|
||||
return s.applicationServiceSet().orders
|
||||
}
|
||||
|
||||
// orderListQuery 描述订单列表的业务查询条件。
|
||||
|
||||
@@ -100,12 +100,8 @@ func (s *Server) requireChannelOwner(w http.ResponseWriter, r *http.Request, cha
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return false
|
||||
}
|
||||
// exists 表示通知渠道是否由当前用户拥有。
|
||||
var exists bool
|
||||
// err 表示通知渠道所有权查询失败的原因。
|
||||
err := s.Store.DB.QueryRowContext(r.Context(),
|
||||
`SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`,
|
||||
channelID, sess.UserID).Scan(&exists)
|
||||
// exists 和 err 表示通知渠道归属查询结果及错误。
|
||||
exists, err := s.Store.Notifications.OwnsChannel(r.Context(), channelID, sess.UserID)
|
||||
if err != nil || !exists {
|
||||
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
|
||||
return false
|
||||
|
||||
@@ -69,6 +69,8 @@ type Server struct {
|
||||
Logger *slog.Logger
|
||||
WebDir string // 前端静态资源目录(含 index.html)
|
||||
Addr string
|
||||
// applications 保存统一装配的应用服务实例。
|
||||
applications *applicationServices
|
||||
|
||||
publishMu sync.Mutex
|
||||
publishCancels map[string]publishBatchWorker
|
||||
@@ -99,7 +101,7 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
|
||||
logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
|
||||
}
|
||||
qrMgr := qrlogin.NewManager(logger)
|
||||
return &Server{
|
||||
server := &Server{
|
||||
Store: store,
|
||||
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
|
||||
Manager: manager,
|
||||
@@ -119,6 +121,8 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
|
||||
qrOwners: make(map[string]qrLoginOwner),
|
||||
loginLimiter: newLoginFailureLimiter(),
|
||||
}
|
||||
server.applications = newApplicationServices(server)
|
||||
return server
|
||||
}
|
||||
|
||||
// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。
|
||||
|
||||
@@ -117,39 +117,22 @@ func (s *Server) mountAIReplyReal(r chi.Router) {
|
||||
|
||||
func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
sess := authSess(r)
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT a.cookie_id, a.ai_enabled, a.max_discount_percent, a.max_discount_amount,
|
||||
a.max_bargain_rounds, COALESCE(a.custom_prompts, '')
|
||||
FROM ai_reply_settings a
|
||||
JOIN cookies c ON c.id=a.cookie_id
|
||||
WHERE c.user_id=?`, sess.UserID)
|
||||
rows, err := s.Store.AIReply.ListForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string]aiReplySettingsResponse)
|
||||
for rows.Next() {
|
||||
var cookieID, customPrompts string
|
||||
var enabled, maxDiscountPercent, maxDiscountAmount, maxBargainRounds int
|
||||
if err := rows.Scan(&cookieID, &enabled, &maxDiscountPercent, &maxDiscountAmount, &maxBargainRounds, &customPrompts); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
result[cookieID] = aiReplySettingsResponse{
|
||||
CookieID: cookieID, AIEnabled: enabled != 0, MaxDiscountPercent: maxDiscountPercent,
|
||||
MaxDiscountAmount: maxDiscountAmount, MaxBargainRounds: maxBargainRounds, CustomPrompts: customPrompts,
|
||||
for _, row := range rows {
|
||||
result[row.CookieID] = aiReplySettingsResponse{
|
||||
CookieID: row.CookieID, AIEnabled: row.AIEnabled, MaxDiscountPercent: row.MaxDiscountPercent,
|
||||
MaxDiscountAmount: row.MaxDiscountAmount, MaxBargainRounds: row.MaxBargainRounds, CustomPrompts: row.CustomPrompts,
|
||||
// 账号标识和五项配置字段保持旧 JSON 名称。
|
||||
// 布尔值继续由数据库整数转换得到。
|
||||
// 自定义提示词不做额外格式化。
|
||||
// DTO 转换不改变查询失败处理。
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
@@ -211,20 +194,12 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "最大砍价轮次必须在 1 到 10 之间")
|
||||
return
|
||||
}
|
||||
_, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`INSERT INTO ai_reply_settings
|
||||
(cookie_id, ai_enabled, max_discount_percent, max_discount_amount,
|
||||
max_bargain_rounds, custom_prompts, updated_at)
|
||||
VALUES (?,?,?,?,?,?,CURRENT_TIMESTAMP)`+db.DialectUpsert(s.Store.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
"ai_enabled": "EXCLUDED.ai_enabled",
|
||||
"max_discount_percent": "EXCLUDED.max_discount_percent",
|
||||
"max_discount_amount": "EXCLUDED.max_discount_amount",
|
||||
"max_bargain_rounds": "EXCLUDED.max_bargain_rounds",
|
||||
"custom_prompts": "EXCLUDED.custom_prompts",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cid, btoi(req.AIEnabled), req.MaxDiscountPercent, req.MaxDiscountAmount,
|
||||
req.MaxBargainRounds, nullIfEmpty(req.CustomPrompts))
|
||||
// err 是 AI 回复配置写入错误。
|
||||
err := s.Store.AIReply.UpsertSettings(r.Context(), cid, db.AIReplySettings{
|
||||
AIEnabled: req.AIEnabled, MaxDiscountPercent: req.MaxDiscountPercent,
|
||||
MaxDiscountAmount: req.MaxDiscountAmount, MaxBargainRounds: req.MaxBargainRounds,
|
||||
CustomPrompts: req.CustomPrompts,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
@@ -379,35 +354,18 @@ func (s *Server) mountUserReal(r chi.Router) {
|
||||
|
||||
func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
|
||||
sess := authSess(r)
|
||||
keyCol := db.DialectQuote(s.Store.Dialect, "key")
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT `+keyCol+`, value FROM user_settings WHERE user_id=?`, sess.UserID)
|
||||
settings, err := s.Store.UserSettings.AllForUser(r.Context(), sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
m := make(map[string]string)
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if rows.Scan(&k, &v) == nil {
|
||||
m[k] = v
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, settingsResponse(m))
|
||||
writeJSON(w, http.StatusOK, settingsResponse(settings))
|
||||
}
|
||||
|
||||
func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
|
||||
sess := authSess(r)
|
||||
key := chi.URLParam(r, "key")
|
||||
var v string
|
||||
keyCol := db.DialectQuote(s.Store.Dialect, "key")
|
||||
err := s.Store.DB.QueryRowContext(r.Context(),
|
||||
`SELECT value FROM user_settings WHERE user_id=? AND `+keyCol+`=?`, sess.UserID, key).Scan(&v)
|
||||
v, err := s.Store.UserSettings.GetForUser(r.Context(), sess.UserID, key)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusOK, userSettingResponse{Value: ""})
|
||||
return
|
||||
@@ -425,14 +383,8 @@ func (s *Server) setUserSetting(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
keyCol := db.DialectQuote(s.Store.Dialect, "key")
|
||||
_, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`INSERT INTO user_settings (user_id, `+keyCol+`, value, updated_at) VALUES (?,?,?,CURRENT_TIMESTAMP)`+
|
||||
db.DialectUpsert(s.Store.Dialect, []string{"user_id", keyCol}, map[string]string{
|
||||
"value": "EXCLUDED.value",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
sess.UserID, key, req.Value)
|
||||
// err 是用户设置写入错误。
|
||||
err := s.Store.UserSettings.SetForUser(r.Context(), sess.UserID, key, req.Value)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user