This commit is contained in:
bel
2023-10-22 22:03:26 -06:00
parent 61cd82b307
commit 078c425d9e
6 changed files with 108 additions and 0 deletions

38
ledger/delta.go Normal file
View File

@@ -0,0 +1,38 @@
package ledger
import (
"time"
"github.com/howeyc/ledger"
)
type Currency string
const (
USD = Currency("$")
)
type Delta struct {
Date time.Time
Account string
Value float64
Currency Currency
}
func newDeltas(t *ledger.Transaction) []Delta {
result := make([]Delta, len(t.AccountChanges))
for i, a := range t.AccountChanges {
result[i] = newDelta(t.Date, a)
}
return result
}
func newDelta(d time.Time, a ledger.Account) Delta {
value, _ := a.Balance.Float64()
return Delta{
Date: d,
Account: a.Name,
Value: value,
Currency: USD, // TODO
}
}

41
ledger/file.go Normal file
View File

@@ -0,0 +1,41 @@
package ledger
import (
"github.com/howeyc/ledger"
)
type File string
func NewFile(p string) (File, error) {
f := File(p)
_, err := f.Deltas()
return f, err
}
func (file File) Deltas(likes ...Like) ([]Delta, error) {
transactions, err := file.transactions()
if err != nil {
return nil, err
}
result := make([]Delta, 0, len(transactions)*2)
for _, transaction := range transactions {
for _, delta := range newDeltas(transaction) {
if got := func() bool {
for _, like := range likes {
if !like(delta) {
return false
}
}
return true
}(); !got {
continue
}
result = append(result, delta)
}
}
return result, nil
}
func (file File) transactions() ([]*ledger.Transaction, error) {
return ledger.ParseLedgerFile(string(file))
}

15
ledger/like.go Normal file
View File

@@ -0,0 +1,15 @@
package ledger
import "regexp"
type Like func(Delta) bool
func LikeAcc(pattern string) Like {
return func(d Delta) bool {
return like(pattern, d.Account)
}
}
func like(pattern string, other string) bool {
return regexp.MustCompile(pattern).MatchString(other)
}