feat(dashboard): #163 first summary
This commit was merged in pull request #181.
This commit is contained in:
88
internal/service/dashboard.go
Normal file
88
internal/service/dashboard.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/types"
|
||||
"time"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type Dashboard struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewDashboard(db *sqlx.DB) *Dashboard {
|
||||
return &Dashboard{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Dashboard) Summary(ctx context.Context, user *types.User, month time.Time) (*types.DashboardMonthlySummary, error) {
|
||||
if user == nil {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
var summary types.DashboardMonthlySummary
|
||||
|
||||
var value *int64
|
||||
err := s.db.GetContext(ctx, &value, `
|
||||
SELECT SUM(value)
|
||||
FROM "transaction"
|
||||
WHERE user_id = $1
|
||||
AND treasure_chest_id IS NOT NULL
|
||||
AND account_id IS NULL
|
||||
AND error IS NULL
|
||||
AND date(timestamp, 'start of month') = date($2, 'start of month')`,
|
||||
user.Id, month)
|
||||
err = db.TransformAndLogDbError("dashboard", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value != nil {
|
||||
summary.Savings = *value
|
||||
}
|
||||
|
||||
err = s.db.GetContext(ctx, &value, `
|
||||
SELECT SUM(value)
|
||||
FROM "transaction"
|
||||
WHERE user_id = $1
|
||||
AND account_id IS NOT NULL
|
||||
AND treasure_chest_id IS NULL
|
||||
AND error IS NULL
|
||||
AND date(timestamp, 'start of month') = date($2, 'start of month')`,
|
||||
user.Id, month)
|
||||
err = db.TransformAndLogDbError("dashboard", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value != nil {
|
||||
summary.Income = *value
|
||||
}
|
||||
|
||||
err = s.db.GetContext(ctx, &value, `
|
||||
SELECT SUM(value)
|
||||
FROM "transaction"
|
||||
WHERE user_id = $1
|
||||
AND account_id IS NOT NULL
|
||||
AND treasure_chest_id IS NOT NULL
|
||||
AND error IS NULL
|
||||
AND date(timestamp, 'start of month') = date($2, 'start of month')`,
|
||||
user.Id, month)
|
||||
err = db.TransformAndLogDbError("dashboard", nil, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if value != nil {
|
||||
summary.Expenses = *value
|
||||
}
|
||||
|
||||
summary.Total = summary.Income + summary.Expenses
|
||||
summary.Month = month
|
||||
|
||||
slog.Info("Dashboard summary", "summary", summary)
|
||||
|
||||
return &summary, nil
|
||||
}
|
||||
Reference in New Issue
Block a user