-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
279 lines (255 loc) · 7.17 KB
/
main.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
package main
import (
"context"
"encoding/csv"
"fmt"
"io"
"log" // TODO Implement https://godoc.org/github.com/apex/log/handlers/cli
"net/http"
"os"
"time"
"go.bmvs.io/ynab/api/transaction"
"github.com/gocarina/gocsv"
"github.com/satraul/bca-go"
"go.bmvs.io/ynab"
"github.com/pkg/errors"
"github.com/shibukawa/configdir"
"github.com/urfave/cli/v2"
)
var (
errEmpty = errors.New("empty input")
errEmptyNonInteractive = errors.New("non-interactive but -u, -p and -t or environment variables not set")
configDirs = configdir.New("satraul", "bca-sync-ynab")
)
var (
noadjust, delete, noninteractive, nostore, reset, csvFlag bool
accountName, budget, password, token, username, fireflyUrl, fireflyToken string
days int
)
func main() {
time.Local = time.FixedZone("WIB", +7*60*60)
app := &cli.App{
Compiled: time.Now(),
Copyright: "(c) 2020 Ahmad Satryaji Aulia",
Description: "Synchronize your BCA transactions with YNAB",
EnableBashCompletion: true,
Version: "v1.3.4",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "username",
Aliases: []string{"u"},
Usage: "username for klikbca https://klikbca.com/. can be set from environment variable",
Destination: &username,
EnvVars: []string{"BCA_USERNAME"},
DefaultText: "-",
},
&cli.StringFlag{
Name: "password",
Aliases: []string{"p"},
Usage: "password for klikbca https://klikbca.com/. can be set from environment variable",
Destination: &password,
EnvVars: []string{"BCA_PASSWORD"},
DefaultText: "-",
},
&cli.StringFlag{
Name: "token",
Aliases: []string{"t"},
Usage: "ynab personal access token https://app.youneedabudget.com/settings/developer. can be set from environment variable",
Destination: &token,
EnvVars: []string{"YNAB_TOKEN"},
DefaultText: "-",
},
&cli.StringFlag{
Name: "account",
Aliases: []string{"a"},
Value: "BCA",
Usage: "ynab account name",
Destination: &accountName,
},
&cli.StringFlag{
Name: "budget",
Aliases: []string{"b"},
Value: "last-used",
Usage: "ynab budget ID",
Destination: &budget,
},
&cli.BoolFlag{
Name: "reset",
Aliases: []string{"r"},
Value: false,
Usage: "reset credentials anew",
Destination: &reset,
},
&cli.BoolFlag{
Name: "delete",
Aliases: []string{"d"},
Value: false,
Usage: "delete credentials",
Destination: &delete,
},
&cli.BoolFlag{
Name: "no-adjust",
Value: false,
Usage: "don't create balance adjustment if applicable after creating transactions",
Destination: &noadjust,
},
&cli.BoolFlag{
Name: "no-store",
Value: false,
Usage: "don't store credentials",
Destination: &nostore,
},
&cli.BoolFlag{
Name: "non-interactive",
Value: false,
Usage: "do not read from stdin and do not read/store credentials file. used with -u, -p and -t or environment variables",
Destination: &noninteractive,
},
&cli.BoolFlag{
Name: "csv",
Value: false,
Usage: "instead of creating ynab transactions, generate a csv",
Destination: &csvFlag,
},
&cli.StringFlag{
Name: "firefly-url",
Aliases: []string{"f"},
Usage: "instead of creating ynab transactions, post to firefly iii url",
Destination: &fireflyUrl,
},
&cli.StringFlag{
Name: "firefly-token",
Aliases: []string{"T"},
Usage: "firefly iii oauth token for use with -f / --firefly-url",
Destination: &fireflyToken,
},
&cli.IntFlag{
Name: "days",
Aliases: []string{"n"},
Value: 27,
Usage: "fetch transactions from n number of days ago (0 to 27 inclusive)",
Destination: &days,
},
},
Action: actionFunc,
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func actionFunc(c *cli.Context) error {
config, err := getOrDeleteConfig(username, password, token, delete, noninteractive, reset, nostore)
if err != nil {
return err
}
if config == nil {
return nil
}
var (
bc = bca.NewAPIClient(bca.NewConfiguration())
ctx = c.Context
ip = getPublicIP()
)
auth, err := bc.Login(ctx, config.BCAUser, config.BCAPassword, ip)
if err != nil {
return errors.Wrap(err, "failed to get bca login")
}
bal, err := bc.BalanceInquiry(ctx, auth)
if err != nil {
return errors.Wrap(err, "failed to get bca balance")
}
trxs, err := getBCATransactions(ctx, bc, auth)
if err != nil {
return err
}
if err := bc.Logout(ctx, auth); err != nil {
return fmt.Errorf("failed to logout: %w", err)
}
if csvFlag {
trxCsv, err := transactionsToCsv(trxs)
if err != nil {
return fmt.Errorf("enable to csv marshal string: %w", err)
}
fmt.Print(trxCsv)
return nil
}
if fireflyUrl != "" {
err := createFireflyTransactions(ctx, bal, trxs)
if err != nil {
return fmt.Errorf("failed to create firefly transactions: %w", err)
}
return nil
}
var (
yc = ynab.NewClient(config.YNABToken)
)
a, err := getYNABAccount(yc, budget, accountName)
if err != nil {
return err
}
if len(trxs) > 0 {
if err := createYNABTransactions(yc, trxs, a, budget); err != nil {
return fmt.Errorf("failed to create ynab transactions: %w", err)
}
}
if !noadjust {
if err := createYNABBalanceAdjustment(bal, ctx, auth, yc, budget, a); err != nil {
return fmt.Errorf("failed to create balance adjustment: %w", err)
}
}
return nil
}
func getBCATransactions(ctx context.Context, bc *bca.BCAApiService, auth []*http.Cookie) ([]bca.Entry, error) {
if days > 27 {
days = 27
}
if days < 0 {
days = 0
}
var (
end = time.Now()
start = end.AddDate(0, 0, -days)
)
trxs, err := bc.AccountStatementView(ctx, start, end, auth)
if err != nil {
return nil, errors.Wrap(err, "failed to get bca transactions. try -r")
}
if len(trxs) == 0 {
fmt.Printf("0 bca transactions from %s to %s\n", start.Format("2006-01-02"), end.Format("2006-01-02"))
}
return trxs, nil
}
func transactionsToCsv(trxs []bca.Entry) (string, error) {
gocsv.TagName = "json"
gocsv.SetCSVWriter(func(out io.Writer) *gocsv.SafeCSVWriter {
writer := csv.NewWriter(out)
return gocsv.NewSafeCSVWriter(writer)
})
ps := make([]transaction.PayloadTransaction, 0)
for _, trx := range trxs {
ps = append(ps, toPayloadTransaction(trx, ""))
}
trxCsv, err := gocsv.MarshalString(&trxs)
return trxCsv, err
}
// clearDate ref: https://cekmutasi.co.id/news/6/jadwal-jam-cut-off-jam-aktif-mutasi-ibanking
func clearDate(now time.Time) time.Time {
rounded := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
switch now.Weekday() {
case time.Friday:
if now.Hour() < 22 {
return rounded
}
return rounded.AddDate(0, 0, 3)
case time.Saturday:
return rounded.AddDate(0, 0, 2)
case time.Sunday:
return rounded.AddDate(0, 0, 1)
default:
if now.Hour() < 22 {
return rounded
}
return rounded.AddDate(0, 0, 1)
}
}