diff --git a/src/assets/css/aesthetic.css b/src/assets/css/aesthetic.css index e892130..4d6397d 100644 --- a/src/assets/css/aesthetic.css +++ b/src/assets/css/aesthetic.css @@ -27,17 +27,17 @@ @keyframes flicker { 0% { - opacity: 1.1; + opacity: 0.9; } 20% { - opacity: 0.9; - } - 40% { opacity: 1.1; } - 60% { + 40% { opacity: 0.9; } + 60% { + opacity: 1; + } 80% { opacity: 1; } @@ -302,6 +302,35 @@ code { color: var(--url-color); } +.table-container { + overflow-x: auto; + width: 0; + min-width: 100%; +} + +.table-container table { + min-width: max-content; + border-collapse: collapse; +} + +.table-container th { + border-bottom: 2px solid var(--text-color); + padding: 2px 4px; +} + +.table-container td { + padding: 2px 4px; +} + +.table-container th:not(:last-child), +.table-container td:not(:last-child) { + border-right: 1px solid var(--text-color); +} + +.table-container tr.negative-row { + background-color: var(--warning-color); +} + /* CSS for centering images */ .centeredImgContainer { max-width: 80%; @@ -344,6 +373,7 @@ dt { } #container { + max-width: 100%; width: 100%; margin: auto; display: flex; @@ -369,6 +399,8 @@ dt { } .main-container-content { + width: 100%; + max-width: 100%; height: 100%; overflow-y: auto; /* IE and Edge */ diff --git a/src/assets/css/aesthetic.css.map b/src/assets/css/aesthetic.css.map index ec0b832..ba0039c 100644 --- a/src/assets/css/aesthetic.css.map +++ b/src/assets/css/aesthetic.css.map @@ -1 +1 @@ -{"version":3,"sourceRoot":"","sources":["crt.scss","expensesTable.scss","forms.scss","modals.scss","main.scss"],"names":[],"mappings":";AAMA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EAIA;EACA;EACA;EACA;EAEA;;;AAGF;EAII;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;;AAKN;EACE;IACE;;;AAIJ;EACE;IACE;;EAGF;IACE;;EAGF;IACE;;;AAIJ;EACE;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;;ACtJJ;EACE;EACA;EACA;;;AAGF;EACE;;;ACPF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;AAAA;EAEE;EACA;;;AC1DF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;ACnBF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;AAGF;EACE;EACA;EACA;EAEA;EAEA;EACA;AAEA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EAEA;EAEA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAGF;AACA;EACE;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;AAEA;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;EACA,aACE;;;AAGJ;EACE;;;AAGF;EACE;EACA;EAEA;EACA;;;AAGF;AACE;EACA;EACA;EACA;EACA;EACA;AAEA;EACA;EACA;EACA;EACA;EAEA;EACA;EAEA;EAEA;;;AAGF;EACE;EAEA;AAEA;EACA;AACA;EACA;EAEA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;AACA;AACA;AACA;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;IACE;;;AAIJ;EACE;;;AAGF;EACE;EAGA;EACA","file":"aesthetic.css"} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["crt.scss","expensesTable.scss","forms.scss","modals.scss","main.scss"],"names":[],"mappings":";AAMA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EAIA;EACA;EACA;EACA;EAEA;;;AAGF;EAII;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;EADF;IACE;;;AAKN;EACE;IACE;;;AAIJ;EACE;IACE;;EAGF;IACE;;EAGF;IACE;;;AAIJ;EACE;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;EAGF;IACE;;;ACtJJ;EACE;EACA;EACA;;;AAGF;EACE;;;ACPF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;AAAA;EAEE;EACA;;;AC1DF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;EACE;EACA;;;ACnBF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;;AAGF;EACE;EACA;EACA;EAEA;EAEA;EACA;AAEA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EAEA;EAEA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAIF;EACE;EACA;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;AAAA;EAEE;;;AAGF;EACE;;;AAIF;AACA;EACE;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;;;AAGF;AAEA;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;EAEE;EACA,aACE;;;AAGJ;EACE;;;AAGF;EACE;EACA;EACA;EAEA;EACA;;;AAGF;AACE;EACA;EACA;EACA;EACA;EACA;AAEA;EACA;EACA;EACA;EACA;EAEA;EACA;EAEA;EAEA;;;AAGF;EACE;EACA;EACA;EAEA;AAEA;EACA;AACA;EACA;EAEA;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;EACE;EACA;;;AAGF;AACA;AACA;AACA;EACE;;;AAGF;EACE;;;AAGF;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;IACE;;;AAIJ;EACE;;;AAGF;EACE;EAGA;EACA","file":"aesthetic.css"} \ No newline at end of file diff --git a/src/assets/css/main.scss b/src/assets/css/main.scss index 6e58a37..32ed6f3 100644 --- a/src/assets/css/main.scss +++ b/src/assets/css/main.scss @@ -88,6 +88,37 @@ code { color: var(--url-color); } +// Table stuff +.table-container { + overflow-x: auto; + width: 0; + min-width: 100%; +} + +.table-container table { + min-width: max-content; + border-collapse: collapse; +} + +.table-container th { + border-bottom: 2px solid var(--text-color); + padding: 2px 4px; +} + +.table-container td { + padding: 2px 4px; +} + +.table-container th:not(:last-child), +.table-container td:not(:last-child) { + border-right: 1px solid var(--text-color); +} + +.table-container tr.negative-row { + background-color: var(--warning-color); +} +// End of table stuff + /* CSS for centering images */ .centeredImgContainer { max-width: 80%; @@ -132,6 +163,7 @@ dt { } #container { + max-width: 100%; width: 100%; margin: auto; @@ -162,6 +194,8 @@ dt { } .main-container-content { + width: 100%; + max-width: 100%; height: 100%; overflow-y: auto; diff --git a/src/assets/htmx/analysis.html b/src/assets/htmx/analysis.html index d762d41..9fa004e 100644 --- a/src/assets/htmx/analysis.html +++ b/src/assets/htmx/analysis.html @@ -1,18 +1,13 @@ {{ define "analysis" }} -
- -
- -
- -
- - - - +
    +
  1. + +
  2. +
{{ end }} diff --git a/src/assets/htmx/analysisDashboard.html b/src/assets/htmx/analysisDashboard.html new file mode 100644 index 0000000..3865dd4 --- /dev/null +++ b/src/assets/htmx/analysisDashboard.html @@ -0,0 +1,44 @@ +{{ define "analysis-filtered" }} + +
+

+ +
+

+ +

+ +
+

+ + +
+ +
+
+ + + + + + + + + + + + + + + + + +{{ end }} diff --git a/src/assets/htmx/analysisDashboardResults.html b/src/assets/htmx/analysisDashboardResults.html new file mode 100644 index 0000000..e78f2b5 --- /dev/null +++ b/src/assets/htmx/analysisDashboardResults.html @@ -0,0 +1,54 @@ +{{ define "analysis-filtered-results" }} +
+ MONTHLY SUMMARY + +
+ + + + + + + + + + + + + + + + + + + + {{ range . }} + + + + + + + + + + + + + + + + {{ else }} + + + + {{ end }} + +
MonthDespesaSalárioCartão RefeiçãoReembolsoPrendaInvestmentAdjustmentAdjustment LiquidPoupançaPoupança LiquidRunning BalanceRunning Balance Liquid
{{ .MonthYear }}{{ .Despesa }}{{ .Salario }}{{ .CartaoRefeicao }}{{ .Reembolso }}{{ .Prenda }}{{ .Investment }}{{ .Adjustment }}{{ .AdjustmentLiquid }}{{ .Poupanca }}{{ .PoupancaLiquid }}{{ .RunningBalance }}{{ .RunningBalanceLiquid }}
No monthly summary data available.
+
+
+ +
+ PERIOD AVERAGES +
+{{ end }} diff --git a/src/assets/htmx/terminal.html b/src/assets/htmx/terminal.html index d86cb66..050b4cd 100644 --- a/src/assets/htmx/terminal.html +++ b/src/assets/htmx/terminal.html @@ -70,6 +70,8 @@ {{ template "overview" . }} {{ else if eq .content "analysis" }} {{ template "analysis" . }} + {{ else if eq .content "analysis-filtered" }} + {{ template "analysis-filtered" . }} {{ else if eq .content "stores" }} {{ template "stores" . }} {{ else if eq .content "store" }} diff --git a/src/cmd/server.go b/src/cmd/server.go index 61bf967..91a5742 100644 --- a/src/cmd/server.go +++ b/src/cmd/server.go @@ -2,6 +2,10 @@ package cmd import ( "encoding/json" + "html/template" + "log" + "net/http" + "time" "github.com/ESilva15/expenses/api" "github.com/ESilva15/expenses/config" @@ -14,11 +18,7 @@ import ( "github.com/shopspring/decimal" "github.com/spf13/cobra" - "html/template" - "log" - "net/http" fp "path/filepath" - "time" "github.com/gin-gonic/gin" ) @@ -73,6 +73,7 @@ func setRoutes(router *gin.RouterGroup, eng *gin.Engine) { pages.RouteShares(router) pages.RouteOverview(router) pages.RouteAnalysis(router) + pages.RouteAnalysisDashboard(router) // This are for the engine, I really need to rethink this pages.RouteLogin(eng) diff --git a/src/development.md b/src/development.md index d40f6ab..47642c8 100644 --- a/src/development.md +++ b/src/development.md @@ -1,10 +1,11 @@ -# Download a production database's data +# Database stuff +## Download a production database's data ```bash docker exec -i \ pg_dump -U -a -d > outputfile.sql ``` -# Start a local development database +## Start a local development database ```bash # Use to clean the volumens and kill the current running database podman compose down -v database @@ -18,8 +19,11 @@ make devdb_clear make devdb_start ``` -# Upload a database +## Upload a database ```bash # Don't forget to devdb_clear the current existing database psql -h 127.0.0.1 -p 5431 -U expdbuser -d expenses -f ./data.sql ``` + +# CSS +Go to `assets/css` and run `sass --watch main.scss aesthetic.css` diff --git a/src/expenses/app.go b/src/expenses/app.go index e9ba67a..d8ce6c9 100644 --- a/src/expenses/app.go +++ b/src/expenses/app.go @@ -18,12 +18,13 @@ import ( // ExpApp is the data structure for the main runtime of this application. type ExpApp struct { - Lua *lua.LState - ExpRepo repo.ExpenseRepository - CategoryRepo repo.CategoryRepository - UserRepo repo.UserRepository - StoreRepo repo.StoreRepository - TypeRepo repo.TypeRepository + Lua *lua.LState + FinancialRepo repo.FinancialRepository + ExpRepo repo.ExpenseRepository + CategoryRepo repo.CategoryRepository + UserRepo repo.UserRepository + StoreRepo repo.StoreRepository + TypeRepo repo.TypeRepository } // App provides access to the expenses main service. @@ -32,12 +33,13 @@ var App *ExpApp // NewExpenseApp returns a new instance of our core App. func NewExpenseApp(dbPool *pgxpool.Pool, luaVM *lua.LState) *ExpApp { return &ExpApp{ - ExpRepo: repo.NewPgExpRepo(dbPool), - CategoryRepo: repo.NewPgCatRepo(dbPool), - UserRepo: repo.NewPgUserRepo(dbPool), - StoreRepo: repo.NewPgStoreRepo(dbPool), - TypeRepo: repo.NewPgTypeRepo(dbPool), - Lua: luaVM, + FinancialRepo: repo.NewPgFinancialRepo(dbPool), + ExpRepo: repo.NewPgExpRepo(dbPool), + CategoryRepo: repo.NewPgCatRepo(dbPool), + UserRepo: repo.NewPgUserRepo(dbPool), + StoreRepo: repo.NewPgStoreRepo(dbPool), + TypeRepo: repo.NewPgTypeRepo(dbPool), + Lua: luaVM, } } diff --git a/src/expenses/financial.go b/src/expenses/financial.go new file mode 100644 index 0000000..9384221 --- /dev/null +++ b/src/expenses/financial.go @@ -0,0 +1,21 @@ +package expenses + +import ( + "context" + + mod "github.com/ESilva15/expenses/expenses/models" +) + +func (a *ExpApp) GetMonthlySummary( + ctx context.Context, + filter *mod.Filter, +) ([]mod.MonthlySummary, error) { + return a.FinancialRepo.GetMonthlySummary(ctx, filter) +} + +func (a *ExpApp) GetMonthlySavingsAverage( + ctx context.Context, + filter *mod.Filter, +) (mod.MonthlySavingsAverage, error) { + return a.FinancialRepo.GetMonthlySavingsAverage(ctx, filter) +} diff --git a/src/expenses/models/financial.go b/src/expenses/models/financial.go new file mode 100644 index 0000000..90bdf0a --- /dev/null +++ b/src/expenses/models/financial.go @@ -0,0 +1,50 @@ +package models + +import ( + "time" + + dec "github.com/shopspring/decimal" +) + +type MonthlySummary struct { + MonthYear string `json:"month_year"` + Despesa dec.Decimal `json:"despesa"` + Salario dec.Decimal `json:"salario"` + CartaoRefeicao dec.Decimal `json:"cartao_refeicao"` + Reembolso dec.Decimal `json:"reembolso"` + Prenda dec.Decimal `json:"prenda"` + Investment dec.Decimal `json:"investment"` + Adjustment dec.Decimal `json:"adjustment"` + AdjustmentLiquid dec.Decimal `json:"adjustment_liquid"` + Poupanca dec.Decimal `json:"poupanca"` + PoupancaLiquid dec.Decimal `json:"poupanca_liquid"` + RunningBalance dec.Decimal `json:"running_balance"` + RunningBalanceLiquid dec.Decimal `json:"running_balance_liquid"` +} + +type MonthlySavingsAverage struct { + AvgPoupanca dec.Decimal `json:"avg_poupanca"` + AvgPoupancaLiquid dec.Decimal `json:"avg_poupanca_liquid"` +} + +// ExpFilter has the fields required to query the database. +type Filter struct { + Start *time.Time // Start is the earliest an expense can be + End *time.Time // End is the latest an expense can be + UserIDs int32 // UserIDs is a list of IDs to match against + CatIDs []int32 // CatIDs is a list of categories to match against + StoreIDs []int32 // StoreIDs is a list of stores to match against + TypeIDs []int32 // TypeIDs is a list of types to match against +} + +// NewExpFilter returns a newly initialized ExpFilter. +func NewFilter() Filter { + return Filter{ + Start: nil, + End: nil, + UserIDs: -1, + CatIDs: nil, + StoreIDs: nil, + TypeIDs: nil, + } +} diff --git a/src/expenses/repo/financialRepo.go b/src/expenses/repo/financialRepo.go new file mode 100644 index 0000000..41f362b --- /dev/null +++ b/src/expenses/repo/financialRepo.go @@ -0,0 +1,14 @@ +package repo + +import ( + "context" + + mod "github.com/ESilva15/expenses/expenses/models" +) + +// CategoryRepository defines the repository for the category data model. +type FinancialRepository interface { + GetMonthlySummary(context.Context, *mod.Filter) ([]mod.MonthlySummary, error) + GetMonthlySavingsAverage(context.Context, *mod.Filter) (mod.MonthlySavingsAverage, error) + Close() +} diff --git a/src/expenses/repo/pg_financialMapper.go b/src/expenses/repo/pg_financialMapper.go new file mode 100644 index 0000000..defa566 --- /dev/null +++ b/src/expenses/repo/pg_financialMapper.go @@ -0,0 +1,39 @@ +package repo + +import ( + mod "github.com/ESilva15/expenses/expenses/models" + pgsqlc "github.com/ESilva15/expenses/expenses/repo/pgdb/pgsqlc" +) + +func mapRepoMonthlySummary(r pgsqlc.GetMonthlySummaryRow) mod.MonthlySummary { + return mod.MonthlySummary{ + MonthYear: r.MonthYear, + Despesa: pgNumericToDecimal(r.Despesa), + Salario: pgNumericToDecimal(r.Salario), + CartaoRefeicao: pgNumericToDecimal(r.CartaoRefeicao), + Reembolso: pgNumericToDecimal(r.Reembolso), + Prenda: pgNumericToDecimal(r.Prenda), + Investment: pgNumericToDecimal(r.Investment), + Adjustment: pgNumericToDecimal(r.Adjustment), + AdjustmentLiquid: pgNumericToDecimal(r.AdjustmentLiquid), + Poupanca: pgNumericToDecimal(r.Poupanca), + PoupancaLiquid: pgNumericToDecimal(r.PoupancaLiquid), + RunningBalance: pgNumericToDecimal(r.RunningBalance), + RunningBalanceLiquid: pgNumericToDecimal(r.RunningBalanceLiquid), + } +} + +func mapRepoMonthlySummaries(rows []pgsqlc.GetMonthlySummaryRow) []mod.MonthlySummary { + summaries := make([]mod.MonthlySummary, len(rows)) + for i, row := range rows { + summaries[i] = mapRepoMonthlySummary(row) + } + return summaries +} + +func mapRepoMonthlySavingsAverage(r pgsqlc.GetMonthlySavingsAverageRow) mod.MonthlySavingsAverage { + return mod.MonthlySavingsAverage{ + AvgPoupanca: pgNumericToDecimal(r.AvgPoupanca), + AvgPoupancaLiquid: pgNumericToDecimal(r.AvgPoupancaLiquid), + } +} diff --git a/src/expenses/repo/pg_financialRepo.go b/src/expenses/repo/pg_financialRepo.go new file mode 100644 index 0000000..36ee615 --- /dev/null +++ b/src/expenses/repo/pg_financialRepo.go @@ -0,0 +1,61 @@ +package repo + +import ( + "context" + + mod "github.com/ESilva15/expenses/expenses/models" + "github.com/ESilva15/expenses/expenses/repo/pgdb/pgsqlc" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" +) + +type PgFinancialRepo struct { + DB *pgxpool.Pool +} + +func NewPgFinancialRepo(db *pgxpool.Pool) PgFinancialRepo { + return PgFinancialRepo{DB: db} +} + +func (f PgFinancialRepo) Close() { + f.DB.Close() +} + +func (p PgFinancialRepo) GetMonthlySummary( + ctx context.Context, + filter *mod.Filter, +) ([]mod.MonthlySummary, error) { + queries := pgsqlc.New(p.DB) + + var pgStart, pgEnd pgtype.Timestamp + if filter.Start != nil { + pgStart = pgtype.Timestamp{Time: *filter.Start, Valid: true} + } + if filter.End != nil { + pgEnd = pgtype.Timestamp{Time: *filter.End, Valid: true} + } + + rows, err := queries.GetMonthlySummary(ctx, pgsqlc.GetMonthlySummaryParams{ + Startdate: pgStart, + Enddate: pgEnd, + UserID: filter.UserIDs, + }) + if err != nil { + return nil, err + } + + return mapRepoMonthlySummaries(rows), nil +} + +func (p PgFinancialRepo) GetMonthlySavingsAverage( + ctx context.Context, + filter *mod.Filter, +) (mod.MonthlySavingsAverage, error) { + queries := pgsqlc.New(p.DB) + res, err := queries.GetMonthlySavingsAverage(ctx) + if err != nil { + return mod.MonthlySavingsAverage{}, err + } + + return mapRepoMonthlySavingsAverage(res), nil +} diff --git a/src/expenses/repo/pgdb/pgsqlc/categories.sql.go b/src/expenses/repo/pgdb/pgsqlc/categories.sql.go index 0c07049..7d4a2cf 100644 --- a/src/expenses/repo/pgdb/pgsqlc/categories.sql.go +++ b/src/expenses/repo/pgdb/pgsqlc/categories.sql.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 // source: categories.sql package pgsqlc diff --git a/src/expenses/repo/pgdb/pgsqlc/db.go b/src/expenses/repo/pgdb/pgsqlc/db.go index 03ff426..8a1bc66 100644 --- a/src/expenses/repo/pgdb/pgsqlc/db.go +++ b/src/expenses/repo/pgdb/pgsqlc/db.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 package pgsqlc diff --git a/src/expenses/repo/pgdb/pgsqlc/expenses.sql.go b/src/expenses/repo/pgdb/pgsqlc/expenses.sql.go index 3727467..38f454e 100644 --- a/src/expenses/repo/pgdb/pgsqlc/expenses.sql.go +++ b/src/expenses/repo/pgdb/pgsqlc/expenses.sql.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 // source: expenses.sql package pgsqlc @@ -84,6 +84,59 @@ func (q *Queries) GetExpense(ctx context.Context, expid int32) (GetExpenseRow, e return i, err } +const getExpenseSum = `-- name: GetExpenseSum :one +SELECT "ExpID", "Description", "Value", "StoreID", "CategoryID", "OwnerUserID", "TypeID", "ExpDate", "CreationDate", "PaidOff", "SharesEven", qr, "ExpShareID", "ExpID", "UserID", "Share", "Calculated" from "expenses" +JOIN "expensesShares" ON "expenses"."ExpID" = "expensesShares"."ExpID" +WHERE + "expenses"."ExpID" = 673 AND + "expensesShares"."UserID" = 1 +` + +type GetExpenseSumRow struct { + ExpID int32 + Description string + Value pgtype.Numeric + StoreID int32 + CategoryID int32 + OwnerUserID int32 + TypeID int32 + ExpDate pgtype.Timestamp + CreationDate pgtype.Timestamp + PaidOff pgtype.Bool + SharesEven pgtype.Bool + Qr string + ExpShareID int32 + ExpID_2 int32 + UserID int32 + Share pgtype.Numeric + Calculated pgtype.Numeric +} + +func (q *Queries) GetExpenseSum(ctx context.Context) (GetExpenseSumRow, error) { + row := q.db.QueryRow(ctx, getExpenseSum) + var i GetExpenseSumRow + err := row.Scan( + &i.ExpID, + &i.Description, + &i.Value, + &i.StoreID, + &i.CategoryID, + &i.OwnerUserID, + &i.TypeID, + &i.ExpDate, + &i.CreationDate, + &i.PaidOff, + &i.SharesEven, + &i.Qr, + &i.ExpShareID, + &i.ExpID_2, + &i.UserID, + &i.Share, + &i.Calculated, + ) + return i, err +} + const getExpenses = `-- name: GetExpenses :many SELECT expenses."ExpID", expenses."Description", expenses."Value", expenses."StoreID", expenses."CategoryID", expenses."OwnerUserID", expenses."TypeID", expenses."ExpDate", expenses."CreationDate", expenses."PaidOff", expenses."SharesEven", expenses.qr, @@ -182,6 +235,45 @@ func (q *Queries) GetExpenses(ctx context.Context, arg GetExpensesParams) ([]Get return items, nil } +const getMonthlyTotalPaid = `-- name: GetMonthlyTotalPaid :many +SELECT + EXTRACT(MONTH FROM e."ExpDate") AS month, + SUM(ep."Payed") AS monthly_total_paid +FROM "expensesPayments" ep +JOIN + expenses e ON ep."ExpID" = e."ExpID" +WHERE + ep."UserID" = 1 + AND e."TypeID" = 0 +GROUP BY EXTRACT(MONTH FROM e."ExpDate") +ORDER BY month +` + +type GetMonthlyTotalPaidRow struct { + Month pgtype.Numeric + MonthlyTotalPaid int64 +} + +func (q *Queries) GetMonthlyTotalPaid(ctx context.Context) ([]GetMonthlyTotalPaidRow, error) { + rows, err := q.db.Query(ctx, getMonthlyTotalPaid) + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetMonthlyTotalPaidRow + for rows.Next() { + var i GetMonthlyTotalPaidRow + if err := rows.Scan(&i.Month, &i.MonthlyTotalPaid); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const insertExpense = `-- name: InsertExpense :one INSERT INTO expenses( "Description", diff --git a/src/expenses/repo/pgdb/pgsqlc/financial.sql.go b/src/expenses/repo/pgdb/pgsqlc/financial.sql.go new file mode 100644 index 0000000..e3127aa --- /dev/null +++ b/src/expenses/repo/pgdb/pgsqlc/financial.sql.go @@ -0,0 +1,168 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: financial.sql + +package pgsqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const getMonthlySavingsAverage = `-- name: GetMonthlySavingsAverage :one +WITH monthly_summary AS ( + SELECT + TO_CHAR(e."ExpDate", 'MM/YYYY') AS month_year, + DATE_TRUNC('month', e."ExpDate") AS month_sort, + SUM(CASE WHEN e."TypeID" = 0 THEN ep."Payed" ELSE 0 END)::NUMERIC AS despesa, + SUM(CASE WHEN e."TypeID" = 1 THEN ep."Payed" ELSE 0 END)::NUMERIC AS salario, + SUM(CASE WHEN e."TypeID" = 2 THEN ep."Payed" ELSE 0 END)::NUMERIC AS cartao_refeicao, + SUM(CASE WHEN e."TypeID" = 3 THEN ep."Payed" ELSE 0 END)::NUMERIC AS reembolso, + SUM(CASE WHEN e."TypeID" = 4 THEN ep."Payed" ELSE 0 END)::NUMERIC AS prenda, + SUM(CASE WHEN e."TypeID" = 5 THEN ep."Payed" ELSE 0 END)::NUMERIC AS investment, + SUM(CASE WHEN e."TypeID" = 6 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment, + SUM(CASE WHEN e."TypeID" = 7 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment_liquid + FROM "expensesPayments" ep + JOIN expenses e ON ep."ExpID" = e."ExpID" + WHERE ep."UserID" = 1 + GROUP BY + TO_CHAR(e."ExpDate", 'MM/YYYY'), + DATE_TRUNC('month', e."ExpDate") +), +calculated_summary AS ( + SELECT + ((salario + cartao_refeicao + reembolso) - (despesa + prenda))::NUMERIC AS poupanca, + ((salario + cartao_refeicao + reembolso) - (despesa + investment + prenda))::NUMERIC AS poupanca_liquid + FROM monthly_summary +) +SELECT + TRUNC(AVG(poupanca), 2)::NUMERIC AS avg_poupanca, + TRUNC(AVG(poupanca_liquid), 2)::NUMERIC AS avg_poupanca_liquid +FROM calculated_summary +` + +type GetMonthlySavingsAverageRow struct { + AvgPoupanca pgtype.Numeric + AvgPoupancaLiquid pgtype.Numeric +} + +func (q *Queries) GetMonthlySavingsAverage(ctx context.Context) (GetMonthlySavingsAverageRow, error) { + row := q.db.QueryRow(ctx, getMonthlySavingsAverage) + var i GetMonthlySavingsAverageRow + err := row.Scan(&i.AvgPoupanca, &i.AvgPoupancaLiquid) + return i, err +} + +const getMonthlySummary = `-- name: GetMonthlySummary :many +WITH monthly_summary AS ( + SELECT + TO_CHAR(e."ExpDate", 'MM/YYYY') AS month_year, + DATE_TRUNC('month', e."ExpDate") AS month_sort, + SUM(CASE WHEN e."TypeID" = 0 THEN ep."Payed" ELSE 0 END)::NUMERIC AS despesa, + SUM(CASE WHEN e."TypeID" = 1 THEN ep."Payed" ELSE 0 END)::NUMERIC AS salario, + SUM(CASE WHEN e."TypeID" = 2 THEN ep."Payed" ELSE 0 END)::NUMERIC AS cartao_refeicao, + SUM(CASE WHEN e."TypeID" = 3 THEN ep."Payed" ELSE 0 END)::NUMERIC AS reembolso, + SUM(CASE WHEN e."TypeID" = 4 THEN ep."Payed" ELSE 0 END)::NUMERIC AS prenda, + SUM(CASE WHEN e."TypeID" = 5 THEN ep."Payed" ELSE 0 END)::NUMERIC AS investment, + SUM(CASE WHEN e."TypeID" = 6 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment, + SUM(CASE WHEN e."TypeID" = 7 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment_liquid + FROM "expensesPayments" ep + JOIN expenses e ON ep."ExpID" = e."ExpID" + WHERE ep."UserID" = $1 + AND ($2::timestamp IS NULL OR e."ExpDate" >= $2::timestamp) + AND ($3::timestamp IS NULL OR e."ExpDate" <= $3::timestamp) + GROUP BY + TO_CHAR(e."ExpDate", 'MM/YYYY'), + DATE_TRUNC('month', e."ExpDate") +), +calculated_summary AS ( + SELECT + month_year, + month_sort, + despesa, + salario, + cartao_refeicao, + reembolso, + prenda, + investment, + adjustment, + adjustment_liquid, + ((salario + cartao_refeicao + reembolso) - (despesa + prenda))::NUMERIC AS poupanca, + ((salario + cartao_refeicao + reembolso) - (despesa + investment + prenda))::NUMERIC AS poupanca_liquid + FROM monthly_summary +) +SELECT + month_year, + despesa, + salario, + cartao_refeicao, + reembolso, + prenda, + investment, + adjustment, + adjustment_liquid, + poupanca, + poupanca_liquid, + (SUM(poupanca) OVER (ORDER BY month_sort ASC) + SUM(adjustment) OVER (ORDER BY month_sort ASC) + SUM(adjustment_liquid) OVER (ORDER BY month_sort ASC))::NUMERIC AS running_balance, + (SUM(poupanca_liquid) OVER (ORDER BY month_sort ASC) + SUM(adjustment_liquid) OVER (ORDER BY month_sort ASC))::NUMERIC AS running_balance_liquid +FROM calculated_summary +ORDER BY month_sort ASC +` + +type GetMonthlySummaryParams struct { + UserID int32 + Startdate pgtype.Timestamp + Enddate pgtype.Timestamp +} + +type GetMonthlySummaryRow struct { + MonthYear string + Despesa pgtype.Numeric + Salario pgtype.Numeric + CartaoRefeicao pgtype.Numeric + Reembolso pgtype.Numeric + Prenda pgtype.Numeric + Investment pgtype.Numeric + Adjustment pgtype.Numeric + AdjustmentLiquid pgtype.Numeric + Poupanca pgtype.Numeric + PoupancaLiquid pgtype.Numeric + RunningBalance pgtype.Numeric + RunningBalanceLiquid pgtype.Numeric +} + +func (q *Queries) GetMonthlySummary(ctx context.Context, arg GetMonthlySummaryParams) ([]GetMonthlySummaryRow, error) { + rows, err := q.db.Query(ctx, getMonthlySummary, arg.UserID, arg.Startdate, arg.Enddate) + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetMonthlySummaryRow + for rows.Next() { + var i GetMonthlySummaryRow + if err := rows.Scan( + &i.MonthYear, + &i.Despesa, + &i.Salario, + &i.CartaoRefeicao, + &i.Reembolso, + &i.Prenda, + &i.Investment, + &i.Adjustment, + &i.AdjustmentLiquid, + &i.Poupanca, + &i.PoupancaLiquid, + &i.RunningBalance, + &i.RunningBalanceLiquid, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/src/expenses/repo/pgdb/pgsqlc/models.go b/src/expenses/repo/pgdb/pgsqlc/models.go index 50503b9..7f0fe90 100644 --- a/src/expenses/repo/pgdb/pgsqlc/models.go +++ b/src/expenses/repo/pgdb/pgsqlc/models.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 package pgsqlc diff --git a/src/expenses/repo/pgdb/pgsqlc/payments.sql.go b/src/expenses/repo/pgdb/pgsqlc/payments.sql.go index 6da6980..b1ef021 100644 --- a/src/expenses/repo/pgdb/pgsqlc/payments.sql.go +++ b/src/expenses/repo/pgdb/pgsqlc/payments.sql.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 // source: payments.sql package pgsqlc diff --git a/src/expenses/repo/pgdb/pgsqlc/shares.sql.go b/src/expenses/repo/pgdb/pgsqlc/shares.sql.go index 953db11..6efbd38 100644 --- a/src/expenses/repo/pgdb/pgsqlc/shares.sql.go +++ b/src/expenses/repo/pgdb/pgsqlc/shares.sql.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 // source: shares.sql package pgsqlc diff --git a/src/expenses/repo/pgdb/pgsqlc/stores.sql.go b/src/expenses/repo/pgdb/pgsqlc/stores.sql.go index 00adb80..098a7a0 100644 --- a/src/expenses/repo/pgdb/pgsqlc/stores.sql.go +++ b/src/expenses/repo/pgdb/pgsqlc/stores.sql.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 // source: stores.sql package pgsqlc diff --git a/src/expenses/repo/pgdb/pgsqlc/types.sql.go b/src/expenses/repo/pgdb/pgsqlc/types.sql.go index b385bd6..02314b2 100644 --- a/src/expenses/repo/pgdb/pgsqlc/types.sql.go +++ b/src/expenses/repo/pgdb/pgsqlc/types.sql.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 // source: types.sql package pgsqlc diff --git a/src/expenses/repo/pgdb/pgsqlc/users.sql.go b/src/expenses/repo/pgdb/pgsqlc/users.sql.go index 42e1e67..070418e 100644 --- a/src/expenses/repo/pgdb/pgsqlc/users.sql.go +++ b/src/expenses/repo/pgdb/pgsqlc/users.sql.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.30.0 +// sqlc v1.31.1 // source: users.sql package pgsqlc diff --git a/src/expenses/repo/pgdb/queries/expenses.sql b/src/expenses/repo/pgdb/queries/expenses.sql index 5a06ff0..dbff381 100644 --- a/src/expenses/repo/pgdb/queries/expenses.sql +++ b/src/expenses/repo/pgdb/queries/expenses.sql @@ -87,3 +87,23 @@ SET "qr" = $9, "ExpDate" = $10 WHERE "ExpID" = $11; + +-- name: GetExpenseSum :one +SELECT * from "expenses" +JOIN "expensesShares" ON "expenses"."ExpID" = "expensesShares"."ExpID" +WHERE + "expenses"."ExpID" = 673 AND + "expensesShares"."UserID" = 1; + +-- name: GetMonthlyTotalPaid :many +SELECT + EXTRACT(MONTH FROM e."ExpDate") AS month, + SUM(ep."Payed") AS monthly_total_paid +FROM "expensesPayments" ep +JOIN + expenses e ON ep."ExpID" = e."ExpID" +WHERE + ep."UserID" = 1 + AND e."TypeID" = 0 +GROUP BY EXTRACT(MONTH FROM e."ExpDate") +ORDER BY month; diff --git a/src/expenses/repo/pgdb/queries/financial.sql b/src/expenses/repo/pgdb/queries/financial.sql new file mode 100644 index 0000000..903f5e2 --- /dev/null +++ b/src/expenses/repo/pgdb/queries/financial.sql @@ -0,0 +1,85 @@ +-- name: GetMonthlySummary :many +WITH monthly_summary AS ( + SELECT + TO_CHAR(e."ExpDate", 'MM/YYYY') AS month_year, + DATE_TRUNC('month', e."ExpDate") AS month_sort, + SUM(CASE WHEN e."TypeID" = 0 THEN ep."Payed" ELSE 0 END)::NUMERIC AS despesa, + SUM(CASE WHEN e."TypeID" = 1 THEN ep."Payed" ELSE 0 END)::NUMERIC AS salario, + SUM(CASE WHEN e."TypeID" = 2 THEN ep."Payed" ELSE 0 END)::NUMERIC AS cartao_refeicao, + SUM(CASE WHEN e."TypeID" = 3 THEN ep."Payed" ELSE 0 END)::NUMERIC AS reembolso, + SUM(CASE WHEN e."TypeID" = 4 THEN ep."Payed" ELSE 0 END)::NUMERIC AS prenda, + SUM(CASE WHEN e."TypeID" = 5 THEN ep."Payed" ELSE 0 END)::NUMERIC AS investment, + SUM(CASE WHEN e."TypeID" = 6 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment, + SUM(CASE WHEN e."TypeID" = 7 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment_liquid + FROM "expensesPayments" ep + JOIN expenses e ON ep."ExpID" = e."ExpID" + WHERE ep."UserID" = $1 + AND (sqlc.narg(StartDate)::timestamp IS NULL OR e."ExpDate" >= sqlc.narg(StartDate)::timestamp) + AND (sqlc.narg(EndDate)::timestamp IS NULL OR e."ExpDate" <= sqlc.narg(EndDate)::timestamp) + GROUP BY + TO_CHAR(e."ExpDate", 'MM/YYYY'), + DATE_TRUNC('month', e."ExpDate") +), +calculated_summary AS ( + SELECT + month_year, + month_sort, + despesa, + salario, + cartao_refeicao, + reembolso, + prenda, + investment, + adjustment, + adjustment_liquid, + ((salario + cartao_refeicao + reembolso) - (despesa + prenda))::NUMERIC AS poupanca, + ((salario + cartao_refeicao + reembolso) - (despesa + investment + prenda))::NUMERIC AS poupanca_liquid + FROM monthly_summary +) +SELECT + month_year, + despesa, + salario, + cartao_refeicao, + reembolso, + prenda, + investment, + adjustment, + adjustment_liquid, + poupanca, + poupanca_liquid, + (SUM(poupanca) OVER (ORDER BY month_sort ASC) + SUM(adjustment) OVER (ORDER BY month_sort ASC) + SUM(adjustment_liquid) OVER (ORDER BY month_sort ASC))::NUMERIC AS running_balance, + (SUM(poupanca_liquid) OVER (ORDER BY month_sort ASC) + SUM(adjustment_liquid) OVER (ORDER BY month_sort ASC))::NUMERIC AS running_balance_liquid +FROM calculated_summary +ORDER BY month_sort ASC; + +-- name: GetMonthlySavingsAverage :one +WITH monthly_summary AS ( + SELECT + TO_CHAR(e."ExpDate", 'MM/YYYY') AS month_year, + DATE_TRUNC('month', e."ExpDate") AS month_sort, + SUM(CASE WHEN e."TypeID" = 0 THEN ep."Payed" ELSE 0 END)::NUMERIC AS despesa, + SUM(CASE WHEN e."TypeID" = 1 THEN ep."Payed" ELSE 0 END)::NUMERIC AS salario, + SUM(CASE WHEN e."TypeID" = 2 THEN ep."Payed" ELSE 0 END)::NUMERIC AS cartao_refeicao, + SUM(CASE WHEN e."TypeID" = 3 THEN ep."Payed" ELSE 0 END)::NUMERIC AS reembolso, + SUM(CASE WHEN e."TypeID" = 4 THEN ep."Payed" ELSE 0 END)::NUMERIC AS prenda, + SUM(CASE WHEN e."TypeID" = 5 THEN ep."Payed" ELSE 0 END)::NUMERIC AS investment, + SUM(CASE WHEN e."TypeID" = 6 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment, + SUM(CASE WHEN e."TypeID" = 7 THEN ep."Payed" ELSE 0 END)::NUMERIC AS adjustment_liquid + FROM "expensesPayments" ep + JOIN expenses e ON ep."ExpID" = e."ExpID" + WHERE ep."UserID" = 1 + GROUP BY + TO_CHAR(e."ExpDate", 'MM/YYYY'), + DATE_TRUNC('month', e."ExpDate") +), +calculated_summary AS ( + SELECT + ((salario + cartao_refeicao + reembolso) - (despesa + prenda))::NUMERIC AS poupanca, + ((salario + cartao_refeicao + reembolso) - (despesa + investment + prenda))::NUMERIC AS poupanca_liquid + FROM monthly_summary +) +SELECT + TRUNC(AVG(poupanca), 2)::NUMERIC AS avg_poupanca, + TRUNC(AVG(poupanca_liquid), 2)::NUMERIC AS avg_poupanca_liquid +FROM calculated_summary; diff --git a/src/pages/analysis.go b/src/pages/analysis.go deleted file mode 100644 index a6fcf33..0000000 --- a/src/pages/analysis.go +++ /dev/null @@ -1,103 +0,0 @@ -package pages - -import ( - "net/http" - - exp "github.com/ESilva15/expenses/expenses" - mod "github.com/ESilva15/expenses/expenses/models" - val "github.com/ESilva15/expenses/expenses/values" - dec "github.com/shopspring/decimal" - - "github.com/gin-gonic/gin" -) - -// MonthlyTotal holds the data for the MonthlyTotal plot. -type MonthlyTotal struct { - Month int `json:"month"` - Total dec.Decimal `json:"total"` -} - -func getAnalysisDataWG(c *gin.Context) (map[string]any, error) { - ctx, err := getLoggedInUserCTX(c) - if err != nil { - return map[string]any{}, err - } - user := *ctx.Value("user").(*mod.User) - - filter, err := expenseFilterFromQuery(c) - if err != nil { - return map[string]any{}, err - } - - queriedExpenses, err := exp.App.GetAllExpenses(ctx, filter) - if err != nil { - return map[string]any{}, err - } - - for i := range queriedExpenses { - _ = exp.App.LoadExpensePayments(&queriedExpenses[i]) - } - - mBalance := make([]MonthlyTotal, val.MonthsPerYear) - for k := range val.MonthsPerYear { - mBalance[k].Month = k - } - - for _, e := range queriedExpenses { - month := int(e.Date.Month()) - 1 // Jan = 0 - t := e.Type.TypeName - - value := exp.App.PaidByUser(e, user.UserID) - if t == "Despesa" { - value = value.Neg() - } - - mBalance[month].Total = mBalance[month].Total.Add(value) - } - - mTotal := make([]MonthlyTotal, len(mBalance)) - copy(mTotal, mBalance) - for i := 1; i < len(mTotal); i++ { - mTotal[i].Total = mTotal[i].Total.Add(mTotal[i-1].Total) - } - - plotData := map[string]any{ - "mBalance": mBalance, - "mTotal": mTotal, - } - - return plotData, nil -} - -func analysisPartialPage(c *gin.Context) { - data, err := getAnalysisDataWG(c) - if err != nil { - ServerErrorView(c, "failed to compile analysis data") - return - } - - c.HTML(http.StatusOK, "analysis", gin.H{ - "plotData": data, - }) -} - -func analysisPage(c *gin.Context) { - data, err := getAnalysisDataWG(c) - if err != nil { - ServerErrorView(c, "failed to compile analysis data") - return - } - - c.HTML(http.StatusOK, "terminal", gin.H{ - "page": "analysis", - "renderNavBar": true, - "content": "analysis", - "plotData": data, - }) -} - -// RouteAnalysis routes the endpoints for analysis stuff. -func RouteAnalysis(router *gin.RouterGroup) { - router.GET("/analysis", analysisPage) - router.POST("/analysis", analysisPartialPage) -} diff --git a/src/pages/expensesHelper.go b/src/pages/expensesHelper.go index acf48f7..9c158ce 100644 --- a/src/pages/expensesHelper.go +++ b/src/pages/expensesHelper.go @@ -15,6 +15,54 @@ import ( "github.com/shopspring/decimal" ) +func filterFromQuery(c *gin.Context) (mod.Filter, error) { + var err error + var start, end time.Time + filter := mod.NewFilter() + + startDate := c.Query("range-start") + if startDate != "" { + startDate += " 00:00:00" + start, err = time.ParseInLocation("02-Jan-2006 15:04:05", startDate, time.UTC) + if err != nil { + log.Printf("error startDate: %v", err) + return mod.Filter{}, nil + } + filter.Start = &start + } + + endDate := c.Query("range-end") + if endDate != "" { + endDate += " 00:00:00" + end, err = time.ParseInLocation("02-Jan-2006 15:04:05", endDate, time.UTC) + if err != nil { + log.Printf("error endDate: %v", err) + return mod.Filter{}, nil + } + filter.End = &end + } + + filter.CatIDs, err = ginaux.QueryIntArray(c, "cat-dropdown[]") + if err != nil { + log.Printf("Failed to retrieve IDs from cat-dropdown[] %+v", err) + return mod.Filter{}, nil + } + + filter.StoreIDs, err = ginaux.QueryIntArray(c, "store-dropdown[]") + if err != nil { + log.Printf("Failed to retrieve IDs from store-dropdown[] %+v", err) + return mod.Filter{}, nil + } + + filter.TypeIDs, err = ginaux.QueryIntArray(c, "type-dropdown[]") + if err != nil { + log.Printf("Failed to retrieve IDs from type-dropdown[] %+v", err) + return mod.Filter{}, nil + } + + return filter, nil +} + func expenseFilterFromQuery(c *gin.Context) (repo.ExpFilter, error) { var err error var start, end time.Time diff --git a/src/pages/financial.go b/src/pages/financial.go new file mode 100644 index 0000000..b6ed994 --- /dev/null +++ b/src/pages/financial.go @@ -0,0 +1,25 @@ +package pages + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +func analysisPage(c *gin.Context) { + c.HTML(http.StatusOK, "terminal", gin.H{ + "page": "analysis", + "renderNavBar": true, + "content": "analysis", + }) +} + +func analysisPartialPage(c *gin.Context) { + c.HTML(http.StatusOK, "analysis", gin.H{}) +} + +// RouteAnalysis routes the endpoints for analysis stuff. +func RouteAnalysis(router *gin.RouterGroup) { + router.GET("/analysis", analysisPage) + router.POST("/analysis", analysisPartialPage) +} diff --git a/src/pages/financialDashboard.go b/src/pages/financialDashboard.go new file mode 100644 index 0000000..db6c484 --- /dev/null +++ b/src/pages/financialDashboard.go @@ -0,0 +1,67 @@ +package pages + +import ( + "log" + "net/http" + + exp "github.com/ESilva15/expenses/expenses" + mod "github.com/ESilva15/expenses/expenses/models" + "github.com/gin-gonic/gin" +) + +func getSummaryData(c *gin.Context) ([]mod.MonthlySummary, error) { + ctx, err := getLoggedInUserCTX(c) + if err != nil { + log.Printf("error getting user from context: %+v", err) + ServerErrorView(c, "Could not get logged in user") + return nil, nil + } + + filter, err := filterFromQuery(c) + if err != nil { + log.Printf("error parsing filters from query: %+v", err) + ServerErrorView(c, "Could not get logged in user") + return nil, nil + } + filter.UserIDs = *&ctx.Value("user").(*mod.User).UserID + summary, err := exp.App.GetMonthlySummary(ctx, &filter) + if err != nil { + log.Printf("error retrieving monthly summary from DB: %+v", err) + c.Header("HX-Redirect", "/500") + return nil, err + } + + return summary, nil +} + +func analysisDashboardPage(c *gin.Context) { + c.HTML(http.StatusOK, "terminal", gin.H{ + "page": "analysis-filtered", + "renderNavBar": true, + "content": "analysis-filtered", + }) +} + +func analysisDashboardPagePartial(c *gin.Context) { + c.HTML(http.StatusOK, "analysis-filtered", gin.H{ + // "plotData": data, + }) +} + +func analysisDashboardQuery(c *gin.Context) { + data, err := getSummaryData(c) + if err != nil { + log.Printf("error: %+v", err) + ServerErrorView(c, "failed to compile analysis data") + return + } + + c.HTML(http.StatusOK, "analysis-filtered-results", data) +} + +// RouteAnalysis routes the endpoints for analysis stuff. +func RouteAnalysisDashboard(router *gin.RouterGroup) { + router.GET("/filtered-analysis", analysisDashboardPage) + router.GET("/filtered-analysis/filters", analysisDashboardQuery) + router.POST("/filtered-analysis", analysisDashboardPagePartial) +}