added the analysis stuff. Still needs a lot of work but it will do for now

This commit is contained in:
2026-10-15 14:33:44 +01:00
parent f4b8f871d1
commit 3cf98f850b
31 changed files with 907 additions and 152 deletions
+37 -5
View File
@@ -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 */
+1 -1
View File
@@ -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"}
{"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"}
+34
View File
@@ -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;
+10 -15
View File
@@ -1,18 +1,13 @@
{{ define "analysis" }}
<div>
<canvas id="monthlyTotal"></canvas>
</div>
<div>
<canvas id="monthlyBalance"></canvas>
</div>
<script>
<!-- Inject go data here -->
window.analysisBalanceData = {{ .plotData.mBalance | toJson }};
window.analysisTotalData = {{ .plotData.mTotal | toJson }};
</script>
<script src="/assets/js/analysis.js"></script>
<ol>
<li>
<button
hx-post="/filtered-analysis"
hx-target="#content"
hx-swap="innerHTML"
hx-replace-url="true"
id="overview">FILTERED ANALYSIS</button>
</li>
</ol>
{{ end }}
+44
View File
@@ -0,0 +1,44 @@
{{ define "analysis-filtered" }}
<form
hx-get="/filtered-analysis/filters"
hx-target="#filtered-analysis"
hx-swap="innerHTML"
>
<p>
<label for="range-start">Start date:</label>
<input
class="tui-input underline fullwidth" type="text" name="range-start"
value="" id="expense-date"><br>
</p>
<p>
<label for="range-end">End date:</label>
<input
class="tui-input underline fullwidth" type="text" name="range-end"
value="" id="expense-date"><br>
</p>
<button type="submit" id="expenses">QUERY</button>
</form>
<div id="filtered-analysis">
</div>
<!-- <div> -->
<!-- <canvas id="monthlyTotal"></canvas> -->
<!-- </div> -->
<!---->
<!-- <div> -->
<!-- <canvas id="monthlyBalance"></canvas> -->
<!-- </div> -->
<!---->
<!-- <script> -->
<!-- <!-- Inject go data here -->
<!-- window.analysisBalanceData = {{ .plotData.mBalance | toJson }}; -->
<!-- window.analysisTotalData = {{ .plotData.mTotal | toJson }}; -->
<!-- </script> -->
<!---->
<!-- <script src="/assets/js/analysis.js"></script> -->
{{ end }}
@@ -0,0 +1,54 @@
{{ define "analysis-filtered-results" }}
<fieldset>
<legend>MONTHLY SUMMARY</legend>
<!-- <div style="overflow-x: auto; width: 0; min-width: 100%;"> -->
<div class="table-container">
<table>
<thead>
<tr>
<th>Month</th>
<th>Despesa</th>
<th>Salário</th>
<th>Cartão Refeição</th>
<th>Reembolso</th>
<th>Prenda</th>
<th>Investment</th>
<th>Adjustment</th>
<th>Adjustment Liquid</th>
<th>Poupança</th>
<th>Poupança Liquid</th>
<th>Running Balance</th>
<th>Running Balance Liquid</th>
</tr>
</thead>
<tbody>
{{ range . }}
<tr {{ if .PoupancaLiquid.IsNegative }}class="negative-row"{{ end }}>
<td>{{ .MonthYear }}</td>
<td>{{ .Despesa }}</td>
<td>{{ .Salario }}</td>
<td>{{ .CartaoRefeicao }}</td>
<td>{{ .Reembolso }}</td>
<td>{{ .Prenda }}</td>
<td>{{ .Investment }}</td>
<td>{{ .Adjustment }}</td>
<td>{{ .AdjustmentLiquid }}</td>
<td>{{ .Poupanca }}</td>
<td>{{ .PoupancaLiquid }}</td>
<td>{{ .RunningBalance }}</td>
<td>{{ .RunningBalanceLiquid }}</td>
</tr>
{{ else }}
<tr>
<td colspan="13" class="text-center text-muted">No monthly summary data available.</td>
</tr>
{{ end }}
</tbody>
</table>
</div>
</fieldset>
<fieldset>
<legend>PERIOD AVERAGES</legend>
</fieldset>
{{ end }}
+2
View File
@@ -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" }}
+5 -4
View File
@@ -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)
+7 -3
View File
@@ -1,10 +1,11 @@
# Download a production database's data
# Database stuff
## Download a production database's data
```bash
docker exec -i <container-name> \
pg_dump -U <db-user> -a -d <database> > 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`
+14 -12
View File
@@ -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,
}
}
+21
View File
@@ -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)
}
+50
View File
@@ -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,
}
}
+14
View File
@@ -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()
}
+39
View File
@@ -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),
}
}
+61
View File
@@ -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
}
@@ -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
+1 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// sqlc v1.31.1
package pgsqlc
+93 -1
View File
@@ -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",
@@ -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
}
+1 -1
View File
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// sqlc v1.31.1
package pgsqlc
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
@@ -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;
@@ -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;
-103
View File
@@ -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)
}
+48
View File
@@ -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
+25
View File
@@ -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)
}
+67
View File
@@ -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)
}