Skip to content

Commit 9b809dc

Browse files
committed
equity command
Fixes #29
1 parent 97fcd20 commit 9b809dc

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

ledger/cmd/print.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ func cliTransactions() ([]*ledger.Transaction, error) {
5757
return nil, parseError
5858
}
5959

60+
sort.Slice(generalLedger, func(i, j int) bool {
61+
return generalLedger[i].Date.Before(generalLedger[j].Date)
62+
})
63+
6064
timeStartIndex, timeEndIndex := 0, 0
6165
for idx := 0; idx < len(generalLedger); idx++ {
6266
if generalLedger[idx].Date.After(parsedStartDate) {

ledger/cmd/printEquity.go

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package cmd
2+
3+
import (
4+
"log"
5+
"math/big"
6+
"sort"
7+
"time"
8+
9+
"github.com/howeyc/ledger"
10+
"github.com/spf13/cobra"
11+
)
12+
13+
// equityCmd represents the equity command
14+
var equityCmd = &cobra.Command{
15+
Use: "equity",
16+
Short: "Print account equity as transaction",
17+
Run: func(cmd *cobra.Command, args []string) {
18+
generalLedger, err := cliTransactions()
19+
if err != nil {
20+
log.Fatalln(err)
21+
}
22+
23+
var trans ledger.Transaction
24+
trans.Payee = "Opening Balances"
25+
trans.Date = time.Now()
26+
if len(generalLedger) > 0 {
27+
trans.Date = generalLedger[len(generalLedger)-1].Date
28+
}
29+
30+
balances := make(map[string]*big.Rat)
31+
for _, trans := range generalLedger {
32+
for _, accChange := range trans.AccountChanges {
33+
if ratNum, ok := balances[accChange.Name]; !ok {
34+
balances[accChange.Name] = new(big.Rat).Set(accChange.Balance)
35+
} else {
36+
ratNum.Add(ratNum, accChange.Balance)
37+
}
38+
}
39+
}
40+
41+
ratZero := big.NewRat(0, 1)
42+
for name, bal := range balances {
43+
if bal.Cmp(ratZero) != 0 {
44+
trans.AccountChanges = append(trans.AccountChanges, ledger.Account{
45+
Name: name,
46+
Balance: bal,
47+
})
48+
}
49+
}
50+
51+
sort.Slice(trans.AccountChanges, func(i, j int) bool {
52+
return trans.AccountChanges[i].Name < trans.AccountChanges[j].Name
53+
})
54+
55+
PrintTransaction(&trans, 80)
56+
},
57+
}
58+
59+
func init() {
60+
rootCmd.AddCommand(equityCmd)
61+
62+
var startDate, endDate time.Time
63+
startDate = time.Date(1970, 1, 1, 0, 0, 0, 0, time.Local)
64+
endDate = time.Now().Add(time.Hour * 24)
65+
equityCmd.Flags().StringVarP(&startString, "begin-date", "b", startDate.Format(transactionDateFormat), "Begin date of transaction processing.")
66+
equityCmd.Flags().StringVarP(&endString, "end-date", "e", endDate.Format(transactionDateFormat), "End date of transaction processing.")
67+
}

0 commit comments

Comments
 (0)