fio.go (2389B)
1 package main 2 3 import ( 4 "errors" 5 "fio/fio" 6 "fmt" 7 "log" 8 "strings" 9 "time" 10 11 "github.com/leekchan/accounting" 12 ) 13 14 type account struct { 15 name string 16 config config 17 fio *fio.Fio 18 root *fio.Root 19 } 20 21 func (acc *account) needsReload() bool { 22 return acc.root == nil || acc.hasNew() 23 } 24 25 func (acc *account) reload(force bool) error { 26 if force || acc.needsReload() { 27 log.Printf("Reloading '%s'", acc.name) 28 if !acc.loadRoot() { 29 return errors.New("Failed to load root for '" + acc.name + "'") 30 } else { 31 reverse(acc.root.AccountStatement.TransactionList.Transactions) 32 } 33 } 34 return nil 35 } 36 37 func (acc *account) hasNew() bool { 38 last := acc.fio.Last() 39 if last == nil { 40 return false 41 } 42 return len(last.AccountStatement.TransactionList.Transactions) > 0 43 } 44 45 func (acc *account) loadCard(template []byte, isActive bool) (string, error) { 46 err := acc.reload(false) 47 if err != nil { 48 return "", err 49 } 50 ac := accounting.Accounting{Symbol: acc.root.AccountStatement.Info.Currency, Precision: 2, Thousand: " ", Format: "%v %s"} 51 // templating 52 card := string(template) 53 card = strings.Replace(card, "{{LINK}}", "/"+acc.name, -1) 54 var active string 55 if isActive { 56 active = "active" 57 } 58 card = strings.Replace(card, "{{ACTIVE}}", active, -1) 59 card = strings.Replace(card, "{{NAME}}", acc.name, -1) 60 card = strings.Replace(card, "{{ACC_ID}}", formatAccId(acc.root), -1) 61 closingBal := ac.FormatMoney(acc.root.AccountStatement.Info.ClosingBalance) 62 card = strings.Replace(card, "{{BALANCE}}", fmt.Sprintf("%v", closingBal), -1) 63 64 return card, nil 65 } 66 67 func (acc *account) loadBalance(template []byte, cards string) (string, error) { 68 err := acc.reload(false) 69 if err != nil { 70 return "", err 71 } 72 // templating 73 file := string(template) 74 file = strings.Replace(file, "{{CARDS}}", cards, -1) 75 file = strings.Replace(file, "{{NAME}}", acc.name, -1) 76 file = strings.Replace(file, "{{LIST}}", formatList(acc.root, acc.config), -1) 77 78 return string(file), nil 79 } 80 81 func (acc *account) loadRoot() bool { 82 from := time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC) 83 to := time.Date(2021, time.December, 31, 0, 0, 0, 0, time.UTC) 84 85 acc.root = acc.fio.Period(from, to) 86 return acc.root != nil 87 } 88 89 func reverse(numbers []*fio.Transaction) []*fio.Transaction { 90 for i := 0; i < len(numbers)/2; i++ { 91 j := len(numbers) - i - 1 92 numbers[i], numbers[j] = numbers[j], numbers[i] 93 } 94 return numbers 95 }