Files
spend-sparrow/internal/service/dashboard.go
Tim Wundenberg 06a8c80f1d
All checks were successful
Build Docker Image / Build-Docker-Image (push) Successful in 5m15s
Build and Push Docker Image / Build-And-Push-Docker-Image (push) Successful in 5m7s
feat(dashboard): #162 include total sum of accounts compared to total savings
2025-06-16 23:00:38 +02:00

112 lines
2.3 KiB
Go

package service
import (
"context"
"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
err = s.db.GetContext(ctx, &value, `
SELECT SUM(current_balance)
FROM treasure_chest
WHERE user_id = $1`,
user.Id)
err = db.TransformAndLogDbError("dashboard", nil, err)
if err != nil {
return nil, err
}
if value != nil {
summary.SumOfSavings = *value
}
err = s.db.GetContext(ctx, &value, `
SELECT SUM(current_balance)
FROM account
WHERE user_id = $1`,
user.Id)
err = db.TransformAndLogDbError("dashboard", nil, err)
if err != nil {
return nil, err
}
if value != nil {
summary.SumOfAccounts = *value
}
return &summary, nil
}