impl updating ledger file batch and single by idx

master
bel 2021-08-01 00:29:33 -06:00
parent 612c3f0b7e
commit eaad03281c
2 changed files with 91 additions and 1 deletions

View File

@ -7,6 +7,7 @@ import (
"io"
"io/ioutil"
"os"
"path"
)
type Ledger struct {
@ -23,6 +24,34 @@ func NewLedger(path string) (Ledger, error) {
}, err
}
func (ledger Ledger) SetTransaction(i int, transaction Transaction) error {
transactions, err := ledger.Transactions()
if err != nil {
return err
}
if i >= len(transactions) {
return errors.New("i too high")
}
transactions[i] = transaction
return ledger.SetTransactions(transactions)
}
func (ledger Ledger) SetTransactions(transactions []Transaction) error {
f, err := ioutil.TempFile(os.TempDir(), path.Base(ledger.path)+".*")
if err != nil {
return err
}
for _, transaction := range transactions {
if _, err := fmt.Fprintf(f, "%s\n", transaction.Marshal()); err != nil {
return err
}
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), ledger.path)
}
func (ledger Ledger) Transactions() ([]Transaction, error) {
f, err := ledger.open()
if err != nil {

View File

@ -1,6 +1,14 @@
package main
import "testing"
import (
"fmt"
"io"
"os"
"path"
"testing"
"github.com/google/uuid"
)
func TestLedgerTransactions(t *testing.T) {
ledger, err := NewLedger("./testdata/ledger.dat")
@ -36,3 +44,56 @@ func TestLedgerTransactions(t *testing.T) {
t.Logf("%+v => \n%s", transactions[i], transactions[i].Marshal())
}
}
func TestLedgerSetTransaction(t *testing.T) {
aTransaction := func() Transaction {
return Transaction{
Date: "2021-07-20",
Description: uuid.New().String(),
Payee: "payee",
Payer: "payer",
Amount: 1.23,
}
}
path := path.Join(t.TempDir(), "ledger.dat")
a, err := os.Open("./testdata/ledger.dat")
if err != nil {
t.Fatal(err)
}
b, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
if _, err := io.Copy(b, a); err != nil {
t.Fatal(err)
}
a.Close()
b.Close()
ledger, err := NewLedger(path)
if err != nil {
t.Fatal(err)
}
transactions, err := ledger.Transactions()
if err != nil {
t.Fatal(err)
}
was := fmt.Sprintf("%+v", transactions)
transactions[0] = aTransaction()
want := fmt.Sprintf("%+v", transactions)
if err := ledger.SetTransaction(0, transactions[0]); err != nil {
t.Fatal(err)
}
transactions, err = ledger.Transactions()
if err != nil {
t.Fatal(err)
}
got := fmt.Sprintf("%+v", transactions)
if got == was {
t.Fatal(got)
}
if got != want {
t.Fatal(want, got)
}
}