Working on the Calculated thing

Did some work towards the lua interface, but its kinda shit tbh
This commit is contained in:
2025-08-26 19:29:33 +01:00
parent b6d0d98d41
commit 7320b61df7
15 changed files with 201 additions and 103 deletions
-38
View File
@@ -1,38 +0,0 @@
package cmd
import (
"log"
exp "expenses/expenses"
"expenses/luadec"
"github.com/spf13/cobra"
lua "github.com/yuin/gopher-lua"
)
func debts(cmd *cobra.Command, args []string) {
log.Println("Added the debts command!")
L := lua.NewState()
defer L.Close()
L.SetGlobal("GetAllExpenses", L.NewFunction(exp.Serv.LuaGetAllExpenses))
L.SetGlobal("AddDecimal", L.NewFunction(luadec.AddDecimal))
if err := L.DoFile("./lua-scripts/test.lua"); err != nil {
log.Printf("Failed to run lua script: %+v", err)
}
}
// shelf
var debtsCmd = &cobra.Command{
Use: "debts",
Short: "",
Long: ``,
Args: nil,
Run: debts,
}
func init() {
rootCmd.AddCommand(debtsCmd)
}
+29
View File
@@ -0,0 +1,29 @@
package cmd
import (
exp "expenses/expenses"
"log"
"github.com/spf13/cobra"
)
func scripts(cmd *cobra.Command, args []string) {
lua := exp.Serv.Lua
if err := lua.DoFile("./lua-scripts/test.lua"); err != nil {
log.Printf("Failed to run lua script: %+v", err)
}
}
// shelf
var scriptsCmd = &cobra.Command{
Use: "debts",
Short: "",
Long: ``,
Args: nil,
Run: scripts,
}
func init() {
rootCmd.AddCommand(scriptsCmd)
}
+1
View File
@@ -3,3 +3,4 @@ port: 8081
dbpath: "./data/data.db" dbpath: "./data/data.db"
dbsys: "sqlite3" dbsys: "sqlite3"
migrations_path: "file://expenses/db/migrations/" migrations_path: "file://expenses/db/migrations/"
mig_custom_scripts: "./expenses/db/migrations/custom/"
+6 -5
View File
@@ -8,11 +8,12 @@ import (
) )
type Configuration struct { type Configuration struct {
AssetsDir string `yaml:"assets"` AssetsDir string `yaml:"assets"`
Port string `yaml:"port"` Port string `yaml:"port"`
DBSys string `yaml:"dbsys"` DBSys string `yaml:"dbsys"`
DBPath string `yaml:"dbpath"` DBPath string `yaml:"dbpath"`
MigrationsPath string `yaml:"migrations_path"` MigrationsPath string `yaml:"migrations_path"`
MigCustomScript string `yaml:"mig_custom_scripts"`
} }
var ( var (
+23 -5
View File
@@ -4,7 +4,10 @@ import (
"database/sql" "database/sql"
"expenses/config" "expenses/config"
mod "expenses/expenses/models" mod "expenses/expenses/models"
"expenses/luadec"
"log" "log"
lua "github.com/yuin/gopher-lua"
) )
var ( var (
@@ -12,12 +15,14 @@ var (
) )
type Service struct { type Service struct {
DB *sql.DB DB *sql.DB
Lua *lua.LState
} }
func NewExpenseService(db *sql.DB) *Service { func NewExpenseService(db *sql.DB, luaVM *lua.LState) *Service {
return &Service{ return &Service{
DB: db, DB: db,
Lua: luaVM,
} }
} }
@@ -30,16 +35,29 @@ func openDB(sys string, path string, extra string) (*sql.DB, error) {
return db, nil return db, nil
} }
func StartLuaVM() (*lua.LState, error) {
L := lua.NewState()
L.SetGlobal("GetAllExpenses", L.NewFunction(Serv.LuaGetAllExpenses))
L.SetGlobal("AddDecimal", L.NewFunction(luadec.AddDecimal))
return L, nil
}
func StartApp() error { func StartApp() error {
config.SetConfig("./config.yaml") config.SetConfig("./config.yaml")
cfg := config.GetInstance() cfg := config.GetInstance()
luaVM, err := StartLuaVM()
if err != nil {
return err
}
migDB, err := openDB(cfg.DBSys, cfg.DBPath, "") migDB, err := openDB(cfg.DBSys, cfg.DBPath, "")
if err != nil { if err != nil {
log.Fatalf("Failed to open migration DB: %v", err) log.Fatalf("Failed to open migration DB: %v", err)
} }
err = mod.RunMigrations(migDB) err = mod.RunMigrations(migDB, luaVM)
if err != nil { if err != nil {
log.Fatalf("Failed to apply migrations: %v", err) log.Fatalf("Failed to apply migrations: %v", err)
} }
@@ -49,7 +67,7 @@ func StartApp() error {
if err != nil { if err != nil {
log.Fatalf("Failed to open DB: %v", err) log.Fatalf("Failed to open DB: %v", err)
} }
Serv = NewExpenseService(db) Serv = NewExpenseService(db, luaVM)
return nil return nil
} }
@@ -1 +1,14 @@
print "hello, world!" local cjson = require("cjson")
---@diagnostic disable-next-line: undefined-global
local expenses, err = GetAllExpenses()
if not expenses then
print("Error:", err)
end
for i = 1, #expenses do
local eJson = expenses[i].expense
local e = cjson.decode(eJson)
print(e)
end
-27
View File
@@ -6,7 +6,6 @@ import (
"time" "time"
"github.com/shopspring/decimal" "github.com/shopspring/decimal"
lua "github.com/yuin/gopher-lua"
) )
func (s *Service) GetAllExpenses() ([]mod.Expense, error) { func (s *Service) GetAllExpenses() ([]mod.Expense, error) {
@@ -21,32 +20,6 @@ func (s *Service) GetAllExpenses() ([]mod.Expense, error) {
return expenses, tx.Commit() return expenses, tx.Commit()
} }
func (s *Service) LuaGetAllExpenses(L *lua.LState) int {
tx, err := s.DB.Begin()
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
defer tx.Rollback()
expenses, err := mod.GetAllExpenses(tx)
tbl := L.NewTable()
for _, e := range expenses {
et := L.NewTable()
et.RawSetString("id", lua.LNumber(e.ExpID))
et.RawSetString("description", lua.LString(e.Description))
et.RawSetString("amount", lua.LString(e.Value.StringFixed(2)))
tbl.Append(et)
}
L.Push(tbl)
return 1
}
func (s *Service) GetExpensesRanged(startDate string, endDate string) ([]mod.Expense, error) { func (s *Service) GetExpensesRanged(startDate string, endDate string) ([]mod.Expense, error) {
startDateTime, err := time.ParseInLocation("02-Jan-2006 15:04:05", startDate, time.UTC) startDateTime, err := time.ParseInLocation("02-Jan-2006 15:04:05", startDate, time.UTC)
if err != nil { if err != nil {
+46
View File
@@ -0,0 +1,46 @@
package expenses
import (
"encoding/json"
mod "expenses/expenses/models"
lua "github.com/yuin/gopher-lua"
)
func (s *Service) LuaGetAllExpenses(L *lua.LState) int {
tx, err := s.DB.Begin()
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
defer tx.Rollback()
expenses, err := mod.GetAllExpenses(tx)
tbl := L.NewTable()
for _, e := range expenses {
err := s.LoadExpensePayments(&e)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
continue
}
err = s.LoadExpenseShares(&e)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
continue
}
jsonData, err := json.Marshal(e)
et := L.NewTable()
et.RawSetString("expense", lua.LString(jsonData))
tbl.Append(et)
}
L.Push(tbl)
return 1
}
+2 -2
View File
@@ -11,8 +11,8 @@ import (
) )
type Category struct { type Category struct {
CategoryID int64 CategoryID int64 `json:"CategoryID"`
CategoryName string CategoryName string `json:"CategoryName"`
} }
func NewCategory() Category { func NewCategory() Category {
+14 -14
View File
@@ -12,20 +12,20 @@ import (
) )
type Expense struct { type Expense struct {
ExpID int64 ExpID int64 `json:"ExpID"`
Description string Description string `json:"Description"`
Value decimal.Decimal Value decimal.Decimal `json:"Value"`
Store Store Store Store `json:"Store"`
Type Type Type Type `json:"Type"`
Category Category Category Category `json:"Category"`
Owner User Owner User `json:"User"`
Date int64 Date int64 `json:"Date"`
Payments []ExpensePayment Payments []ExpensePayment `json:"Payments"`
Shares []Share Shares []Share `json:"Shares"`
Debts Debts Debts Debts `json:"Debts"`
PaidOff bool PaidOff bool `json:"PaidOff"`
SharesEven bool SharesEven bool `json:"SharesEven"`
CreationDate int64 CreationDate int64 `json:"CreationDate"`
} }
func NewExpense() Expense { func NewExpense() Expense {
+4 -4
View File
@@ -13,10 +13,10 @@ import (
) )
type Share struct { type Share struct {
ExpShareID int64 ExpShareID int64 `json:"ExpShareID"`
User User User User `json:"User"`
Share dec.Decimal Share dec.Decimal `json:"Share"`
Calculated dec.Decimal // Normalized user share because of fracd cents Calculated dec.Decimal `json:"Calculated"`
} }
type Shares []Share type Shares []Share
+56 -1
View File
@@ -4,10 +4,15 @@ import (
"database/sql" "database/sql"
"expenses/config" "expenses/config"
"log" "log"
"os"
"path/filepath"
"strconv"
"strings"
mig "github.com/golang-migrate/migrate/v4" mig "github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/sqlite3" "github.com/golang-migrate/migrate/v4/database/sqlite3"
_ "github.com/golang-migrate/migrate/v4/source/file" _ "github.com/golang-migrate/migrate/v4/source/file"
lua "github.com/yuin/gopher-lua"
) )
func prepareMigrator(db *sql.DB) (*mig.Migrate, error) { func prepareMigrator(db *sql.DB) (*mig.Migrate, error) {
@@ -34,7 +39,51 @@ func Goto(db *sql.DB, id uint) error {
return nil return nil
} }
func RunMigrations(db *sql.DB) error { func listCustomScripts() (map[uint]string, error) {
// List the available scripts
cfg := config.GetInstance()
dir, err := os.Open(cfg.MigCustomScript)
if err != nil {
return make(map[uint]string), err
}
files, err := dir.Readdir(-1)
if err != nil {
log.Fatal(err)
}
customScripts := make(map[uint]string)
for _, f := range files {
parts := strings.SplitN(f.Name(), "_", 2)
numStr := parts[0]
num, err := strconv.ParseUint(numStr, 10, 16)
if err != nil {
return customScripts, err
}
customScripts[uint(num)] = filepath.Join(cfg.MigCustomScript, f.Name())
}
return customScripts, nil
}
func runCustomScript(ver uint, lua *lua.LState) error {
customScripts, err := listCustomScripts()
if err != nil {
return err
}
if val, ok := customScripts[ver]; ok {
if err := lua.DoFile(val); err != nil {
log.Printf("Failed to run lua script: %+v", err)
}
}
return nil
}
func RunMigrations(db *sql.DB, lua *lua.LState) error {
m, err := prepareMigrator(db) m, err := prepareMigrator(db)
if err != nil { if err != nil {
return err return err
@@ -62,5 +111,11 @@ func RunMigrations(db *sql.DB) error {
ver, _, _ := m.Version() ver, _, _ := m.Version()
log.Printf("Successfuly jumped to migration %d", ver) log.Printf("Successfuly jumped to migration %d", ver)
// Sigh, it still needs plenty of work
// err = runCustomScript(ver, lua)
// if err != nil {
// return err
// }
return nil return nil
} }
+2 -2
View File
@@ -12,8 +12,8 @@ import (
) )
type Store struct { type Store struct {
StoreID int64 StoreID int64 `json:"StoreID"`
StoreName string StoreName string `json:"StoreName"`
} }
func NewStore() Store { func NewStore() Store {
+2 -2
View File
@@ -12,8 +12,8 @@ import (
) )
type Type struct { type Type struct {
TypeID int64 TypeID int64 `json:"TypeID"`
TypeName string TypeName string `json:"TypeName"`
} }
func NewType() Type { func NewType() Type {
+2 -2
View File
@@ -9,8 +9,8 @@ import (
) )
type User struct { type User struct {
UserID int64 UserID int64 `json:"UserID"`
UserName string UserName string `json:"UserName"`
} }
func NewUser() User { func NewUser() User {