budgeteer/postgres/ynab-export.go
2022-02-23 20:52:29 +00:00

103 lines
2.6 KiB
Go

package postgres
import (
"context"
"encoding/csv"
"fmt"
"io"
"github.com/google/uuid"
)
type YNABExport struct {
queries *Queries
budgetID uuid.UUID
}
func NewYNABExport(context context.Context, queries *Queries, budgetID uuid.UUID) (*YNABExport, error) {
return &YNABExport{
queries: queries,
budgetID: budgetID,
}, nil
}
// ImportAssignments expects a TSV-file as exported by YNAB in the following format:
// "Month" "Category Group/Category" "Category Group" "Category" "Budgeted" "Activity" "Available"
// "Apr 2019" "Income: Next Month" "Income" "Next Month" 0,00€ 0,00€ 0,00€
//
// Activity and Available are not imported, since they are determined by the transactions and historic assignments.
func (ynab *YNABExport) ExportAssignments(context context.Context, w io.Writer) error {
csv := csv.NewWriter(w)
csv.Comma = '\t'
assignments, err := ynab.queries.GetAllAssignments(context, ynab.budgetID)
if err != nil {
return fmt.Errorf("load assignments: %w", err)
}
count := 0
for _, assignment := range assignments {
row := []string{
assignment.Date.Format("Jan 2006"),
assignment.Group + ": " + assignment.Category,
assignment.Group,
assignment.Category,
assignment.Amount.String() + "€",
"0,00€",
"0,00€",
}
csv.Write(row)
count++
}
csv.Flush()
fmt.Printf("Exported %d assignments\n", count)
return nil
}
// ImportTransactions expects a TSV-file as exported by YNAB in the following format:
// "Account" "Flag" "Date" "Payee" "Category Group/Category" "Category Group" "Category" "Memo" "Outflow" "Inflow" "Cleared"
// "Cash" "" "11.12.2021" "Transfer : Checking" "" "" "" "Brought to bank" 500,00€ 0,00€ "Cleared"
func (ynab *YNABExport) ExportTransactions(context context.Context, w io.Writer) error {
csv := csv.NewWriter(w)
csv.Comma = '\t'
transactions, err := ynab.queries.GetTransactionsForBudget(context, ynab.budgetID)
if err != nil {
return fmt.Errorf("load transactions: %w", err)
}
count := 0
for _, transaction := range transactions {
row := []string{
transaction.Account,
"", // Flag
transaction.Date.Format("02.01.2006"),
transaction.Payee,
transaction.CategoryGroup + " : " + transaction.Category,
transaction.CategoryGroup,
transaction.Category,
transaction.Memo,
}
if transaction.Amount.IsPositive() {
row = append(row, transaction.Amount.String()+"€", "0,00€")
} else {
row = append(row, "0,00€", transaction.Amount.String()[1:]+"€")
}
row = append(row, string(transaction.Status))
csv.Write(row)
count++
}
csv.Flush()
fmt.Printf("Exported %d transactions\n", count)
return nil
}