diff --git a/http/accounts.go b/http/accounts.go index 7c7383d..53934d7 100644 --- a/http/accounts.go +++ b/http/accounts.go @@ -9,7 +9,7 @@ import ( ) type AccountData struct { - Accounts []postgres.Account + Accounts []postgres.GetAccountsRow } func (h *Handler) accounts(c *gin.Context) { diff --git a/postgres/accounts.sql.go b/postgres/accounts.sql.go index d865584..382aecc 100644 --- a/postgres/accounts.sql.go +++ b/postgres/accounts.sql.go @@ -29,20 +29,28 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A } const getAccounts = `-- name: GetAccounts :many -SELECT accounts.id, accounts.budget_id, accounts.name FROM accounts +SELECT accounts.id, accounts.name, SUM(transactions.amount) as balance FROM accounts WHERE accounts.budget_id = $1 +AND transactions.date < NOW() +GROUP BY accounts.id, accounts.name ` -func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Account, error) { +type GetAccountsRow struct { + ID uuid.UUID + Name string + Balance int64 +} + +func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsRow, error) { rows, err := q.db.Query(ctx, getAccounts, budgetID) if err != nil { return nil, err } defer rows.Close() - var items []Account + var items []GetAccountsRow for rows.Next() { - var i Account - if err := rows.Scan(&i.ID, &i.BudgetID, &i.Name); err != nil { + var i GetAccountsRow + if err := rows.Scan(&i.ID, &i.Name, &i.Balance); err != nil { return nil, err } items = append(items, i) diff --git a/postgres/queries/accounts.sql b/postgres/queries/accounts.sql index 663fd3e..62e502e 100644 --- a/postgres/queries/accounts.sql +++ b/postgres/queries/accounts.sql @@ -5,5 +5,7 @@ VALUES ($1, $2) RETURNING *; -- name: GetAccounts :many -SELECT accounts.* FROM accounts -WHERE accounts.budget_id = $1; \ No newline at end of file +SELECT accounts.id, accounts.name, SUM(transactions.amount) as balance FROM accounts +WHERE accounts.budget_id = $1 +AND transactions.date < NOW() +GROUP BY accounts.id, accounts.name; \ No newline at end of file diff --git a/web/accounts.html b/web/accounts.html index 6cb4219..7ff29da 100644 --- a/web/accounts.html +++ b/web/accounts.html @@ -11,7 +11,7 @@ {{range .Accounts}}