-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
491 lines (435 loc) · 14 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
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
package main
//go:generate swagger generate client -f spec-v1-swagger.json --additional-initialism=OK --additional-initialism=YNAB -O createTransaction -O getBudgets -M Account -M AccountType -M BudgetSummary -M BudgetSummaryResponse -M CurrencyFormat -M DateFormat -M ErrorDetail -M ErrorResponse -M LoanAccountPeriodicValue -M PostTransactionsWrapper -M SaveSubTransaction -M SaveTransaction -M SaveTransactionsResponse -M SaveTransactionWithOptionalFields -M SubTransaction -M TransactionDetail -M TransactionSummary
import (
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/dbinit/ynab-amazon-import/client"
"github.com/dbinit/ynab-amazon-import/client/budgets"
"github.com/dbinit/ynab-amazon-import/client/transactions"
"github.com/dbinit/ynab-amazon-import/models"
"github.com/go-openapi/runtime"
httptransport "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
)
var (
token = flag.String("token", "", "YNAB personal access token")
budget = flag.String("budget", "", "YNAB budget name")
account = flag.String("account", "", "YNAB account name")
orders = flag.String("orders", "", "Amazon orders CSV file")
items = flag.String("items", "", "Amazon items CSV file")
color = flag.String("color", "", "Optional flag color for imported transactions")
dryRun = flag.Bool("dry_run", false, "Dry run.")
)
const (
// Default payee names.
defaultPayee = "Amazon"
missingPayee = "Missing"
// Amazon CSV date format.
dateFormat = "01/02/06"
// Amazon URL prefix for order details.
orderURL = "https://amzn.com/order-details/?orderID="
// CSV column names.
shipmentDate = "Shipment Date"
orderID = "Order ID"
orderStatus = "Order Status"
shippingCharge = "Shipping Charge"
totalPromotions = "Total Promotions"
taxCharged = "Tax Charged"
totalCharged = "Total Charged"
title = "Title"
seller = "Seller"
itemSubtotalTax = "Item Subtotal Tax"
itemTotal = "Item Total"
// Shipped "Order Status" value.
shipped = "Shipped"
)
func main() {
flag.Parse()
// Make sure required flags are provided.
var missing []string
for _, n := range []string{"token", "budget", "account", "orders", "items"} {
if f := flag.Lookup(n); f == nil || f.Value.String() == "" {
missing = append(missing, n)
}
}
if len(missing) > 0 {
log.Fatalf("missing required flag(s): %v", missing)
}
authInfo := httptransport.BearerToken(*token)
budgetID, accountID, err := budgetAccount(*budget, *account, authInfo)
if err != nil {
log.Fatal(err)
}
odm, err := parseOrders(*orders)
if err != nil {
log.Fatal(err)
}
idm, err := parseItems(*items)
if err != nil {
log.Fatal(err)
}
// Build the transactions.
data := &models.PostTransactionsWrapper{Transactions: buildTransactions(accountID, mergeOrders(odm, idm))}
if len(data.Transactions) == 0 {
log.Fatal("nothing to import")
}
if *dryRun {
j, err := json.MarshalIndent(data, "", "\t")
if err != nil {
log.Fatalf("json.MarshalIndent(): %v", err)
}
log.Println(string(j))
return
}
params := transactions.NewCreateTransactionParams().WithBudgetID(budgetID.String()).WithData(data)
if _, err = client.Default.Transactions.CreateTransaction(params, authInfo); err != nil {
log.Fatalf("CreateTransaction(): %v", err)
}
}
// budgetAccount finds the named budget and account and returns the IDs.
func budgetAccount(budgetName, accountName string, authInfo runtime.ClientAuthInfoWriter) (*strfmt.UUID, *strfmt.UUID, error) {
params := budgets.NewGetBudgetsParams().WithIncludeAccounts(ptrOf(true))
budgets, err := client.Default.Budgets.GetBudgets(params, authInfo)
if err != nil {
return nil, nil, fmt.Errorf("GetBudgets(): %w", err)
}
if budgets == nil || budgets.Payload == nil || budgets.Payload.Data == nil {
return nil, nil, fmt.Errorf("GetBudgets(): %+v", budgets)
}
var bid, aid *strfmt.UUID
for _, b := range budgets.Payload.Data.Budgets {
if b == nil || b.ID == nil || b.Name == nil || !strings.EqualFold(*b.Name, budgetName) {
continue
}
bid, budgetName = b.ID, *b.Name
log.Printf("budget %q found with ID %s", budgetName, bid)
for _, a := range b.Accounts {
if a == nil || a.ID == nil || a.Name == nil || !strings.EqualFold(*a.Name, accountName) {
continue
}
aid, accountName = a.ID, *a.Name
log.Printf("account %q found with ID %s", budgetName, bid)
break
}
break
}
if bid == nil {
return nil, nil, fmt.Errorf("budget %q not found", budgetName)
}
if aid == nil {
return nil, nil, fmt.Errorf("account %q not found in budget %q", accountName, budgetName)
}
return bid, aid, nil
}
type orderDetail struct {
orderID string
shipmentDate *strfmt.Date
shippingCharge int64
totalPromotions int64
taxCharged int64
totalCharged int64
items []*itemDetail
}
func (od *orderDetail) String() string {
var items string
for i, id := range od.items {
items += fmt.Sprintf("\n\t%02d %s", i, id)
}
return fmt.Sprintf(
"Date: %s, Ship: %d, Promo: %d, Tax: %d, Total: %d%s",
od.shipmentDate, od.shippingCharge, od.totalPromotions, od.taxCharged, od.totalCharged, items)
}
type itemDetail struct {
title string
seller string
subTotalTax int64
itemTotal int64
}
func (id *itemDetail) String() string {
return fmt.Sprintf(
"Seller: %q, Tax: %d, Total: %d, Title: %q",
id.seller, id.subTotalTax, id.itemTotal, id.title)
}
// parseOrders parses an Amazon order CSV and returns an orderDetail for each
// order ID.
func parseOrders(name string) (map[string]*orderDetail, error) {
rows, err := parseCSV(name, orderStatus, orderID, shipmentDate, shippingCharge, totalPromotions, taxCharged, totalCharged)
if err != nil {
return nil, fmt.Errorf("failed to parse orders CSV: %w", err)
}
details := make(map[string]*orderDetail)
for _, row := range rows {
// Skip orders that haven't shipped.
if row[orderStatus] != shipped {
continue
}
// Get or add an order record.
od, err := getOrAddOrder(details, row)
if err != nil {
return nil, err
}
// Parse the order amounts.
amounts := []*int64{&od.shippingCharge, &od.totalPromotions, &od.taxCharged, &od.totalCharged}
for i, col := range []string{shippingCharge, totalPromotions, taxCharged, totalCharged} {
n, err := parseMoney(row[col], col != totalPromotions)
if err != nil {
return nil, fmt.Errorf("failed to parse %s %q: %w", col, row[col], err)
}
*amounts[i] += n
}
}
return details, nil
}
// parseItems parses an Amazon item CSV and returns an orderDetail for each
// order ID.
func parseItems(name string) (map[string]*orderDetail, error) {
rows, err := parseCSV(name, orderStatus, orderID, shipmentDate, title, seller, itemSubtotalTax, itemTotal)
if err != nil {
return nil, fmt.Errorf("failed to parse items CSV: %w", err)
}
details := make(map[string]*orderDetail)
for _, row := range rows {
// Skip items that haven't shipped.
if row[orderStatus] != shipped {
continue
}
// Get or add an order record.
od, err := getOrAddOrder(details, row)
if err != nil {
return nil, err
}
// Create an item record.
id := &itemDetail{title: row[title], seller: row[seller]}
// Parse the item amounts.
amounts := []*int64{&id.subTotalTax, &id.itemTotal}
for i, col := range []string{itemSubtotalTax, itemTotal} {
n, err := parseMoney(row[col], true)
if err != nil {
return nil, fmt.Errorf("failed to parse %s %q: %w", col, row[col], err)
}
*amounts[i] = n
}
// Add the item and amounts to the order.
od.taxCharged += id.subTotalTax
od.totalCharged += id.itemTotal
od.items = append(od.items, id)
}
return details, nil
}
// parseCSV parses a CSV file and extracts named columns into a string map for
// each row.
func parseCSV(name string, cols ...string) (rows []map[string]string, err error) {
f, err := os.Open(name)
if err != nil {
return nil, fmt.Errorf("os.Open(%q): %w", name, err)
}
defer func() {
// Do we care about close errors?
if ferr := f.Close(); ferr != nil && err == nil {
err = fmt.Errorf("(os.File).Close(%q): %w", name, ferr)
}
}()
reader := csv.NewReader(f)
// Read the header row.
row, err := reader.Read()
if err != nil {
return nil, fmt.Errorf("(csv.Reader).Read(%q) header: %w", name, err)
}
// Build a column index map.
sort.Strings(cols)
colm := make(map[int]string)
for i, c := range row {
// Find each column name. Column names must match exactly.
if j := sort.SearchStrings(cols, c); j < len(cols) && cols[j] == c {
cols = append(cols[:j], cols[j+1:]...)
colm[i] = c
}
}
if len(cols) > 0 {
return nil, fmt.Errorf("missing columns in %q: %v", name, cols)
}
// Build row maps of column names to values.
for row, err = reader.Read(); err == nil; row, err = reader.Read() {
rm := make(map[string]string)
for i, c := range colm {
if len(row) > i {
rm[c] = row[i]
}
}
rows = append(rows, rm)
}
if err != nil && err != io.EOF {
return nil, fmt.Errorf("(csv.Reader).Read(%q) rows: %w", name, err)
}
return rows, nil
}
// getOrAddOrder checks for an existing orderDetail and returns it or adds a new
// one and returns it. Orders are grouped by order ID and shipment date.
func getOrAddOrder(details map[string]*orderDetail, row map[string]string) (*orderDetail, error) {
// Get the transaction date.
date, err := parseDate(row[shipmentDate])
if err != nil {
return nil, fmt.Errorf("failed to parse %s %q: %w", shipmentDate, row[shipmentDate], err)
}
// Check if there is already a record for the order ID.
oid := row[orderID]
key := date.String() + "-" + oid
if d, ok := details[key]; ok {
return d, nil
}
d := &orderDetail{orderID: oid, shipmentDate: date}
details[key] = d
return d, nil
}
// parseDate returns the YNAB date representation of an Amazon CSV date string.
func parseDate(date string) (*strfmt.Date, error) {
d, err := time.ParseInLocation(dateFormat, date, time.Local)
if err != nil {
return nil, err
}
return ptrOf(strfmt.Date(d)), nil
}
// ptrOf returns a pointer to a value of any type.
func ptrOf[T any](v T) *T { return &v }
// parseMoney returns the YNAB int64 representation of an Amazon CSV currency
// string. E.g. "$12.34" becomes 12340.
func parseMoney(amount string, invert bool) (int64, error) {
m := moneyRE.FindStringSubmatch(amount)
if m == nil || len(m) != 4 {
return 0, fmt.Errorf("failed to parse %q as money", amount)
}
// Make sure decimal has 3 digits.
a, err := strconv.ParseInt(m[1]+m[2]+(m[3] + "000")[:3], 10, 0)
if err != nil {
return 0, fmt.Errorf("failed to parse %q as money: %w", amount, err)
}
if invert {
return a * -1, nil
}
return a, nil
}
// Matches a currency string, e.g. "$12.34".
var moneyRE = regexp.MustCompile(`^([-])?[^\d]*(\d+)(?:[.](\d+))?$`)
// truncate as string to a maximum length.
func truncate(s string, l int) string {
if l <= 0 {
return ""
}
if utf8.RuneCountInString(s) < l {
return s
}
return string([]rune(s)[:l])
}
// mergeItems merges parsed orders and parsed items.
func mergeOrders(odm, idm map[string]*orderDetail) map[string]*orderDetail {
for key, id := range idm {
od, ok := odm[key]
if !ok {
// No matching order, so just copy the item pseudo-order.
log.Printf("Missing order: %s\n\n", id)
odm[key] = id
continue
}
// Copy over items.
od.items = id.items
// If there is more total tax than item tax, assume it is for shipping.
if st := od.taxCharged - id.taxCharged; st < 0 && od.shippingCharge < 0 {
od.shippingCharge += st
}
// Add an item for any remaining balance.
if r := od.totalCharged - od.shippingCharge - od.totalPromotions - id.totalCharged; r != 0 {
od.items = append(od.items, &itemDetail{
title: orderURL + od.orderID,
seller: missingPayee,
itemTotal: r,
})
}
}
return odm
}
// buildTransactions builds new transactions from order details.
func buildTransactions(accountID *strfmt.UUID, odm map[string]*orderDetail) []*models.SaveTransaction {
// Create transactions in key order.
keys := make([]string, 0, len(odm))
for k := range odm {
keys = append(keys, k)
}
sort.Strings(keys)
var transactions []*models.SaveTransaction
for _, k := range keys {
od := odm[k]
if od.totalCharged == 0 {
// Skip $0 orders.
continue
}
t := &models.SaveTransaction{
AccountID: accountID,
Amount: &od.totalCharged,
Date: od.shipmentDate,
SaveTransactionWithOptionalFields: models.SaveTransactionWithOptionalFields{
Cleared: models.SaveTransactionWithOptionalFieldsClearedCleared,
FlagColor: color,
},
}
transactions = append(transactions, t)
if len(od.items) == 0 {
// Missing items.
t.Memo = truncate(orderURL+od.orderID, 200)
t.PayeeName = truncate(defaultPayee, 50)
continue
}
if len(od.items) == 1 {
// Single item.
t.Memo = truncate(od.items[0].title, 200)
t.PayeeName = truncate(od.items[0].seller, 50)
continue
}
// Apply any promotional amounts to shipping charges.
if n := od.shippingCharge + od.totalPromotions; n < 0 {
// Create a subtransaction for the remaining shipping charge.
t.Subtransactions = append(t.Subtransactions, &models.SaveSubTransaction{
Amount: &n,
Memo: truncate(shippingCharge, 200),
PayeeName: truncate(defaultPayee, 50),
})
} else if n > 0 {
// Create a subtransaction for the remaining promo total.
t.Subtransactions = append(t.Subtransactions, &models.SaveSubTransaction{
Amount: &n,
Memo: truncate(totalPromotions, 200),
PayeeName: truncate(defaultPayee, 50),
})
}
// Create subtransactions for each of the order items.
var multiPayee bool
for _, id := range od.items {
payeeName := truncate(id.seller, 50)
t.Subtransactions = append(t.Subtransactions, &models.SaveSubTransaction{
Amount: &id.itemTotal,
Memo: truncate(id.title, 200),
PayeeName: payeeName,
})
if multiPayee || payeeName == t.PayeeName {
continue
}
// If all items have the same payee, propagate it to the transaction.
if multiPayee = t.PayeeName != ""; multiPayee {
t.PayeeName = ""
} else {
t.PayeeName = payeeName
}
}
}
return transactions
}