Use decimal.Decimal to represent floats more easily

This commit is contained in:
2025-08-10 14:00:20 +01:00
parent 528540a723
commit ba00980217
19 changed files with 92 additions and 67 deletions
+4 -2
View File
@@ -3,6 +3,8 @@ package cmd
import ( import (
"expenses/config" "expenses/config"
"expenses/pages" "expenses/pages"
"github.com/shopspring/decimal"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"fmt" "fmt"
@@ -22,8 +24,8 @@ var (
"formatDate": func(ts int64) string { "formatDate": func(ts int64) string {
return time.Unix(ts, 0).Format("02-Jan-2006") return time.Unix(ts, 0).Format("02-Jan-2006")
}, },
"formatPrice": func(v float64) string { "formatPrice": func(v decimal.Decimal) string {
return fmt.Sprintf("%.2f", v) return fmt.Sprintf("%s", v.Round(2).StringFixed(2))
}, },
} }
) )
@@ -2,9 +2,9 @@
-- expenses -- expenses
CREATE TABLE expenses_new ( CREATE TABLE expenses_new (
"ExpID" integer PRIMARY KEY AUTOINCREMENT, "ExpID" INTEGER PRIMARY KEY AUTOINCREMENT,
"Description" text NOT NULL, "Description" TEXT NOT NULL,
"Value" DECIMAL(10,2) NOT NULL DEFAULT 0, "Value" TEXT NOT NULL DEFAULT 0,
"StoreID" int NOT NULL DEFAULT 0, "StoreID" int NOT NULL DEFAULT 0,
"CategoryID" int NOT NULL DEFAULT 0, "CategoryID" int NOT NULL DEFAULT 0,
"OwnerUserID" int NOT NULL DEFAULT 0, "OwnerUserID" int NOT NULL DEFAULT 0,
@@ -25,7 +25,7 @@ CREATE TABLE expensesShares_new (
"ExpShareID" integer PRIMARY KEY AUTOINCREMENT, "ExpShareID" integer PRIMARY KEY AUTOINCREMENT,
"ExpID" int NOT NULL, "ExpID" int NOT NULL,
"UserID" int NOT NULL, "UserID" int NOT NULL,
"Share" DECIMAL(10,2) NOT NULL DEFAULT 0.5, "Share" TEXT NOT NULL DEFAULT 0.5,
FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT, FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT
); );
@@ -38,7 +38,7 @@ CREATE TABLE expensesPayments_new (
"ExpPaymID" integer PRIMARY KEY AUTOINCREMENT, "ExpPaymID" integer PRIMARY KEY AUTOINCREMENT,
"ExpID" int NOT NULL, "ExpID" int NOT NULL,
"UserID" int NOT NULL, "UserID" int NOT NULL,
"Payed" DECIMAL(10,2) NOT NULL DEFAULT 0, "Payed" TEXT NOT NULL DEFAULT 0,
FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT, FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT
); );
+2 -2
View File
@@ -163,7 +163,7 @@ VALUES(?, ?, ? , ?, ?, ?, ?, ?)
type InsertExpenseParams struct { type InsertExpenseParams struct {
Description string Description string
Value float64 Value string
StoreID int64 StoreID int64
CategoryID int64 CategoryID int64
TypeID int64 TypeID int64
@@ -200,7 +200,7 @@ WHERE "ExpID" = ?
type UpdateExpenseParams struct { type UpdateExpenseParams struct {
Description string Description string
Value float64 Value string
StoreID int64 StoreID int64
CategoryID int64 CategoryID int64
TypeID int64 TypeID int64
+3 -3
View File
@@ -12,7 +12,7 @@ type Category struct {
type Expense struct { type Expense struct {
ExpID int64 ExpID int64
Description string Description string
Value float64 Value string
StoreID int64 StoreID int64
CategoryID int64 CategoryID int64
OwnerUserID int64 OwnerUserID int64
@@ -30,14 +30,14 @@ type ExpensesPayment struct {
ExpPaymID int64 ExpPaymID int64
ExpID int64 ExpID int64
UserID int64 UserID int64
Payed float64 Payed string
} }
type ExpensesShare struct { type ExpensesShare struct {
ExpShareID int64 ExpShareID int64
ExpID int64 ExpID int64
UserID int64 UserID int64
Share float64 Share string
} }
type Store struct { type Store struct {
+2 -2
View File
@@ -74,7 +74,7 @@ VALUES(?, ?, ?)
type InsertPaymentParams struct { type InsertPaymentParams struct {
ExpID int64 ExpID int64
UserID int64 UserID int64
Payed float64 Payed string
} }
func (q *Queries) InsertPayment(ctx context.Context, arg InsertPaymentParams) (sql.Result, error) { func (q *Queries) InsertPayment(ctx context.Context, arg InsertPaymentParams) (sql.Result, error) {
@@ -89,7 +89,7 @@ WHERE "ExpPaymID" = ?
type UpdatePaymentParams struct { type UpdatePaymentParams struct {
UserID int64 UserID int64
Payed float64 Payed string
ExpPaymID int64 ExpPaymID int64
} }
+2 -2
View File
@@ -66,7 +66,7 @@ VALUES(?, ?, ?)
type InsertShareParams struct { type InsertShareParams struct {
ExpID int64 ExpID int64
UserID int64 UserID int64
Share float64 Share string
} }
func (q *Queries) InsertShare(ctx context.Context, arg InsertShareParams) (sql.Result, error) { func (q *Queries) InsertShare(ctx context.Context, arg InsertShareParams) (sql.Result, error) {
@@ -81,7 +81,7 @@ WHERE "ExpShareID" = ?
type UpdateShareParams struct { type UpdateShareParams struct {
UserID int64 UserID int64
Share float64 Share string
ExpShareID int64 ExpShareID int64
} }
-9
View File
@@ -11,12 +11,3 @@ sql:
expenseTypes: "ExpenseTypes" expenseTypes: "ExpenseTypes"
expenseShares: "ExpenseShares" expenseShares: "ExpenseShares"
expensePayments: "ExpensePayments" expensePayments: "ExpensePayments"
overrides:
- db_type: "float"
go_type:
import: "github.com/shopspring/decimal"
type: "DECIMAL"
- db_type: "DECIMAL"
go_type:
import: "github.com/shopspring/decimal"
type: "DECIMAL"
+7 -3
View File
@@ -2,20 +2,24 @@ package expenses
import ( import (
mod "expenses/expenses/models" mod "expenses/expenses/models"
"github.com/shopspring/decimal"
) )
type Debt struct { type Debt struct {
Debtor mod.User Debtor mod.User
Sum float64 Sum decimal.Decimal
} }
func sortBySum(a, b Debt) int { func sortBySum(a, b Debt) int {
if a.Sum < b.Sum { if a.Sum.LessThan(b.Sum) {
return -1 return -1
} }
if a.Sum > b.Sum {
if a.Sum.GreaterThan(b.Sum) {
return 1 return 1
} }
return 0 return 0
} }
+11 -8
View File
@@ -2,18 +2,20 @@ package expenses
import ( import (
mod "expenses/expenses/models" mod "expenses/expenses/models"
"github.com/shopspring/decimal"
) )
type DebtCalculator struct { type DebtCalculator struct {
Shares map[mod.User]float64 Shares map[mod.User]decimal.Decimal
Payments map[mod.User]float64 Payments map[mod.User]decimal.Decimal
Expense *mod.Expense Expense *mod.Expense
} }
func NewDebtCalculator(e *mod.Expense) *DebtCalculator { func NewDebtCalculator(e *mod.Expense) *DebtCalculator {
return &DebtCalculator{ return &DebtCalculator{
Shares: make(map[mod.User]float64), Shares: make(map[mod.User]decimal.Decimal),
Payments: make(map[mod.User]float64), Payments: make(map[mod.User]decimal.Decimal),
Expense: e, Expense: e,
} }
} }
@@ -21,13 +23,13 @@ func NewDebtCalculator(e *mod.Expense) *DebtCalculator {
func (dc *DebtCalculator) mapShares() { func (dc *DebtCalculator) mapShares() {
for _, share := range dc.Expense.Shares { for _, share := range dc.Expense.Shares {
dc.Shares[share.User] = share.Share dc.Shares[share.User] = share.Share
dc.Payments[share.User] = 0 dc.Payments[share.User] = decimal.NewFromInt(0)
} }
} }
func (dc *DebtCalculator) mapPayments() { func (dc *DebtCalculator) mapPayments() {
for _, payment := range dc.Expense.Payments { for _, payment := range dc.Expense.Payments {
dc.Payments[payment.User] += payment.PayedAmount dc.Payments[payment.User] = dc.Payments[payment.User].Add(payment.PayedAmount)
} }
} }
@@ -35,9 +37,10 @@ func (dc *DebtCalculator) getDebts() []Debt {
debts := []Debt{} debts := []Debt{}
for user := range dc.Payments { for user := range dc.Payments {
debt := (dc.Shares[user] * dc.Expense.Value) - dc.Payments[user] // debt := (dc.Shares[user] * dc.Expense.Value) - dc.Payments[user]
debt := (dc.Shares[user].Mul(dc.Expense.Value)).Sub(dc.Payments[user])
if debt > 0 { if debt.GreaterThan(decimal.NewFromInt(0)) {
debts = append(debts, Debt{Debtor: user, Sum: debt}) debts = append(debts, Debt{Debtor: user, Sum: debt})
} }
} }
+5 -4
View File
@@ -2,7 +2,8 @@ package expenses
import ( import (
mod "expenses/expenses/models" mod "expenses/expenses/models"
"strconv"
"github.com/shopspring/decimal"
) )
// TODO // TODO
@@ -13,12 +14,12 @@ func ParseFormPayments(userIDs []string, paymentsIDs []string,
values []string) ([]mod.ExpensePayment, error) { values []string) ([]mod.ExpensePayment, error) {
payments := []mod.ExpensePayment{} payments := []mod.ExpensePayment{}
for k := range userIDs { for k := range userIDs {
userID, err := strconv.ParseInt(userIDs[k], 10, 16) userID, err := ParseID(userIDs[k])
if err != nil { if err != nil {
return nil, err return nil, err
} }
payed, err := strconv.ParseFloat(values[k], 32) payed, err := decimal.NewFromString(values[k])
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -32,7 +33,7 @@ func ParseFormPayments(userIDs []string, paymentsIDs []string,
} }
if paymentsIDs[k] != "" { if paymentsIDs[k] != "" {
id, err := strconv.ParseInt(paymentsIDs[k], 10, 16) id, err := ParseID(paymentsIDs[k])
if err != nil { if err != nil {
return nil, err return nil, err
} }
+5 -5
View File
@@ -1,9 +1,9 @@
package expenses package expenses
import ( import (
"strconv"
mod "expenses/expenses/models" mod "expenses/expenses/models"
"github.com/shopspring/decimal"
) )
// TODO // TODO
@@ -14,12 +14,12 @@ func ParseFormShares(userIDs []string, shares []string, sharesIDs []string,
) ([]mod.ExpenseShare, error) { ) ([]mod.ExpenseShare, error) {
shareList := []mod.ExpenseShare{} shareList := []mod.ExpenseShare{}
for i := range userIDs { for i := range userIDs {
userID, err := strconv.ParseInt(userIDs[i], 10, 16) userID, err := ParseID(userIDs[i])
if err != nil { if err != nil {
return nil, err return nil, err
} }
share, err := strconv.ParseFloat(shares[i], 32) share, err := decimal.NewFromString(shares[i])
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -33,7 +33,7 @@ func ParseFormShares(userIDs []string, shares []string, sharesIDs []string,
} }
if sharesIDs[i] != "" { if sharesIDs[i] != "" {
id, err := strconv.ParseInt(sharesIDs[i], 10, 16) id, err := ParseID(sharesIDs[i])
if err != nil { if err != nil {
return nil, err return nil, err
} }
+6 -4
View File
@@ -7,12 +7,14 @@ import (
"database/sql" "database/sql"
"fmt" "fmt"
"github.com/shopspring/decimal"
) )
type Expense struct { type Expense struct {
ExpID int64 ExpID int64
Description string Description string
Value float64 Value decimal.Decimal
Store Store Store Store
Type Type Type Type
Category Category Category Category
@@ -27,7 +29,7 @@ func NewExpense() Expense {
return Expense{ return Expense{
ExpID: -1, ExpID: -1,
Description: "", Description: "",
Value: 0.0, Value: decimal.NewFromFloat(0.0),
Store: NewStore(), Store: NewStore(),
Category: NewCategory(), Category: NewCategory(),
Owner: NewUser(), Owner: NewUser(),
@@ -71,7 +73,7 @@ func (exp *Expense) Insert(tx *sql.Tx) error {
queries := repo.New(tx) queries := repo.New(tx)
res, err := queries.InsertExpense(ctx, repo.InsertExpenseParams{ res, err := queries.InsertExpense(ctx, repo.InsertExpenseParams{
Description: exp.Description, Description: exp.Description,
Value: exp.Value, Value: exp.Value.String(),
StoreID: exp.Store.StoreID, StoreID: exp.Store.StoreID,
CategoryID: exp.Category.CategoryID, CategoryID: exp.Category.CategoryID,
TypeID: exp.Type.TypeID, TypeID: exp.Type.TypeID,
@@ -137,7 +139,7 @@ func (e *Expense) Update(tx *sql.Tx) error {
res, err := queries.UpdateExpense(ctx, repo.UpdateExpenseParams{ res, err := queries.UpdateExpense(ctx, repo.UpdateExpenseParams{
ExpID: e.ExpID, ExpID: e.ExpID,
Description: e.Description, Description: e.Description,
Value: e.Value, Value: e.Value.String(),
StoreID: e.Store.StoreID, StoreID: e.Store.StoreID,
CategoryID: e.Category.CategoryID, CategoryID: e.Category.CategoryID,
TypeID: e.Type.TypeID, TypeID: e.Type.TypeID,
+8 -2
View File
@@ -1,11 +1,17 @@
package models package models
import repo "expenses/expenses/db/repository" import (
repo "expenses/expenses/db/repository"
"github.com/shopspring/decimal"
)
func mapRepoGetPaymentsRow(s repo.GetPaymentsRow) ExpensePayment { func mapRepoGetPaymentsRow(s repo.GetPaymentsRow) ExpensePayment {
payed, _ := decimal.NewFromString(s.ExpensesPayment.Payed)
return ExpensePayment{ return ExpensePayment{
ExpPaymID: s.ExpensesPayment.ExpPaymID, ExpPaymID: s.ExpensesPayment.ExpPaymID,
PayedAmount: s.ExpensesPayment.Payed, PayedAmount: payed,
User: User{ User: User{
UserID: s.User.UserID, UserID: s.User.UserID,
UserName: s.User.UserName, UserName: s.User.UserName,
+4 -3
View File
@@ -9,12 +9,13 @@ import (
"fmt" "fmt"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"github.com/shopspring/decimal"
) )
type ExpensePayment struct { type ExpensePayment struct {
ExpPaymID int64 ExpPaymID int64
User User User User
PayedAmount float64 PayedAmount decimal.Decimal
} }
func (e *Expense) GetPayments() error { func (e *Expense) GetPayments() error {
@@ -44,7 +45,7 @@ func (p *ExpensePayment) Insert(tx *sql.Tx, expID int64) error {
res, err := queries.InsertPayment(ctx, repo.InsertPaymentParams{ res, err := queries.InsertPayment(ctx, repo.InsertPaymentParams{
ExpID: expID, ExpID: expID,
UserID: p.User.UserID, UserID: p.User.UserID,
Payed: p.PayedAmount, Payed: p.PayedAmount.String(),
}) })
if err != nil { if err != nil {
return err return err
@@ -73,7 +74,7 @@ func (p *ExpensePayment) Update() error {
queries := repo.New(db) queries := repo.New(db)
res, err := queries.UpdatePayment(ctx, repo.UpdatePaymentParams{ res, err := queries.UpdatePayment(ctx, repo.UpdatePaymentParams{
ExpPaymID: p.ExpPaymID, ExpPaymID: p.ExpPaymID,
Payed: p.PayedAmount, Payed: p.PayedAmount.String(),
UserID: p.User.UserID, UserID: p.User.UserID,
}) })
if err != nil { if err != nil {
+11 -4
View File
@@ -1,12 +1,18 @@
package models package models
import repo "expenses/expenses/db/repository" import (
repo "expenses/expenses/db/repository"
"github.com/shopspring/decimal"
)
func mapRepoGetExpenseRow(e repo.GetExpenseRow) Expense { func mapRepoGetExpenseRow(e repo.GetExpenseRow) Expense {
value, _ := decimal.NewFromString(e.Expense.Value)
return Expense{ return Expense{
ExpID: e.Expense.ExpID, ExpID: e.Expense.ExpID,
Description: e.Expense.Description, Description: e.Expense.Description,
Value: e.Expense.Value, Value: value,
Store: Store{ Store: Store{
StoreID: e.Store.StoreID, StoreID: e.Store.StoreID,
StoreName: e.Store.StoreName, StoreName: e.Store.StoreName,
@@ -31,10 +37,12 @@ func mapRepoGetExpenseRow(e repo.GetExpenseRow) Expense {
} }
func mapRepoGetExpenseRowMulti(e repo.GetExpensesRow) Expense { func mapRepoGetExpenseRowMulti(e repo.GetExpensesRow) Expense {
value, _ := decimal.NewFromString(e.Expense.Value)
return Expense{ return Expense{
ExpID: e.Expense.ExpID, ExpID: e.Expense.ExpID,
Description: e.Expense.Description, Description: e.Expense.Description,
Value: e.Expense.Value, Value: value,
Store: Store{ Store: Store{
StoreID: e.Store.StoreID, StoreID: e.Store.StoreID,
StoreName: e.Store.StoreName, StoreName: e.Store.StoreName,
@@ -65,4 +73,3 @@ func mapRepoGetExpensesRows(er []repo.GetExpensesRow) []Expense {
} }
return expenses return expenses
} }
+4 -3
View File
@@ -10,12 +10,13 @@ import (
"fmt" "fmt"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"github.com/shopspring/decimal"
) )
type ExpenseShare struct { type ExpenseShare struct {
ExpShareID int64 ExpShareID int64
User User User User
Share float64 Share decimal.Decimal
} }
func (e *Expense) GetShares() error { func (e *Expense) GetShares() error {
@@ -44,7 +45,7 @@ func (sh *ExpenseShare) Insert(tx *sql.Tx, expID int64) error {
queries := repo.New(tx) queries := repo.New(tx)
res, err := queries.InsertShare(ctx, repo.InsertShareParams{ res, err := queries.InsertShare(ctx, repo.InsertShareParams{
ExpID: expID, ExpID: expID,
Share: sh.Share, Share: sh.Share.String(),
UserID: sh.User.UserID, UserID: sh.User.UserID,
}) })
if err != nil { if err != nil {
@@ -74,7 +75,7 @@ func (sh *ExpenseShare) Update() error {
queries := repo.New(db) queries := repo.New(db)
res, err := queries.UpdateShare(ctx, repo.UpdateShareParams{ res, err := queries.UpdateShare(ctx, repo.UpdateShareParams{
ExpShareID: sh.ExpShareID, ExpShareID: sh.ExpShareID,
Share: sh.Share, Share: sh.Share.String(),
UserID: sh.User.UserID, UserID: sh.User.UserID,
}) })
if err != nil { if err != nil {
+8 -2
View File
@@ -1,11 +1,17 @@
package models package models
import repo "expenses/expenses/db/repository" import (
repo "expenses/expenses/db/repository"
"github.com/shopspring/decimal"
)
func mapRepoGetSharesRow(s repo.GetSharesRow) ExpenseShare { func mapRepoGetSharesRow(s repo.GetSharesRow) ExpenseShare {
share, _ := decimal.NewFromString(s.ExpensesShare.Share)
return ExpenseShare{ return ExpenseShare{
ExpShareID: s.ExpensesShare.ExpShareID, ExpShareID: s.ExpensesShare.ExpShareID,
Share: s.ExpensesShare.Share, Share: share,
User: User{ User: User{
UserID: s.User.UserID, UserID: s.User.UserID,
UserName: s.User.UserName, UserName: s.User.UserName,
+2 -2
View File
@@ -3,10 +3,10 @@ package pages
import ( import (
"expenses/expenses" "expenses/expenses"
mod "expenses/expenses/models" mod "expenses/expenses/models"
"strconv"
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
) )
func processFormShares(c *gin.Context) ([]mod.ExpenseShare, error) { func processFormShares(c *gin.Context) ([]mod.ExpenseShare, error) {
@@ -36,7 +36,7 @@ func expenseFromForm(c *gin.Context) (*mod.Expense, error) {
date := formattedDate.Unix() date := formattedDate.Unix()
newValue := c.PostForm("expense-value") newValue := c.PostForm("expense-value")
value, err := strconv.ParseFloat(newValue, 32) value, err := decimal.NewFromString(newValue)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+3 -2
View File
@@ -8,6 +8,7 @@ import (
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
) )
type ExpenseDebtOverview struct { type ExpenseDebtOverview struct {
@@ -56,7 +57,7 @@ func getResults(c *gin.Context) {
} }
} }
userDebtSummary := make(map[mod.User]float64) userDebtSummary := make(map[mod.User]decimal.Decimal)
expensesWithDebts := []ExpenseDebtOverview{} expensesWithDebts := []ExpenseDebtOverview{}
for _, e := range queriedExpenses { for _, e := range queriedExpenses {
if len(e.Shares) <= 1 { if len(e.Shares) <= 1 {
@@ -77,7 +78,7 @@ func getResults(c *gin.Context) {
}) })
for _, debt := range expenseDebts { for _, debt := range expenseDebts {
userDebtSummary[debt.Debtor] += debt.Sum userDebtSummary[debt.Debtor] = userDebtSummary[debt.Debtor].Add(debt.Sum)
} }
} }