Show Account Balance

This commit is contained in:
Jan Bader 2021-12-02 21:29:11 +00:00
parent 276fdb4ade
commit 6f8a94ff5d
4 changed files with 19 additions and 9 deletions

View File

@ -9,7 +9,7 @@ import (
) )
type AccountData struct { type AccountData struct {
Accounts []postgres.Account Accounts []postgres.GetAccountsRow
} }
func (h *Handler) accounts(c *gin.Context) { func (h *Handler) accounts(c *gin.Context) {

View File

@ -29,20 +29,28 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A
} }
const getAccounts = `-- name: GetAccounts :many 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 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) rows, err := q.db.Query(ctx, getAccounts, budgetID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
var items []Account var items []GetAccountsRow
for rows.Next() { for rows.Next() {
var i Account var i GetAccountsRow
if err := rows.Scan(&i.ID, &i.BudgetID, &i.Name); err != nil { if err := rows.Scan(&i.ID, &i.Name, &i.Balance); err != nil {
return nil, err return nil, err
} }
items = append(items, i) items = append(items, i)

View File

@ -5,5 +5,7 @@ VALUES ($1, $2)
RETURNING *; RETURNING *;
-- name: GetAccounts :many -- name: GetAccounts :many
SELECT accounts.* FROM accounts SELECT accounts.id, accounts.name, SUM(transactions.amount) as balance FROM accounts
WHERE accounts.budget_id = $1; WHERE accounts.budget_id = $1
AND transactions.date < NOW()
GROUP BY accounts.id, accounts.name;

View File

@ -11,7 +11,7 @@
{{range .Accounts}} {{range .Accounts}}
<div class="budget-item"> <div class="budget-item">
<a href="account/{{.ID}}">{{.Name}}</a> <a href="account/{{.ID}}">{{.Name}}</a>
<span class="time"></span> <span class="time">{{.Balance}}</span>
</div> </div>
{{end}} {{end}}
{{end}} {{end}}