127 lines
3.7 KiB
Go
127 lines
3.7 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
"household-book/model"
|
|
)
|
|
|
|
type ReportService struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func NewReportService(db *sql.DB) *ReportService {
|
|
return &ReportService{db: db}
|
|
}
|
|
|
|
func (s *ReportService) CategoryRanking(ctx context.Context, year, month int, typ string, limit int) ([]model.CategoryRankingItem, error) {
|
|
if typ == "" {
|
|
typ = "expense"
|
|
}
|
|
if limit <= 0 {
|
|
limit = 10
|
|
}
|
|
|
|
// 百分比分母用当月该类型的全部金额,与 LIMIT 解耦:
|
|
// 否则当分类数 > limit 时,截断后的 top-N 之和会让百分比之和强行凑到 100%,与实际口径不符。
|
|
var monthTotal int64
|
|
if err := s.db.QueryRowContext(ctx,
|
|
`SELECT COALESCE(SUM(amount), 0) FROM transactions
|
|
WHERE type = ?
|
|
AND strftime('%Y', date) = printf('%04d', ?)
|
|
AND strftime('%m', date) = printf('%02d', ?)`,
|
|
typ, year, month,
|
|
).Scan(&monthTotal); err != nil {
|
|
return nil, fmt.Errorf("query month total: %w", err)
|
|
}
|
|
|
|
// 与预算看板一致:仅统计叶子分类(parent_id IS NOT NULL),避免父类与子类金额并列不可加。
|
|
rows, err := s.db.QueryContext(ctx, `SELECT c.id, c.name, c.is_active, COALESCE(SUM(t.amount), 0) AS amount
|
|
FROM transactions t
|
|
JOIN categories c ON c.id = t.category_id
|
|
WHERE t.type = ?
|
|
AND c.parent_id IS NOT NULL
|
|
AND strftime('%Y', t.date) = printf('%04d', ?)
|
|
AND strftime('%m', t.date) = printf('%02d', ?)
|
|
GROUP BY c.id, c.name, c.is_active
|
|
ORDER BY amount DESC
|
|
LIMIT ?`, typ, year, month, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("query category ranking: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var items []model.CategoryRankingItem
|
|
for rows.Next() {
|
|
var item model.CategoryRankingItem
|
|
var isActive int
|
|
if err := rows.Scan(&item.CategoryID, &item.CategoryName, &isActive, &item.Amount); err != nil {
|
|
return nil, fmt.Errorf("scan category ranking: %w", err)
|
|
}
|
|
item.CategoryIsActive = isActive == 1
|
|
items = append(items, item)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if items == nil {
|
|
items = []model.CategoryRankingItem{}
|
|
}
|
|
if monthTotal > 0 {
|
|
for i := range items {
|
|
items[i].Percent = float64(items[i].Amount) / float64(monthTotal) * 100
|
|
}
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
func (s *ReportService) Trend(ctx context.Context, year int) ([]model.TrendItem, error) {
|
|
rows, err := s.db.QueryContext(ctx, `WITH months(month) AS (
|
|
VALUES ('01'), ('02'), ('03'), ('04'), ('05'), ('06'), ('07'), ('08'), ('09'), ('10'), ('11'), ('12')
|
|
)
|
|
SELECT
|
|
printf('%04d-', ?) || months.month AS month,
|
|
COALESCE(SUM(CASE WHEN t.type = 'income' THEN t.amount ELSE 0 END), 0) AS income,
|
|
COALESCE(SUM(CASE WHEN t.type = 'expense' THEN t.amount ELSE 0 END), 0) AS expense
|
|
FROM months
|
|
LEFT JOIN transactions t
|
|
ON strftime('%Y', t.date) = printf('%04d', ?)
|
|
AND strftime('%m', t.date) = months.month
|
|
GROUP BY months.month
|
|
ORDER BY months.month`, year, year)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("query trend: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
items := make([]model.TrendItem, 0, 12)
|
|
for rows.Next() {
|
|
var item model.TrendItem
|
|
if err := rows.Scan(&item.Month, &item.Income, &item.Expense); err != nil {
|
|
return nil, fmt.Errorf("scan trend: %w", err)
|
|
}
|
|
item.Balance = item.Income - item.Expense
|
|
items = append(items, item)
|
|
}
|
|
return items, rows.Err()
|
|
}
|
|
|
|
func (s *ReportService) Overview(ctx context.Context, year, month int, typ string) (*model.ReportOverview, error) {
|
|
ranking, err := s.CategoryRanking(ctx, year, month, typ, 10)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
trend, err := s.Trend(ctx, year)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &model.ReportOverview{
|
|
Year: year,
|
|
Month: month,
|
|
CategoryRanking: ranking,
|
|
Trend: trend,
|
|
}, nil
|
|
}
|