-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
ledger.go
614 lines (560 loc) 路 17.8 KB
/
ledger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
package server
import (
"encoding/json"
"io/ioutil"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/johnstarich/sage/client"
"github.com/johnstarich/sage/client/model"
sErrors "github.com/johnstarich/sage/errors"
"github.com/johnstarich/sage/ledger"
"github.com/johnstarich/sage/prompter"
"github.com/johnstarich/sage/rules"
"github.com/johnstarich/sage/sync"
"github.com/pkg/errors"
"github.com/shopspring/decimal"
"go.uber.org/zap"
)
const (
accountTypesQuery = "accountTypes[]" // include [] suffix to support query param arrays
// MaxResults is the maximum number of results from a paginated request
MaxResults = 50
)
func getLedgerSyncStatus(ldgStore *ledger.Store) gin.HandlerFunc {
return func(c *gin.Context) {
var errs sErrors.Errors // used for its marshaler
syncing, prompt, err := ldgStore.SyncStatus()
errs.AddErr(err)
c.JSON(http.StatusOK, map[string]interface{}{
"Syncing": syncing,
"Prompt": prompt,
"Errors": errs.ErrOrNil(),
})
}
}
func submitSyncPrompt(ldgStore *ledger.Store) gin.HandlerFunc {
return func(c *gin.Context) {
var prompt prompter.Response
if err := c.BindJSON(&prompt); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
ldgStore.SubmitSyncPrompt(prompt)
c.Status(http.StatusAccepted)
}
}
func syncLedger(ldgStore *ledger.Store, accountStore *client.AccountStore, rulesStore *rules.Store) gin.HandlerFunc {
return func(c *gin.Context) {
_, syncFromStart := c.GetQuery("fromLedgerStart")
sync.Sync(ldgStore, accountStore, rulesStore, syncFromStart)
c.Status(http.StatusAccepted)
}
}
type transactionsResponse struct {
ledger.QueryResult
AccountIDMap map[string]string
}
func getTransactions(ldgStore *ledger.Store, accountStore *client.AccountStore) gin.HandlerFunc {
return func(c *gin.Context) {
var errs sErrors.Errors
var page, results int = 1, 10
if pageQuery, ok := c.GetQuery("page"); ok {
parsedPage, parseErr := strconv.ParseInt(pageQuery, 10, 64)
switch {
case parseErr != nil:
errs.AddErr(errors.Errorf("Invalid integer: %s", pageQuery))
case parsedPage < 1:
errs.AddErr(errors.New("Page must be a positive integer"))
default:
page = int(parsedPage)
}
}
if resultsQuery, ok := c.GetQuery("results"); ok {
parsedResults, parseErr := strconv.ParseInt(resultsQuery, 10, 64)
switch {
case parseErr != nil:
errs.AddErr(errors.Errorf("Invalid integer: %s", resultsQuery))
case parsedResults < 1 || parsedResults > MaxResults:
errs.AddErr(errors.Errorf("Results must be a positive integer no more than %d", MaxResults))
default:
results = int(parsedResults)
}
}
if len(errs) > 0 {
abortWithClientError(c, http.StatusBadRequest, errs.ErrOrNil())
return
}
var options ledger.QueryOptions
if err := c.BindQuery(&options); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
result := transactionsResponse{
QueryResult: ldgStore.Query(options, page, results),
AccountIDMap: make(map[string]string),
}
// attempt to make asset and liability accounts more descriptive
accountIDMap, err := newAccountIDMap(accountStore)
if err != nil {
abortWithClientError(c, http.StatusInternalServerError, err)
return
}
for i := range result.Transactions {
accountName := result.Transactions[i].Postings[0].Account
if _, exists := result.AccountIDMap[accountName]; !exists {
clientAccount, ok := accountIDMap.Find(accountName)
if ok {
result.AccountIDMap[accountName] = clientAccount.Description()
}
}
}
c.JSON(http.StatusOK, result)
}
}
// BalanceResponse is the response type for fetching account balances
type BalanceResponse struct {
Start, End *time.Time
OpeningBalanceDate *time.Time
Messages []AccountMessage
Accounts []AccountResponse
}
// AccountResponse contains details for an account's balance over time
type AccountResponse struct {
ID string
Account string
AccountType string
OpeningBalance *decimal.Decimal
Balances []decimal.Decimal
Institution string `json:",omitempty"`
}
// AccountMessage contains important information for an account
type AccountMessage struct {
AccountID string `json:",omitempty"`
AccountName string `json:",omitempty"`
Message string
}
type txnToAccountMap map[string]map[string]model.Account
// newAccountIDMap returns a mapping from an institution's description, then account ID suffix (without '*'s), and finally to the source account
func newAccountIDMap(accountStore *client.AccountStore) (txnToAccountMap, error) {
// inst name -> account ID suffix -> account
accountIDMap := make(txnToAccountMap)
var clientAccount model.Account
err := accountStore.Iter(&clientAccount, func(id string) bool {
instName := clientAccount.Institution().Org()
if len(id) > model.RedactSuffixLength {
id = id[len(id)-model.RedactSuffixLength:]
}
if accountIDMap[instName] == nil {
accountIDMap[instName] = make(map[string]model.Account)
}
accountIDMap[instName][id] = clientAccount
return true
})
return accountIDMap, err
}
func (t txnToAccountMap) Find(accountName string) (account model.Account, found bool) {
components := strings.Split(accountName, ":")
if len(components) == 0 {
return nil, false
}
accountType := components[0]
if accountType != model.AssetAccount && accountType != model.LiabilityAccount {
return nil, false
}
if len(components) < 3 {
// require accountType:institution:accountNumber format
return nil, false
}
institutionName, accountID := components[1], strings.Join(components[2:], ":")
idSuffix := accountID
if len(idSuffix) > model.RedactSuffixLength {
idSuffix = idSuffix[len(idSuffix)-model.RedactSuffixLength:]
}
clientAccount, found := t[institutionName][idSuffix]
return clientAccount, found
}
func getBalances(ldgStore *ledger.Store, accountStore *client.AccountStore) gin.HandlerFunc {
return func(c *gin.Context) {
resp, err := getBalancesResponse(ldgStore, accountStore, c.QueryArray(accountTypesQuery))
if err != nil {
abortWithClientError(c, http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, resp)
}
}
func getBalancesResponse(ldgStore *ledger.Store, accountStore *client.AccountStore, accountTypesQueryArray []string) (interface{}, error) {
start, end, balanceMap := ldgStore.Balances()
resp := BalanceResponse{
Start: start,
End: end,
}
accountIDMap, err := newAccountIDMap(accountStore)
if err != nil {
return nil, err
}
accountTypes := map[string]bool{
// return assets and liabilities by default
// useful for a simple balance table
model.AssetAccount: true,
model.LiabilityAccount: true,
}
if len(accountTypesQueryArray) > 0 {
accountTypes = make(map[string]bool, len(accountTypesQueryArray))
for _, value := range accountTypesQueryArray {
accountTypes[value] = true
}
}
var openingBalances ledger.Transaction
if balances, found := ldgStore.OpeningBalances(); found {
resp.OpeningBalanceDate = &balances.Date
openingBalances = balances
}
findOpeningBalance := func(accountName string) *decimal.Decimal {
for _, p := range openingBalances.Postings {
if p.Account == accountName {
return &p.Amount
}
}
return nil
}
for accountName, balances := range balanceMap {
account := AccountResponse{
ID: accountName,
OpeningBalance: findOpeningBalance(accountName),
Balances: balances,
}
if extractAccount(&account, accountName, accountTypes, accountIDMap.Find) {
resp.Accounts = append(resp.Accounts, account)
}
}
var accounts []model.Account
var a model.Account
err = accountStore.Iter(&a, func(id string) bool {
format := model.LedgerFormat(a)
if len(accountTypes) == 0 || accountTypes[format.AccountType] {
accounts = append(accounts, a)
}
return true
})
if err != nil {
return nil, err
}
for _, account := range accounts {
ledgerAccount := model.LedgerFormat(account)
accountName := ledgerAccount.String()
if _, inBalances := balanceMap[accountName]; !inBalances {
resp.Accounts = append(resp.Accounts, AccountResponse{
ID: accountName,
Account: account.Description(),
AccountType: ledgerAccount.AccountType,
OpeningBalance: findOpeningBalance(accountName),
})
}
}
sort.Slice(resp.Accounts, func(a, b int) bool {
return resp.Accounts[a].ID < resp.Accounts[b].ID
})
resp.Messages = append(resp.Messages, getOpeningBalanceMessages(ldgStore, accounts)...)
sort.Slice(resp.Messages, func(a, b int) bool {
return resp.Messages[a].AccountID < resp.Messages[b].AccountID
})
return resp, nil
}
// extractAccount attempts to fill in the account response, returns true if the account should be added
func extractAccount(account *AccountResponse, accountName string, filterAccountTypes map[string]bool, getAccount func(name string) (model.Account, bool)) bool {
format, err := model.ParseLedgerFormat(accountName)
if err != nil || format.AccountType == "" {
return false
}
if len(filterAccountTypes) > 0 && !filterAccountTypes[format.AccountType] {
return false
}
account.AccountType = format.AccountType
switch format.AccountType {
case model.AssetAccount, model.LiabilityAccount:
account.Account = format.Institution + " " + format.AccountID
account.Institution = format.Institution
if clientAccount, found := getAccount(accountName); found {
account.Account = clientAccount.Description()
}
default:
account.ID = format.Remaining
account.Account = account.ID
}
return true
}
func getOpeningBalanceMessages(ldgStore *ledger.Store, accounts []model.Account) []AccountMessage {
var messages []AccountMessage
var openingPostings []ledger.Posting
if openingBalances, ok := ldgStore.OpeningBalances(); ok {
openingPostings = openingBalances.Postings
}
openingBalAccounts := make(map[string]bool)
for _, p := range openingPostings {
if !p.IsOpeningBalance() {
openingBalAccounts[p.Account] = true
}
}
for _, account := range accounts {
id := model.LedgerAccountName(account)
if !openingBalAccounts[id] {
messages = append(messages, AccountMessage{
AccountID: id,
AccountName: account.Description(),
Message: "Missing opening balance",
})
}
}
return messages
}
func getExpenseAndRevenueAccounts(ldgStore *ledger.Store, rulesStore *rules.Store) gin.HandlerFunc {
return func(c *gin.Context) {
_, _, balanceMap := ldgStore.Balances()
accounts := make(map[string]bool, len(balanceMap)+1)
accounts[model.Uncategorized] = true
for account := range balanceMap {
if strings.HasPrefix(account, model.ExpenseAccount+":") || strings.HasPrefix(account, model.RevenueAccount+":") {
components := strings.Split(account, ":")
account = ""
for _, comp := range components {
if len(account) > 0 {
account += ":"
}
account += comp
accounts[account] = true
}
}
}
for _, account := range rulesStore.Accounts() {
accounts[account] = true
}
accountsSlice := make([]string, 0, len(accounts))
for account := range accounts {
accountsSlice = append(accountsSlice, account)
}
sort.Strings(accountsSlice)
c.JSON(http.StatusOK, map[string]interface{}{
"Accounts": accountsSlice,
})
}
}
func updateTransaction(ldgStore *ledger.Store) gin.HandlerFunc {
return func(c *gin.Context) {
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
var txnJSON struct {
ID string // the original transaction's ID
}
if err := json.Unmarshal(body, &txnJSON); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
id := txnJSON.ID
var txn ledger.Transaction
if err := json.Unmarshal(body, &txn); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
switch err := ldgStore.UpdateTransaction(id, txn).(type) {
case ledger.Error:
abortWithClientError(c, http.StatusBadRequest, err)
return
case nil: // skip
default:
abortWithClientError(c, http.StatusInternalServerError, err)
return
}
c.Status(http.StatusNoContent)
}
}
func updateTransactions(ldgStore *ledger.Store) gin.HandlerFunc {
return func(c *gin.Context) {
var txns []struct {
ID string `binding:"required"` // the original transaction's ID
ledger.Transaction
}
if err := c.BindJSON(&txns); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
newTxns := make(map[string]ledger.Transaction, len(txns))
for _, txn := range txns {
newTxns[txn.ID] = txn.Transaction
}
switch err := ldgStore.UpdateTransactions(newTxns).(type) {
case ledger.Error:
abortWithClientError(c, http.StatusBadRequest, err)
return
case nil: // skip
default:
abortWithClientError(c, http.StatusInternalServerError, err)
return
}
c.Status(http.StatusNoContent)
}
}
func updateOpeningBalance(ldgStore *ledger.Store, accountStore *client.AccountStore) gin.HandlerFunc {
return func(c *gin.Context) {
var opening ledger.Transaction
if err := c.ShouldBindJSON(&opening); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
var total decimal.Decimal
for i := range opening.Postings {
format, err := model.ParseLedgerFormat(opening.Postings[i].Account)
if err != nil || format.AccountType == "" {
abortWithClientError(c, http.StatusBadRequest, errors.Wrap(err, "Invalid ledger account ID"))
return
}
total = total.Sub(opening.Postings[i].Amount)
opening.Postings[i].Currency = "$"
}
opening.Postings = append(opening.Postings, ledger.Posting{
Account: "equity:Opening Balances",
Amount: total,
Currency: "$",
Tags: map[string]string{"id": ledger.OpeningBalanceID},
})
switch err := ldgStore.UpdateOpeningBalance(opening).(type) {
case ledger.Error:
abortWithClientError(c, http.StatusBadRequest, err)
return
case nil: // skip
default:
abortWithClientError(c, http.StatusInternalServerError, err)
return
}
c.Status(http.StatusNoContent)
}
}
func importOFXFile(ldgStore *ledger.Store, accountStore *client.AccountStore, rulesStore *rules.Store) gin.HandlerFunc {
return func(c *gin.Context) {
logger := c.MustGet(loggerKey).(*zap.Logger)
skeletonAccounts, txns, err := client.ReadOFX(c.Request.Body)
if err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
rulesStore.ApplyAll(txns)
switch err := ldgStore.AddTransactions(txns).(type) {
case ledger.Error:
abortWithClientError(c, http.StatusBadRequest, err)
return
case nil: // skip
default:
abortWithClientError(c, http.StatusInternalServerError, err)
return
}
accountsAdded := 0
for _, account := range skeletonAccounts {
if err := accountStore.Add(account); err != nil {
logger.Warn("Failed to add bare-bones account from imported file", zap.String("error", err.Error()))
} else {
accountsAdded++
}
}
c.Status(http.StatusNoContent)
}
}
func reimportTransactions(ldgStore *ledger.Store, rulesStore *rules.Store) gin.HandlerFunc {
return func(c *gin.Context) {
var body struct {
Start, End string
Accounts []string
}
if err := c.BindJSON(&body); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
start, end, err := getStartEndTimes(body.Start, body.End, endOfMonth)
if err != nil {
abortWithClientError(c, http.StatusOK, err)
return
}
if len(body.Accounts) == 0 {
body.Accounts = []string{model.Uncategorized}
}
result := ldgStore.Query(ledger.QueryOptions{
Start: start,
End: end,
// currently accounts are fixed to "uncategorized" and "expenses:uncategorized"
Accounts: body.Accounts,
}, 1, ldgStore.Size())
rulesStore.ApplyAll(result.Transactions)
updatedTxns := make(map[string]ledger.Transaction, len(result.Transactions))
for _, txn := range result.Transactions {
updatedTxns[txn.ID()] = txn
}
if err := ldgStore.UpdateTransactions(updatedTxns); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
c.JSON(http.StatusOK, map[string]interface{}{
"Count": result.Count,
})
}
}
type renameParams struct {
Old string `binding:"required"`
New string `binding:"required"`
OldID string
NewID string
}
func renameLedgerAccount(ldgStore *ledger.Store) gin.HandlerFunc {
return func(c *gin.Context) {
var params renameParams
if err := c.BindJSON(¶ms); err != nil {
abortWithClientError(c, http.StatusBadRequest, err)
return
}
if params.OldID != params.NewID && (params.OldID == "" || params.NewID == "") {
abortWithClientError(c, http.StatusBadRequest, errors.New("If OldID or NewID is set, the other must also be set"))
return
}
renameCount, err := ldgStore.RenameAccount(params.Old, params.New, params.OldID, params.NewID)
if err != nil {
abortWithClientError(c, http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, map[string]interface{}{
"Renamed": renameCount,
})
}
}
func renameSuggestions(accountStore *client.AccountStore) gin.HandlerFunc {
const DiscoverOldOrg = "Discover Financial Services"
return func(c *gin.Context) {
var suggestions []renameParams
var account model.Account
err := accountStore.Iter(&account, func(string) bool {
// if old Discover direct connect account, show rename to use new Org and FID
if account.Institution().Org() == DiscoverOldOrg && account.Institution().FID() == "7101" {
ledgerAccount := model.LedgerFormat(account).String()
accountID := account.ID()
suggestions = append(suggestions, renameParams{
Old: ledgerAccount,
New: strings.Replace(ledgerAccount, DiscoverOldOrg, "Discover Card Account Center", 1),
OldID: client.MakeUniqueTxnID("7101", accountID)(""),
NewID: client.MakeUniqueTxnID("9625", accountID)(""),
})
}
return true
})
if err != nil {
abortWithClientError(c, http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, map[string]interface{}{
"Suggestions": suggestions,
})
}
}