Extract package

This commit is contained in:
Jan Bader 2022-02-23 21:30:28 +00:00
parent d89a8f4e2e
commit 28c20aacd3
11 changed files with 81 additions and 69 deletions

View File

@ -6,6 +6,7 @@ package postgres
import (
"context"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -97,7 +98,7 @@ type GetAccountsWithBalanceRow struct {
ID uuid.UUID
Name string
OnBudget bool
Balance Numeric
Balance numeric.Numeric
}
func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsWithBalanceRow, error) {

View File

@ -7,6 +7,7 @@ import (
"context"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -21,7 +22,7 @@ RETURNING id, category_id, date, memo, amount
type CreateAssignmentParams struct {
Date time.Time
Amount Numeric
Amount numeric.Numeric
CategoryID uuid.UUID
}
@ -65,7 +66,7 @@ type GetAllAssignmentsRow struct {
Date time.Time
Category string
Group string
Amount Numeric
Amount numeric.Numeric
}
func (q *Queries) GetAllAssignments(ctx context.Context, budgetID uuid.UUID) ([]GetAllAssignmentsRow, error) {

View File

@ -7,6 +7,7 @@ import (
"context"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -23,10 +24,10 @@ ORDER BY COALESCE(ass.date, tra.date), COALESCE(ass.category_id, tra.category_id
type GetCumultativeBalancesRow struct {
Date time.Time
CategoryID uuid.UUID
Assignments Numeric
AssignmentsCum Numeric
Transactions Numeric
TransactionsCum Numeric
Assignments numeric.Numeric
AssignmentsCum numeric.Numeric
Transactions numeric.Numeric
TransactionsCum numeric.Numeric
}
func (q *Queries) GetCumultativeBalances(ctx context.Context, budgetID uuid.UUID) ([]GetCumultativeBalancesRow, error) {

View File

@ -7,6 +7,7 @@ import (
"fmt"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -42,7 +43,7 @@ type Assignment struct {
CategoryID uuid.UUID
Date time.Time
Memo sql.NullString
Amount Numeric
Amount numeric.Numeric
}
type AssignmentsByMonth struct {
@ -81,7 +82,7 @@ type Transaction struct {
ID uuid.UUID
Date time.Time
Memo string
Amount Numeric
Amount numeric.Numeric
AccountID uuid.UUID
CategoryID uuid.NullUUID
PayeeID uuid.NullUUID

View File

@ -1,8 +1,10 @@
package postgres
package numeric
import (
"fmt"
"math/big"
"strings"
"unicode/utf8"
"github.com/jackc/pgtype"
)
@ -11,7 +13,7 @@ type Numeric struct {
pgtype.Numeric
}
func NewZeroNumeric() Numeric {
func Zero() Numeric {
return Numeric{pgtype.Numeric{Exp: 0, Int: big.NewInt(0), Status: pgtype.Present, NaN: false}}
}
@ -165,3 +167,27 @@ func (n Numeric) MarshalJSON() ([]byte, error) {
bytesWithSeparator = append(bytesWithSeparator, bytes[split:]...)
return bytesWithSeparator, nil
}
func Parse(text string) (Numeric, error) {
// Remove trailing currency
text = trimLastChar(text)
// Unify decimal separator
text = strings.Replace(text, ",", ".", 1)
num := Numeric{}
err := num.Set(text)
if err != nil {
return num, fmt.Errorf("parse numeric %s: %w", text, err)
}
return num, nil
}
func trimLastChar(s string) string {
r, size := utf8.DecodeLastRuneInString(s)
if r == utf8.RuneError && (size == 0 || size == 1) {
size = 0
}
return s[:len(s)-size]
}

View File

@ -7,6 +7,7 @@ import (
"context"
"time"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -20,7 +21,7 @@ RETURNING id, date, memo, amount, account_id, category_id, payee_id, group_id, s
type CreateTransactionParams struct {
Date time.Time
Memo string
Amount Numeric
Amount numeric.Numeric
AccountID uuid.UUID
PayeeID uuid.NullUUID
CategoryID uuid.NullUUID
@ -95,7 +96,7 @@ type GetAllTransactionsForBudgetRow struct {
ID uuid.UUID
Date time.Time
Memo string
Amount Numeric
Amount numeric.Numeric
GroupID uuid.NullUUID
Status TransactionStatus
Account string
@ -222,7 +223,7 @@ type GetTransactionsForAccountRow struct {
ID uuid.UUID
Date time.Time
Memo string
Amount Numeric
Amount numeric.Numeric
GroupID uuid.NullUUID
Status TransactionStatus
Account string
@ -281,7 +282,7 @@ WHERE id = $7
type UpdateTransactionParams struct {
Date time.Time
Memo string
Amount Numeric
Amount numeric.Numeric
AccountID uuid.UUID
PayeeID uuid.NullUUID
CategoryID uuid.NullUUID

View File

@ -6,6 +6,7 @@ import (
"fmt"
"io"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -43,8 +44,8 @@ func (ynab *YNABExport) ExportAssignments(context context.Context, w io.Writer)
assignment.Group,
assignment.Category,
assignment.Amount.String() + "€",
NewZeroNumeric().String() + "€",
NewZeroNumeric().String() + "€",
numeric.Zero().String() + "€",
numeric.Zero().String() + "€",
}
err := csv.Write(row)
@ -129,9 +130,9 @@ func GetTransactionRow(transaction GetAllTransactionsForBudgetRow) []string {
row = append(row, transaction.Memo)
if transaction.Amount.IsPositive() {
row = append(row, NewZeroNumeric().String()+"€", transaction.Amount.String()+"€")
row = append(row, numeric.Zero().String()+"€", transaction.Amount.String()+"€")
} else {
row = append(row, transaction.Amount.String()[1:]+"€", NewZeroNumeric().String()+"€")
row = append(row, transaction.Amount.String()[1:]+"€", numeric.Zero().String()+"€")
}
return append(row, string(transaction.Status))

View File

@ -7,8 +7,8 @@ import (
"io"
"strings"
"time"
"unicode/utf8"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/google/uuid"
)
@ -242,7 +242,7 @@ func (ynab *YNABImport) ImportRegularTransaction(context context.Context, payeeN
func (ynab *YNABImport) ImportTransferTransaction(context context.Context, payeeName string,
transaction CreateTransactionParams, openTransfers *[]Transfer,
account *Account, amount Numeric) error {
account *Account, amount numeric.Numeric) error {
transferToAccountName := payeeName[11:]
transferToAccount, err := ynab.GetAccount(context, transferToAccountName)
if err != nil {
@ -295,34 +295,10 @@ func (ynab *YNABImport) ImportTransferTransaction(context context.Context, payee
return nil
}
func trimLastChar(s string) string {
r, size := utf8.DecodeLastRuneInString(s)
if r == utf8.RuneError && (size == 0 || size == 1) {
size = 0
}
return s[:len(s)-size]
}
func ParseNumeric(text string) (Numeric, error) {
// Remove trailing currency
text = trimLastChar(text)
// Unify decimal separator
text = strings.Replace(text, ",", ".", 1)
num := Numeric{}
err := num.Set(text)
func GetAmount(inflow string, outflow string) (numeric.Numeric, error) {
in, err := numeric.Parse(inflow)
if err != nil {
return num, fmt.Errorf("parse numeric %s: %w", text, err)
}
return num, nil
}
func GetAmount(inflow string, outflow string) (Numeric, error) {
in, err := ParseNumeric(inflow)
if err != nil {
return in, err
return in, fmt.Errorf("parse inflow: %w", err)
}
if !in.IsZero() {
@ -330,9 +306,9 @@ func GetAmount(inflow string, outflow string) (Numeric, error) {
}
// if inflow is zero, use outflow
out, err := ParseNumeric("-" + outflow)
out, err := numeric.Parse("-" + outflow)
if err != nil {
return out, err
return out, fmt.Errorf("parse outflow: %w", err)
}
return out, nil
}

View File

@ -7,6 +7,7 @@ import (
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
@ -24,19 +25,19 @@ func getFirstOfMonthTime(date time.Time) time.Time {
type CategoryWithBalance struct {
*postgres.GetCategoriesRow
Available postgres.Numeric
AvailableLastMonth postgres.Numeric
Activity postgres.Numeric
Assigned postgres.Numeric
Available numeric.Numeric
AvailableLastMonth numeric.Numeric
Activity numeric.Numeric
Assigned numeric.Numeric
}
func NewCategoryWithBalance(category *postgres.GetCategoriesRow) CategoryWithBalance {
return CategoryWithBalance{
GetCategoriesRow: category,
Available: postgres.NewZeroNumeric(),
AvailableLastMonth: postgres.NewZeroNumeric(),
Activity: postgres.NewZeroNumeric(),
Assigned: postgres.NewZeroNumeric(),
Available: numeric.Zero(),
AvailableLastMonth: numeric.Zero(),
Activity: numeric.Zero(),
Assigned: numeric.Zero(),
}
}
@ -101,15 +102,15 @@ func (h *Handler) budgetingForMonth(c *gin.Context) {
data := struct {
Categories []CategoryWithBalance
AvailableBalance postgres.Numeric
AvailableBalance numeric.Numeric
}{categoriesWithBalance, availableBalance}
c.JSON(http.StatusOK, data)
}
func (*Handler) getAvailableBalance(categories []postgres.GetCategoriesRow, budget postgres.Budget,
moneyUsed postgres.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow,
firstOfNextMonth time.Time) postgres.Numeric {
availableBalance := postgres.NewZeroNumeric()
moneyUsed numeric.Numeric, cumultativeBalances []postgres.GetCumultativeBalancesRow,
firstOfNextMonth time.Time) numeric.Numeric {
availableBalance := numeric.Zero()
for _, cat := range categories {
if cat.ID != budget.IncomeCategoryID {
continue
@ -161,10 +162,10 @@ func (h *Handler) budgeting(c *gin.Context) {
func (h *Handler) calculateBalances(budget postgres.Budget,
firstOfNextMonth time.Time, firstOfMonth time.Time, categories []postgres.GetCategoriesRow,
cumultativeBalances []postgres.GetCumultativeBalancesRow) ([]CategoryWithBalance, postgres.Numeric) {
cumultativeBalances []postgres.GetCumultativeBalancesRow) ([]CategoryWithBalance, numeric.Numeric) {
categoriesWithBalance := []CategoryWithBalance{}
moneyUsed := postgres.NewZeroNumeric()
moneyUsed := numeric.Zero()
for i := range categories {
cat := &categories[i]
// do not show hidden categories
@ -183,7 +184,7 @@ func (h *Handler) calculateBalances(budget postgres.Budget,
func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow,
cumultativeBalances []postgres.GetCumultativeBalancesRow, firstOfNextMonth time.Time,
moneyUsed *postgres.Numeric, firstOfMonth time.Time, budget postgres.Budget) CategoryWithBalance {
moneyUsed *numeric.Numeric, firstOfMonth time.Time, budget postgres.Budget) CategoryWithBalance {
categoryWithBalance := NewCategoryWithBalance(cat)
for _, bal := range cumultativeBalances {
if bal.CategoryID != cat.ID {
@ -200,7 +201,7 @@ func (*Handler) CalculateCategoryBalances(cat *postgres.GetCategoriesRow,
categoryWithBalance.Available = categoryWithBalance.Available.Add(bal.Transactions)
if !categoryWithBalance.Available.IsPositive() && bal.Date.Before(firstOfMonth) {
*moneyUsed = moneyUsed.Add(categoryWithBalance.Available)
categoryWithBalance.Available = postgres.NewZeroNumeric()
categoryWithBalance.Available = numeric.Zero()
}
if bal.Date.Before(firstOfMonth) {

View File

@ -6,6 +6,7 @@ import (
"time"
"git.javil.eu/jacob1123/budgeteer/postgres"
"git.javil.eu/jacob1123/budgeteer/postgres/numeric"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
@ -35,7 +36,7 @@ func (h *Handler) newTransaction(c *gin.Context) {
return
}
amount := postgres.Numeric{}
amount := numeric.Numeric{}
err = amount.Set(payload.Amount)
if err != nil {
c.AbortWithError(http.StatusBadRequest, fmt.Errorf("amount: %w", err))

View File

@ -7,9 +7,11 @@ packages:
queries: "postgres/queries/"
overrides:
- go_type:
type: "Numeric"
import: "git.javil.eu/jacob1123/budgeteer/postgres/numeric"
type: Numeric
db_type: "pg_catalog.numeric"
- go_type:
type: "Numeric"
import: "git.javil.eu/jacob1123/budgeteer/postgres/numeric"
type: Numeric
db_type: "pg_catalog.numeric"
nullable: true