Cleaning some warnings

This commit is contained in:
2025-09-15 19:12:14 +01:00
parent 3514adbea9
commit 27d409ed96
32 changed files with 1292 additions and 184 deletions
+2
View File
@@ -0,0 +1,2 @@
registry=dir.esilva.org
repo=esilva
+11
View File
@@ -0,0 +1,11 @@
version: "2"
linters:
default: all
disable:
- wsl
- depguard
- varnamelen
- wrapcheck
- wsl_v5
- exhaustruct
- gochecknoglobals
+1
View File
@@ -1,3 +1,4 @@
// package api will handle the JSON REST API responsabilities
package api
import "github.com/gin-gonic/gin"
+1
View File
@@ -22,6 +22,7 @@ func getAllTypes(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"users": types})
}
// RouteTypes will route the endpoints for the types resources
func RouteTypes(router *gin.RouterGroup) {
router.GET("types", getAllTypes)
}
+1
View File
@@ -22,6 +22,7 @@ func getAllUsers(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"users": users})
}
// RouteUsers will route the endpoints for the users resources
func RouteUsers(router *gin.RouterGroup) {
router.GET("users", getAllUsers)
}
+2
View File
@@ -5,6 +5,7 @@ import (
"strings"
expauth "expenses/expenses/auth"
"github.com/gin-gonic/gin"
)
@@ -12,6 +13,7 @@ type TokenData struct {
Token string `json:"JWTToken"`
}
// APIAuhtMiddleWare will handle this API authentication
func APIAuthMiddleWare() gin.HandlerFunc {
return func(c *gin.Context) {
auth := c.GetHeader("Authorization")
+26 -17
View File
@@ -1,17 +1,20 @@
// Package expenses will be the core of the expenses splitter webapp's functionalities
package expenses
import (
"context"
"expenses/config"
"expenses/expenses/repo"
"log"
"strings"
"expenses/config"
"expenses/expenses/repo"
"github.com/jackc/pgx/v5/pgxpool"
lua "github.com/yuin/gopher-lua"
)
type ExpensesApp struct {
// ExpApp is the data structure for the main runtime of this application.
type ExpApp struct {
Lua *lua.LState
ExpRepo repo.ExpenseRepository
CategoryRepo repo.CategoryRepository
@@ -21,29 +24,33 @@ type ExpensesApp struct {
}
var (
App *ExpensesApp
// App provides access to the expenses main service.
App *ExpApp
)
func NewExpenseApp(db *pgxpool.Pool, luaVM *lua.LState) *ExpensesApp {
return &ExpensesApp{
ExpRepo: repo.NewPgExpRepo(db),
CategoryRepo: repo.NewPgCatRepo(db),
UserRepo: repo.NewPgUserRepo(db),
StoreRepo: repo.NewPgStoreRepo(db),
TypeRepo: repo.NewPgTypeRepo(db),
// 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,
}
}
func (a *ExpensesApp) Close() {
// TODO
// Close the repos?
// Close will close this ExpApp instance.
func (a *ExpApp) Close() {
// TODO - Close the repos?
a.Lua.Close()
}
func StartLuaVM() (*lua.LState, error) {
// startLuaVM creates the LuaVM we require to run our custom scripts.
func startLuaVM() (*lua.LState, error) {
L := lua.NewState()
App.registerLuaBinds(L)
return L, nil
}
@@ -75,7 +82,8 @@ func runMigrations(luaVM *lua.LState) error {
return nil
}
func (a *ExpensesApp) GoToMigration(id uint) error {
// GoToMigration provides a way to force moving to the specified migration.
func (a *ExpApp) GoToMigration(id uint) error {
migrator, err := repo.NewPgMigrator()
if err != nil {
return err
@@ -84,6 +92,7 @@ func (a *ExpensesApp) GoToMigration(id uint) error {
return migrator.Goto(id)
}
// StartApp will configure and open the required connections to run this app.
func StartApp() error {
config.SetConfig("./config.yaml")
cfg := config.GetInstance()
@@ -91,7 +100,7 @@ func StartApp() error {
pgStr := getPgConnString(cfg)
// Create the LuaVM
luaVM, err := StartLuaVM()
luaVM, err := startLuaVM()
if err != nil {
return err
}
+2
View File
@@ -11,6 +11,8 @@ import (
mod "expenses/expenses/models"
)
// AuthMiddleware is the middleware we will use to verify if a user is
// authenticated or not
func AuthMiddleware() gin.HandlerFunc {
log.Println("Are we authing?")
return func(c *gin.Context) {
+12 -5
View File
@@ -5,16 +5,20 @@ import (
mod "expenses/expenses/models"
)
func (a *ExpensesApp) GetAllCategories(ctx context.Context) ([]mod.Category, error) {
// GetAllCategories returns all categories.
func (a *ExpApp) GetAllCategories(ctx context.Context) ([]mod.Category, error) {
return a.CategoryRepo.GetAll(ctx)
}
func (a *ExpensesApp) GetCategory(id int32) (mod.Category, error) {
// GetCategory returns a category by its ID.
func (a *ExpApp) GetCategory(id int32) (mod.Category, error) {
ctx := context.Background()
return a.CategoryRepo.Get(ctx, id)
}
func (a *ExpensesApp) CreateCategory(name string) error {
// CreateCategory creates a new category.
func (a *ExpApp) CreateCategory(name string) error {
ctx := context.Background()
newCat := mod.Category{
@@ -24,7 +28,8 @@ func (a *ExpensesApp) CreateCategory(name string) error {
return a.CategoryRepo.Insert(ctx, newCat)
}
func (a *ExpensesApp) UpdateCategory(id int32, name string) error {
// UpdateCategory updates a category by its ID.
func (a *ExpApp) UpdateCategory(id int32, name string) error {
ctx := context.Background()
cat := mod.Category{
@@ -35,7 +40,9 @@ func (a *ExpensesApp) UpdateCategory(id int32, name string) error {
return a.CategoryRepo.Update(ctx, cat)
}
func (a *ExpensesApp) DeleteCategory(id int32) error {
// DeleteCategory deletes a category by its ID.
func (a *ExpApp) DeleteCategory(id int32) error {
ctx := context.Background()
return a.CategoryRepo.Delete(ctx, id)
}
+2 -2
View File
@@ -1,8 +1,8 @@
// Package errors package will have custom errors for the expenses package
package errors
import "fmt"
var (
ErrNotFound = fmt.Errorf("not found")
ErrNotFound = fmt.Errorf("not found") // ErrNotFound is used for not found data
)
+24 -19
View File
@@ -8,19 +8,24 @@ import (
dec "github.com/shopspring/decimal"
)
type UserTab struct {
// userTab describes the tab a given user has.
type userTab struct {
User mod.User
Sum dec.Decimal
}
type UserTabs []UserTab
func (ut UserTabs) SortBySum() {
// userTabs is a list of UserTab.
type userTabs []userTab
// SortBySum sorts the list of UserTab by the attrib Sum.
func (ut userTabs) SortBySum() {
sort.Slice(ut, func(i, j int) bool {
return ut[i].Sum.Cmp(ut[j].Sum) > 0
})
}
func (ut UserTabs) Equal(t UserTabs) bool {
// Equal returns the equality of the passed UserTab.
func (ut userTabs) Equal(t userTabs) bool {
if len(ut) != len(t) {
return false
}
@@ -34,24 +39,24 @@ func (ut UserTabs) Equal(t UserTabs) bool {
return true
}
func filterExpenseParticipants(e *mod.Expense) (UserTabs, UserTabs) {
func filterExpenseParticipants(e *mod.Expense) (userTabs, userTabs) {
shares := mapShares(e)
payments := mapPayments(e)
debtors := UserTabs{}
creditors := UserTabs{}
debtors := userTabs{}
creditors := userTabs{}
for user, share := range shares {
debt := share.Sub(payments[user])
if debt.LessThan(dec.NewFromFloat(0.0)) {
creditors = append(creditors, UserTab{
creditors = append(creditors, userTab{
User: user,
Sum: debt.Abs(),
})
}
if debt.GreaterThan(dec.NewFromFloat(0.0)) {
debtors = append(debtors, UserTab{
debtors = append(debtors, userTab{
User: user,
Sum: debt.Abs(),
})
@@ -66,13 +71,13 @@ func filterExpenseParticipants(e *mod.Expense) (UserTabs, UserTabs) {
// TODO
// Instead of doing this impererively (I think?) create a struct that can
// handle doing the accounting while collecting the data instead
type CompoundKey struct {
// handle doing the accounting while collecting the data instead.
type compoundeKey struct {
Debtor mod.User
Creditor mod.User
}
func resolveDebt(creditor UserTab, debtors UserTabs) mod.Debts {
func resolveDebt(creditor userTab, debtors userTabs) mod.Debts {
debts := mod.Debts{}
credit := creditor.Sum
@@ -101,14 +106,14 @@ func resolveDebt(creditor UserTab, debtors UserTabs) mod.Debts {
return debts
}
func resolveDebts(debtors UserTabs, creditors UserTabs) mod.Debts {
keyedDebts := make(map[CompoundKey]dec.Decimal)
func resolveDebts(debtors userTabs, creditors userTabs) mod.Debts {
keyedDebts := make(map[compoundeKey]dec.Decimal)
for _, creditor := range creditors {
debt := resolveDebt(creditor, debtors)
for _, d := range debt {
key := CompoundKey{Debtor: d.Debtor, Creditor: d.Creditor}
key := compoundeKey{Debtor: d.Debtor, Creditor: d.Creditor}
if _, ok := keyedDebts[key]; ok {
keyedDebts[key] = keyedDebts[key].Add(d.Sum)
} else {
@@ -149,16 +154,16 @@ func CalculateDebts(e *mod.Expense) (mod.Debts, error) {
// This won't work if the payment was made with multiple payments - but for my
// use case that won't be a thing. Right now every expense I introduce has been
// fully payed in one go
func (a *ExpensesApp) settleDebt(payment mod.Payment,
credit mod.Payment, eId int32) error {
func (a *ExpApp) settleDebt(payment mod.Payment,
credit mod.Payment, eID int32) error {
ctx := context.Background()
credit.PayedAmount = credit.PayedAmount.Sub(payment.PayedAmount)
return a.ExpRepo.SettleDebt(ctx, eId, payment, credit)
return a.ExpRepo.SettleDebt(ctx, eID, payment, credit)
}
func (a *ExpensesApp) ProcessDebt(expID int32, debt mod.Debt) error {
func (a *ExpApp) ProcessDebt(expID int32, debt mod.Debt) error {
// We have to balance the debtor and creditor payments
payment := mod.Payment{
User: mod.User{
+26 -26
View File
@@ -21,32 +21,32 @@ func NewDebtCalculator(e *mod.Expense) *DebtCalculator {
}
// TODO
// This code will be replicated in the expenses controller but without
// This code will be replicated in the expenses controller but without
// the dc
func (dc *DebtCalculator) mapShares() {
for _, share := range dc.Expense.Shares {
dc.Shares[share.User] = share.Share
dc.Payments[share.User] = decimal.NewFromInt(0)
}
}
// func (dc *DebtCalculator) mapShares() {
// for _, share := range dc.Expense.Shares {
// dc.Shares[share.User] = share.Share
// dc.Payments[share.User] = decimal.NewFromInt(0)
// }
// }
func (dc *DebtCalculator) mapPayments() {
for _, payment := range dc.Expense.Payments {
dc.Payments[payment.User] = dc.Payments[payment.User].Add(payment.PayedAmount)
}
}
// func (dc *DebtCalculator) mapPayments() {
// for _, payment := range dc.Expense.Payments {
// dc.Payments[payment.User] = dc.Payments[payment.User].Add(payment.PayedAmount)
// }
// }
func (dc *DebtCalculator) getDebts() []mod.Debt {
debts := []mod.Debt{}
for user := range dc.Payments {
// debt := (dc.Shares[user] * dc.Expense.Value) - dc.Payments[user]
debt := (dc.Shares[user].Mul(dc.Expense.Value)).Sub(dc.Payments[user])
if debt.GreaterThan(decimal.NewFromInt(0)) {
debts = append(debts, mod.Debt{Debtor: user, Sum: debt})
}
}
return debts
}
// func (dc *DebtCalculator) getDebts() []mod.Debt {
// debts := []mod.Debt{}
//
// for user := range dc.Payments {
// // debt := (dc.Shares[user] * dc.Expense.Value) - dc.Payments[user]
// debt := (dc.Shares[user].Mul(dc.Expense.Value)).Sub(dc.Payments[user])
//
// if debt.GreaterThan(decimal.NewFromInt(0)) {
// debts = append(debts, mod.Debt{Debtor: user, Sum: debt})
// }
// }
//
// return debts
// }
+14 -14
View File
@@ -143,20 +143,20 @@ var (
},
}
expense4 = mod.Expense{
ExpID: 7,
Value: dec.NewFromFloat(0.50),
Shares: []mod.Share{
{ExpShareID: 0, User: user1, Share: dec.NewFromFloat(0.34)},
{ExpShareID: 1, User: user2, Share: dec.NewFromFloat(0.33)},
{ExpShareID: 2, User: user3, Share: dec.NewFromFloat(0.33)},
},
Payments: []mod.Payment{
{ExpPaymID: 0, User: user1, PayedAmount: dec.NewFromFloat(0.18)},
{ExpPaymID: 1, User: user1, PayedAmount: dec.NewFromFloat(0.16)},
{ExpPaymID: 2, User: user2, PayedAmount: dec.NewFromFloat(0.16)},
},
}
// expense4 = mod.Expense{
// ExpID: 7,
// Value: dec.NewFromFloat(0.50),
// Shares: []mod.Share{
// {ExpShareID: 0, User: user1, Share: dec.NewFromFloat(0.34)},
// {ExpShareID: 1, User: user2, Share: dec.NewFromFloat(0.33)},
// {ExpShareID: 2, User: user3, Share: dec.NewFromFloat(0.33)},
// },
// Payments: []mod.Payment{
// {ExpPaymID: 0, User: user1, PayedAmount: dec.NewFromFloat(0.18)},
// {ExpPaymID: 1, User: user1, PayedAmount: dec.NewFromFloat(0.16)},
// {ExpPaymID: 2, User: user2, PayedAmount: dec.NewFromFloat(0.16)},
// },
// }
expense5 = mod.Expense{
ExpID: 9,
+16 -16
View File
@@ -12,17 +12,17 @@ func TestFilterExpenseParticipants(t *testing.T) {
testCases := []struct {
name string
exp *mod.Expense
expectedDebtors UserTabs
expectedCreditors UserTabs
expectedDebtors userTabs
expectedCreditors userTabs
}{
{
name: "Expense something something",
exp: &expense2,
expectedCreditors: UserTabs{
expectedCreditors: userTabs{
{User: user1, Sum: dec.NewFromFloat(32.0)},
{User: user3, Sum: dec.NewFromFloat(22.0)},
},
expectedDebtors: UserTabs{
expectedDebtors: userTabs{
{User: user2, Sum: dec.NewFromFloat(43.0)},
{User: user4, Sum: dec.NewFromFloat(11.0)},
},
@@ -30,10 +30,10 @@ func TestFilterExpenseParticipants(t *testing.T) {
{
name: "Expense cents",
exp: &expense6,
expectedCreditors: UserTabs{
expectedCreditors: userTabs{
{User: user1, Sum: dec.NewFromFloat(0.32)},
},
expectedDebtors: UserTabs{
expectedDebtors: userTabs{
{User: user2, Sum: dec.NewFromFloat(0.16)},
{User: user3, Sum: dec.NewFromFloat(0.16)},
},
@@ -59,18 +59,18 @@ func TestFilterExpenseParticipants(t *testing.T) {
func TestResolveDebt_ExactDebtsForCredit(t *testing.T) {
// Test1:
// Debt is solvable
debtors := UserTabs{
debtors := userTabs{
{User: user1, Sum: dec.NewFromFloat(10.0)},
{User: user2, Sum: dec.NewFromFloat(10.0)},
{User: user3, Sum: dec.NewFromFloat(10.0)},
}
creditor := UserTab{User: user4, Sum: dec.NewFromFloat(30.0)}
creditor := userTab{User: user4, Sum: dec.NewFromFloat(30.0)}
expectedDebts := mod.Debts{
{Creditor: user4, Debtor: user1, Sum: dec.NewFromFloat(10.0)},
{Creditor: user4, Debtor: user2, Sum: dec.NewFromFloat(10.0)},
{Creditor: user4, Debtor: user3, Sum: dec.NewFromFloat(10.0)},
}
expectedDebtors := UserTabs{
expectedDebtors := userTabs{
{User: user1, Sum: dec.NewFromFloat(0.0)},
{User: user2, Sum: dec.NewFromFloat(0.0)},
{User: user3, Sum: dec.NewFromFloat(0.0)},
@@ -92,11 +92,11 @@ func TestResolveDebt_ExactDebtsForCredit(t *testing.T) {
func TestResolveDebt_LessDebtsThanCredit(t *testing.T) {
// Test2:
// Debt is not solvable:
debtors := UserTabs{
debtors := userTabs{
{User: user1, Sum: dec.NewFromFloat(10.0)},
{User: user2, Sum: dec.NewFromFloat(10.0)},
}
creditor := UserTab{User: user4, Sum: dec.NewFromFloat(30.0)}
creditor := userTab{User: user4, Sum: dec.NewFromFloat(30.0)}
expectedDebts := mod.Debts{
{Creditor: user4, Debtor: user1, Sum: dec.NewFromFloat(10.0)},
{Creditor: user4, Debtor: user2, Sum: dec.NewFromFloat(10.0)},
@@ -111,12 +111,12 @@ func TestResolveDebt_LessDebtsThanCredit(t *testing.T) {
}
func TestResolveDebt_EnoughDebtsForCredit(t *testing.T) {
debtors := UserTabs{
debtors := userTabs{
{User: user1, Sum: dec.NewFromFloat(10.0)},
{User: user2, Sum: dec.NewFromFloat(10.0)},
{User: user3, Sum: dec.NewFromFloat(10.0)},
}
creditor := UserTab{User: user4, Sum: dec.NewFromFloat(10.0)}
creditor := userTab{User: user4, Sum: dec.NewFromFloat(10.0)}
expectedDebts := mod.Debts{
{Creditor: user4, Debtor: user1, Sum: dec.NewFromFloat(10.0)},
}
@@ -130,13 +130,13 @@ func TestResolveDebt_EnoughDebtsForCredit(t *testing.T) {
}
func TestResolveDebt_RenameMe(t *testing.T) {
debtors := UserTabs{
debtors := userTabs{
{User: user1, Sum: dec.NewFromFloat(10.0)},
}
expectedDebtors := UserTabs{
expectedDebtors := userTabs{
{User: user1, Sum: dec.NewFromFloat(3.0)},
}
creditor := UserTab{User: user4, Sum: dec.NewFromFloat(7.0)}
creditor := userTab{User: user4, Sum: dec.NewFromFloat(7.0)}
expectedDebts := mod.Debts{
{Creditor: user4, Debtor: user1, Sum: dec.NewFromFloat(7.0)},
}
+5 -5
View File
@@ -46,7 +46,7 @@ func ParseFormPayments(userIDs []string, paymentsIDs []string,
return payments, nil
}
func (a *ExpensesApp) GetExpensePaymentByUserID(eId int32, uId int32,
func (a *ExpApp) GetExpensePaymentByUserID(eId int32, uId int32,
) (mod.Payment, error) {
ctx := context.Background()
return a.ExpRepo.GetExpensePaymentByUserID(ctx, eId, uId)
@@ -54,22 +54,22 @@ func (a *ExpensesApp) GetExpensePaymentByUserID(eId int32, uId int32,
// insertPayment allows us to insert a payment manually
// for now its private, need to figure out if it needs to be public
func (a *ExpensesApp) insertPayment(payment mod.Payment, eIdx int32) error {
func (a *ExpApp) insertPayment(payment mod.Payment, eIdx int32) error {
ctx := context.Background()
return a.ExpRepo.InsertPayment(ctx, eIdx, payment)
}
func (a *ExpensesApp) DeletePayment(id int32) error {
func (a *ExpApp) DeletePayment(id int32) error {
ctx := context.Background()
return a.ExpRepo.DeletePayment(ctx, id)
}
func (a *ExpensesApp) UpdatePayment(payment mod.Payment) error {
func (a *ExpApp) UpdatePayment(payment mod.Payment) error {
ctx := context.Background()
return a.ExpRepo.UpdatePayment(ctx, payment)
}
func (a *ExpensesApp) AddPayment(expID int32, userID int32, sum dec.Decimal) error {
func (a *ExpApp) AddPayment(expID int32, userID int32, sum dec.Decimal) error {
payment := mod.Payment{
User: mod.User{
UserID: userID,
+1 -1
View File
@@ -5,7 +5,7 @@ import (
lua "github.com/yuin/gopher-lua"
)
func (a *ExpensesApp) luaInsertPayment(L *lua.LState) int {
func (a *ExpApp) luaInsertPayment(L *lua.LState) int {
paymentJSON := L.CheckString(1)
expenseID := L.CheckInt(2)
+4 -3
View File
@@ -48,7 +48,7 @@ func ParseFormShares(userIDs []string, shares []string, sharesIDs []string,
// NormalizeShares will take the total of an expense and the proposed shares
// and calculate how much each user actually has to pay - avoids fracd cents
func (a *ExpensesApp) NormalizeShares(e *mod.Expense) error {
func (a *ExpApp) NormalizeShares(e *mod.Expense) error {
excess := dec.NewFromFloat(0.0)
ownerShIdx := -1
for k := range e.Shares {
@@ -69,12 +69,13 @@ func (a *ExpensesApp) NormalizeShares(e *mod.Expense) error {
// insertShare allows us to insert a share manually
// for now its private, need to figure out if it needs to be public
func (a *ExpensesApp) insertShare(share mod.Share, eIdx int32) error {
func (a *ExpApp) insertShare(share mod.Share, eIdx int32) error {
ctx := context.Background()
return a.ExpRepo.InsertShare(ctx, eIdx, share)
}
func (a *ExpensesApp) DeleteShare(id int32) error {
// DeleteShare will delete a share by its `id`.
func (a *ExpApp) DeleteShare(id int32) error {
ctx := context.Background()
return a.ExpRepo.DeleteShare(ctx, id)
}
+1 -1
View File
@@ -5,7 +5,7 @@ import (
lua "github.com/yuin/gopher-lua"
)
func (a *ExpensesApp) luaInsertShare(L *lua.LState) int {
func (a *ExpApp) luaInsertShare(L *lua.LState) int {
shareJson := L.CheckString(1)
expenseID := L.CheckInt(2)
+1 -1
View File
@@ -44,7 +44,7 @@ func TestNormalizeShares(t *testing.T) {
}
// dummy service to call it
app := ExpensesApp{}
app := ExpApp{}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := app.NormalizeShares(tc.exp)
+22 -11
View File
@@ -3,12 +3,14 @@ package expenses
import (
"context"
mod "expenses/expenses/models"
"github.com/shopspring/decimal"
"log"
"time"
"github.com/shopspring/decimal"
)
func (a *ExpensesApp) GetAllExpenses(ctx context.Context) ([]mod.Expense, error) {
// GetAllExpenses returns the list of Expenses in which the 'user' participates
func (a *ExpApp) GetAllExpenses(ctx context.Context) ([]mod.Expense, error) {
user := *ctx.Value("user").(*mod.User)
expenses, err := a.ExpRepo.GetAll(ctx, user.UserID)
@@ -19,7 +21,9 @@ func (a *ExpensesApp) GetAllExpenses(ctx context.Context) ([]mod.Expense, error)
return expenses, nil
}
func (a *ExpensesApp) GetExpensesRanged(
// TODO - make the GetAllExpenses and this function be only one
// GetExpensesRanged returns the list of Expenses in which the 'user' participates
func (a *ExpApp) GetExpensesRanged(
ctx context.Context, startDate string, endDate string) ([]mod.Expense, error) {
startDateTime, err := time.ParseInLocation("02-Jan-2006 15:04:05", startDate, time.UTC)
if err != nil {
@@ -37,7 +41,9 @@ func (a *ExpensesApp) GetExpensesRanged(
return a.ExpRepo.GetExpensesRange(ctx, startDateTime, endDateTime, user.UserID)
}
func (a *ExpensesApp) GetExpense(id int32) (mod.Expense, error) {
// TODO - we should only be able to access them if the user participates in them
// GetExpense returns a given expense by ID
func (a *ExpApp) GetExpense(id int32) (mod.Expense, error) {
ctx := context.Background()
expense, err := a.ExpRepo.Get(ctx, id)
@@ -48,7 +54,8 @@ func (a *ExpensesApp) GetExpense(id int32) (mod.Expense, error) {
return expense, nil
}
func (a *ExpensesApp) LoadExpenseShares(e *mod.Expense) error {
// LoadExpenseShares populates the Expense with its shares from the DB
func (a *ExpApp) LoadExpenseShares(e *mod.Expense) error {
ctx := context.Background()
var err error
@@ -57,7 +64,8 @@ func (a *ExpensesApp) LoadExpenseShares(e *mod.Expense) error {
return err
}
func (a *ExpensesApp) LoadExpensePayments(e *mod.Expense) error {
// LoadExpensePayments populates the Expense with its payments from the DB
func (a *ExpApp) LoadExpensePayments(e *mod.Expense) error {
ctx := context.Background()
var err error
@@ -66,14 +74,17 @@ func (a *ExpensesApp) LoadExpensePayments(e *mod.Expense) error {
return err
}
func (a *ExpensesApp) LoadExpenseDebts(e *mod.Expense) error {
// LoadExpenseDebts populates the Expense with its debts from the DB
func (a *ExpApp) LoadExpenseDebts(e *mod.Expense) error {
debts, _ := CalculateDebts(e)
e.Debts = debts
return nil
}
func (a *ExpensesApp) DeleteExpense(id int32) error {
// TODO - only expenses the user participates in
// DeleteExpense deletes a given expense
func (a *ExpApp) DeleteExpense(id int32) error {
ctx := context.Background()
err := a.ExpRepo.Delete(ctx, id)
return err
@@ -126,7 +137,7 @@ func ExpenseIsEvenlyShared(exp *mod.Expense) bool {
return true
}
func (a *ExpensesApp) analyzeExpense(e *mod.Expense) {
func (a *ExpApp) analyzeExpense(e *mod.Expense) {
// Figure out if its paid off or not by adding the existing payments
e.PaidOff = e.Value.Equal(ExpenseTotalPayed(e))
@@ -137,13 +148,13 @@ func (a *ExpensesApp) analyzeExpense(e *mod.Expense) {
a.NormalizeShares(e)
}
func (a *ExpensesApp) NewExpense(ctx context.Context, exp mod.Expense) error {
func (a *ExpApp) NewExpense(ctx context.Context, exp mod.Expense) error {
a.analyzeExpense(&exp)
return a.ExpRepo.Insert(ctx, exp)
}
func (a *ExpensesApp) UpdateExpense(exp mod.Expense) error {
func (a *ExpApp) UpdateExpense(exp mod.Expense) error {
ctx := context.Background()
// TODO
+20 -17
View File
@@ -7,7 +7,7 @@ import (
lua "github.com/yuin/gopher-lua"
)
func (a *ExpensesApp) prepareExpense(exp *mod.Expense) error {
func (a *ExpApp) prepareExpense(exp *mod.Expense) error {
err := a.LoadExpensePayments(exp)
if err != nil {
return err
@@ -21,35 +21,38 @@ func (a *ExpensesApp) prepareExpense(exp *mod.Expense) error {
return nil
}
func (a *ExpensesApp) luaGetAllExpenses(L *lua.LState) int {
func (a *ExpApp) luaGetAllExpenses(l *lua.LState) int {
ctx := context.Background()
// TODO - what do we do about the LUA API
expenses, err := a.ExpRepo.GetAll(ctx, 1)
if err != nil {
return returnWithError(l, err.Error())
}
tbl := L.NewTable()
tbl := l.NewTable()
for _, e := range expenses {
err = a.prepareExpense(&e)
if err != nil {
return returnWithError(L, err.Error())
return returnWithError(l, err.Error())
}
jsonData, err := json.Marshal(&e)
if err != nil {
return returnWithError(L, err.Error())
return returnWithError(l, err.Error())
}
et := L.NewTable()
et := l.NewTable()
et.RawSetString("expense", lua.LString(jsonData))
tbl.Append(et)
}
L.Push(lua.LBool(true))
L.Push(tbl)
l.Push(lua.LBool(true))
l.Push(tbl)
return 2
}
func (a *ExpensesApp) luaGetExpense(L *lua.LState) int {
expId := L.CheckInt(1)
func (a *ExpApp) luaGetExpense(l *lua.LState) int {
expId := l.CheckInt(1)
// TODO
// This also doesnt make sense
@@ -57,25 +60,25 @@ func (a *ExpensesApp) luaGetExpense(L *lua.LState) int {
expense, err := a.ExpRepo.Get(ctx, int32(expId))
if err != nil {
return returnWithError(L, err.Error())
return returnWithError(l, err.Error())
}
err = a.prepareExpense(&expense)
if err != nil {
return returnWithError(L, err.Error())
return returnWithError(l, err.Error())
}
jsonData, err := json.Marshal(&expense)
if err != nil {
return returnWithError(L, err.Error())
return returnWithError(l, err.Error())
}
L.Push(lua.LBool(true))
L.Push(lua.LString(jsonData))
l.Push(lua.LBool(true))
l.Push(lua.LString(jsonData))
return 2
}
func (a *ExpensesApp) luaUpdateExpense(L *lua.LState) int {
func (a *ExpApp) luaUpdateExpense(L *lua.LState) int {
expJson := L.CheckString(1)
exp, err := mod.ExpenseFromJSON([]byte(expJson))
@@ -93,7 +96,7 @@ func (a *ExpensesApp) luaUpdateExpense(L *lua.LState) int {
return 2
}
func (a *ExpensesApp) luaNormalizeShares(L *lua.LState) int {
func (a *ExpApp) luaNormalizeShares(L *lua.LState) int {
expenseJson := L.CheckString(1)
expense, err := mod.ExpenseFromJSON([]byte(expenseJson))
+1 -1
View File
@@ -7,7 +7,7 @@ import (
lua "github.com/yuin/gopher-lua"
)
func (a *ExpensesApp) registerLuaBinds(L *lua.LState) {
func (a *ExpApp) registerLuaBinds(L *lua.LState) {
ljson.Preload(L)
// Add the decimal.Decimal operations
L.SetGlobal("AddDecimal", L.NewFunction(luadec.AddDecimal))
+11 -11
View File
@@ -9,31 +9,31 @@ import (
type ExpenseRepository interface {
// Direct expense methods
Get(ctx context.Context, id int32) (mod.Expense, error)
GetAll(ctx context.Context, uId int32) (mod.Expenses, error)
GetAll(ctx context.Context, uID int32) (mod.Expenses, error)
GetExpensesRange(ctx context.Context, start time.Time,
end time.Time, uId int32) (mod.Expenses, error)
end time.Time, uID int32) (mod.Expenses, error)
Update(ctx context.Context, exp mod.Expense) error
Insert(ctx context.Context, exp mod.Expense) error
Delete(ctx context.Context, id int32) error
// Share methods
GetShares(ctx context.Context, eId int32) (mod.Shares, error)
GetShares(ctx context.Context, eID int32) (mod.Shares, error)
UpdateShare(ctx context.Context, sh mod.Share) error
InsertShare(ctx context.Context, eId int32, sh mod.Share) error
InsertShares(ctx context.Context, eId int32, sh mod.Shares) error
InsertShare(ctx context.Context, eID int32, sh mod.Share) error
InsertShares(ctx context.Context, eID int32, sh mod.Shares) error
DeleteShare(ctx context.Context, id int32) error
// Payment methods
GetPayments(ctx context.Context, eId int32) (mod.Payments, error)
GetExpensePaymentByUserID(ctx context.Context, eId int32,
uId int32) (mod.Payment, error)
GetPayments(ctx context.Context, eID int32) (mod.Payments, error)
GetExpensePaymentByUserID(ctx context.Context, eID int32,
uID int32) (mod.Payment, error)
UpdatePayment(ctx context.Context, pm mod.Payment) error
InsertPayment(ctx context.Context, eId int32, pm mod.Payment) error
InsertPayments(ctx context.Context, eId int32, pm mod.Payments) error
InsertPayment(ctx context.Context, eID int32, pm mod.Payment) error
InsertPayments(ctx context.Context, eID int32, pm mod.Payments) error
DeletePayment(ctx context.Context, id int32) error
// Debts
SettleDebt(ctx context.Context, eId int32,
SettleDebt(ctx context.Context, eID int32,
payment mod.Payment, credit mod.Payment) error
Close()
+6 -6
View File
@@ -5,16 +5,16 @@ import (
mod "expenses/expenses/models"
)
func (a *ExpensesApp) GetAllStores(ctx context.Context) ([]mod.Store, error) {
func (a *ExpApp) GetAllStores(ctx context.Context) ([]mod.Store, error) {
return a.StoreRepo.GetAll(ctx)
}
func (a *ExpensesApp) GetStore(id int32) (mod.Store, error) {
func (a *ExpApp) GetStore(id int32) (mod.Store, error) {
ctx := context.Background()
return a.StoreRepo.Get(ctx, id)
}
func (a *ExpensesApp) NewStore(name string, nif string) error {
func (a *ExpApp) NewStore(name string, nif string) error {
ctx := context.Background()
newStore := mod.Store{
@@ -25,7 +25,7 @@ func (a *ExpensesApp) NewStore(name string, nif string) error {
return a.StoreRepo.Insert(ctx, newStore)
}
func (a *ExpensesApp) UpdateStore(id int32, name string, nif string) error {
func (a *ExpApp) UpdateStore(id int32, name string, nif string) error {
ctx := context.Background()
store := mod.Store{
@@ -37,12 +37,12 @@ func (a *ExpensesApp) UpdateStore(id int32, name string, nif string) error {
return a.StoreRepo.Update(ctx, store)
}
func (a *ExpensesApp) DeleteStore(id int32) error {
func (a *ExpApp) DeleteStore(id int32) error {
ctx := context.Background()
return a.StoreRepo.Delete(ctx, id)
}
func (a *ExpensesApp) GetStoreIDFromNIF(nif string) (int32, error) {
func (a *ExpApp) GetStoreIDFromNIF(nif string) (int32, error) {
ctx := context.Background()
store, err := a.StoreRepo.GetByNIF(ctx, nif)
+10 -5
View File
@@ -5,16 +5,19 @@ import (
mod "expenses/expenses/models"
)
func (a *ExpensesApp) GetAllTypes(ctx context.Context) (mod.Types, error) {
// GetAllTypes returns all types
func (a *ExpApp) GetAllTypes(ctx context.Context) (mod.Types, error) {
return a.TypeRepo.GetAll(ctx)
}
func (a *ExpensesApp) GetType(id int32) (mod.Type, error) {
// GetType returns a type by its `id`
func (a *ExpApp) GetType(id int32) (mod.Type, error) {
ctx := context.Background()
return a.TypeRepo.Get(ctx, id)
}
func (a *ExpensesApp) NewType(name string) error {
// NewType creates a new type in the DB, or fails with error
func (a *ExpApp) NewType(name string) error {
ctx := context.Background()
newTyp := mod.Type{
@@ -24,12 +27,14 @@ func (a *ExpensesApp) NewType(name string) error {
return a.TypeRepo.Insert(ctx, newTyp)
}
func (a *ExpensesApp) DeleteType(id int32) error {
// DeleteType deletes a type by its `id`, or fails with error
func (a *ExpApp) DeleteType(id int32) error {
ctx := context.Background()
return a.TypeRepo.Delete(ctx, id)
}
func (a *ExpensesApp) UpdateType(id int32, name string) error {
// UpdateType updates a type by its `id`, or fails with error
func (a *ExpApp) UpdateType(id int32, name string) error {
ctx := context.Background()
updatedType := mod.Type{
+9 -4
View File
@@ -3,24 +3,29 @@ package expenses
import (
"context"
mod "expenses/expenses/models"
"golang.org/x/crypto/bcrypt"
)
func (a *ExpensesApp) GetUser(id int32) (*mod.User, error) {
// GetUser returns an user by its `id`
func (a *ExpApp) GetUser(id int32) (*mod.User, error) {
ctx := context.Background()
return a.UserRepo.Get(ctx, id)
}
func (a *ExpensesApp) GetUserByName(name string) (*mod.User, error) {
// GetUserByName returns a user by its `name`
func (a *ExpApp) GetUserByName(name string) (*mod.User, error) {
ctx := context.Background()
return a.UserRepo.GetByName(ctx, name)
}
func (a *ExpensesApp) GetAllUsers(ctx context.Context) ([]mod.User, error) {
// GetAllUsers returns all the users
func (a *ExpApp) GetAllUsers(ctx context.Context) ([]mod.User, error) {
return a.UserRepo.GetAll(ctx)
}
func (a *ExpensesApp) ValidateCredentials(name string, pass string) (*mod.User, error) {
// ValidateCredentials validates the input credentials against the database
func (a *ExpApp) ValidateCredentials(name string, pass string) (*mod.User, error) {
ctx := context.Background()
user, err := a.UserRepo.GetByName(ctx, name)
+2
View File
@@ -1,3 +1,4 @@
// Package luadec holds shopspring/decimal binds to be used on lua scripts
package luadec
import (
@@ -5,6 +6,7 @@ import (
lua "github.com/yuin/gopher-lua"
)
// AddDecimal adds to decimal numbers passed as strings
func AddDecimal(L *lua.LState) int {
decA, _ := decimal.NewFromString(L.CheckString(1))
decB, _ := decimal.NewFromString(L.CheckString(2))
+1
View File
@@ -1,3 +1,4 @@
// main will start the expenses app
package main
import (
+1
View File
@@ -1,3 +1,4 @@
// Package pages is the HTTP frontend for this application
package pages
import (
+2 -2
View File
@@ -44,8 +44,8 @@ func ExpensesGlobalPage(c *gin.Context) {
expenses, err := exp.App.GetAllExpenses(ctx)
if err != nil {
log.Panicln("error:", err)
c.Header("HX-Redirect", "/500")
log.Println("error:", err)
ServerErrorView(c, "Could not get logged in user")
return
}
+12 -17
View File
@@ -1,19 +1,14 @@
package pages
import (
mod "expenses/expenses/models"
"github.com/gin-gonic/gin"
)
func storeFromForm(c *gin.Context) (*mod.Store, error) {
name := c.PostForm("store-name")
nif := c.PostForm("store-nif")
store := mod.Store{
StoreName: name,
StoreNIF: nif,
}
return &store, nil
}
// func storeFromForm(c *gin.Context) (*mod.Store, error) {
// name := c.PostForm("store-name")
// nif := c.PostForm("store-nif")
//
// store := mod.Store{
// StoreName: name,
// StoreNIF: nif,
// }
//
// return &store, nil
// }
//
File diff suppressed because it is too large Load Diff