Skip to content

Commit

Permalink
fix(YNAB): date must not be in the future
Browse files Browse the repository at this point in the history
Fix error 400 from YNAB API when a transaction date is in the future or
more than 5 years ago.

Fixes #73
  • Loading branch information
martinohansen committed Apr 23, 2024
1 parent 7f8c6dd commit b175269
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
13 changes: 11 additions & 2 deletions writer/ynab/ynab.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,14 @@ func ynabberToYNAB(cfg ynabber.Config, t ynabber.Transaction) (Ytransaction, err
}, nil
}

// validTransaction checks if date is within the limits of YNAB and w.Config.
func (w Writer) validTransaction(date time.Time) bool {
fiveYearsAgo := time.Now().AddDate(-5, 0, 0)
return !date.Before(fiveYearsAgo) &&
!date.Before(time.Time(w.Config.YNAB.FromDate)) &&
!date.After(time.Now())
}

func (w Writer) Bulk(t []ynabber.Transaction) error {
// skipped and failed counters
skipped := 0
Expand All @@ -121,8 +129,9 @@ func (w Writer) Bulk(t []ynabber.Transaction) error {
// Build array of transactions to send to YNAB
y := new(Ytransactions)
for _, v := range t {
// Skip transaction if the date is before FromDate
if v.Date.Before(time.Time(w.Config.YNAB.FromDate)) {

// Skip transactions that are not within the valid date range.
if !w.validTransaction(v.Date) {
skipped += 1
continue
}
Expand Down
46 changes: 46 additions & 0 deletions writer/ynab/ynab_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,49 @@ func TestYnabberToYNAB(t *testing.T) {
})
}
}

func TestValidTransaction(t *testing.T) {
fromDate := time.Now().AddDate(-1, 0, 0)
mockFromDate := ynabber.Date(fromDate)
writer := Writer{
Config: &ynabber.Config{
YNAB: ynabber.YNAB{
FromDate: mockFromDate,
},
},
}

tests := []struct {
name string
date time.Time
want bool
}{
{
name: "Yesterday",
date: time.Now().AddDate(0, 0, -1),
want: true,
},
{
name: "Tomorrow",
date: time.Now().AddDate(0, 0, 1),
want: false,
},
{
name: "5 years ago",
date: time.Now().AddDate(-5, 0, 0),
want: false,
},
{
name: "Before FromDate",
date: fromDate.AddDate(0, 0, -1),
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := writer.validTransaction(tt.date); got != tt.want {
t.Errorf("validTransaction() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit b175269

Please sign in to comment.