initial commit
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-11-12 12:04:22 -07:00
parent 0444f8ecf8
commit 22aac4adbd
16 changed files with 850 additions and 0 deletions

40
ynab/accounts.go Normal file
View File

@ -0,0 +1,40 @@
package ynab
import (
"fmt"
"net/url"
)
// Reference: https://api.ynab.com/v1#/Accounts/
type Accounts struct {
Data struct {
Account struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
OnBudget bool `json:"on_budget"`
Closed bool `json:"closed"`
Note interface{} `json:"note"`
Balance int `json:"balance"`
ClearedBalance int `json:"cleared_balance"`
UnclearedBalance int `json:"uncleared_balance"`
TransferPayeeID string `json:"transfer_payee_id"`
DirectImportLinked bool `json:"direct_import_linked"`
DirectImportInError bool `json:"direct_import_in_error"`
Deleted bool `json:"deleted"`
} `json:"account"`
ServerKnowledge int `json:"server_knowledge"`
} `json:"data"`
}
func (c *Client) GetAccount(accountID string) (*Accounts, error) {
response := Accounts{}
err := c.get(fmt.Sprintf("/accounts/%s", accountID), &response, url.Values{})
if err != nil {
return nil, fmt.Errorf("failed to get accounts: %v", err)
}
return &response, nil
}

143
ynab/client.go Normal file
View File

@ -0,0 +1,143 @@
package ynab
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
// Reference: https://api.ynab.com/
const apiBaseURL = "https://api.ynab.com/v1/budgets/"
// A client is the structure that will be used to consume the API
// endpoints. It holds the login credentials, http client/transport,
// rate limit information, and the login session timer.
type Client struct {
BearerToken string
BudgetID string
httpClient *http.Client
transport *http.Transport
}
// Send an HTTP GET request, and return the processed response
func (c *Client) get(endpoint string, out interface{}, query url.Values) error {
req, err := http.NewRequest("GET", apiBaseURL+c.BudgetID+endpoint+"?"+query.Encode(), nil)
if err != nil {
return fmt.Errorf("failed to create new GET request: %v", err)
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.BearerToken))
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http GET request failed: %v", err)
}
err = c.processResponse(res, out)
if err != nil {
return fmt.Errorf("failed to process response: %v", err)
}
return nil
}
// Format the message body, send an HTTP POST request, and return the processed response
func (c *Client) post(endpoint string, out interface{}, body interface{}) error {
// Attempt to marshall the body as JSON
json, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("failed to marshal body to json: %v", err)
}
req, err := http.NewRequest("POST", apiBaseURL+c.BudgetID+endpoint, bytes.NewBuffer(json))
if err != nil {
return fmt.Errorf("failed to create new POST request: %v", err)
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.BearerToken))
req.Header.Add("Content-Type", "application/json")
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http POST request failed: %v", err)
}
err = c.processResponse(res, out)
if err != nil {
return fmt.Errorf("failed to process response: %v", err)
}
return nil
}
// Format the message body, send an HTTP POST request, and return the processed response
func (c *Client) put(endpoint string, out interface{}, body interface{}) error {
// Attempt to marshall the body as JSON
json, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("failed to marshal body to json: %v", err)
}
req, err := http.NewRequest("PUT", apiBaseURL+c.BudgetID+endpoint, bytes.NewBuffer(json))
if err != nil {
return fmt.Errorf("failed to create new POST request: %v", err)
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.BearerToken))
req.Header.Add("Content-Type", "application/json")
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http POST request failed: %v", err)
}
err = c.processResponse(res, out)
if err != nil {
return fmt.Errorf("failed to process response: %v", err)
}
return nil
}
// processResponse takes the body of an HTTP response, and either returns
// the error code, or unmarshalls the JSON response, extracts
// rate limit info, and places it into the object
// output parameter. This function closes the response body after reading it.
func (c *Client) processResponse(res *http.Response, out interface{}) error {
body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return fmt.Errorf("failed to read response body: %v", err)
}
if res.StatusCode != 200 && res.StatusCode != 201 {
return fmt.Errorf("unexpected http status code '%d': %v", res.StatusCode, err)
}
err = json.Unmarshal(body, out)
if err != nil {
return fmt.Errorf("failed to unmarshal response body: %v", err)
}
return nil
}
// NewClient is the factory function for clients - takes a bearer token
func NewClient(budgetID, bearerToken string) (*Client, error) {
transport := &http.Transport{
ResponseHeaderTimeout: 5 * time.Second,
}
client := &http.Client{
Transport: transport,
}
// Create a new client
c := &Client{
BudgetID: budgetID,
BearerToken: bearerToken,
httpClient: client,
transport: transport,
}
return c, nil
}

125
ynab/transactions.go Normal file
View File

@ -0,0 +1,125 @@
package ynab
import (
"fmt"
"net/url"
"time"
)
// Reference: https://api.ynab.com/v1#/Transactions/
type BaseTransaction struct {
Type string `json:"type,omitempty"`
ParentTransactionID interface{} `json:"parent_transaction_id,omitempty"`
ID string `json:"id,omitempty"`
Date string `json:"date,omitempty"`
Amount int `json:"amount,omitempty"`
Memo string `json:"memo,omitempty"`
Cleared string `json:"cleared,omitempty"`
Approved bool `json:"approved,omitempty"`
FlagColor interface{} `json:"flag_color,omitempty"`
AccountID string `json:"account_id,omitempty"`
AccountName string `json:"account_name,omitempty"`
PayeeID string `json:"payee_id,omitempty"`
PayeeName string `json:"payee_name,omitempty"`
CategoryID string `json:"category_id,omitempty"`
CategoryName string `json:"category_name,omitempty"`
TransferAccountID interface{} `json:"transfer_account_id,omitempty"`
TransferTransactionID interface{} `json:"transfer_transaction_id,omitempty"`
MatchedTransactionID interface{} `json:"matched_transaction_id,omitempty"`
ImportID string `json:"import_id,omitempty"`
Deleted bool `json:"deleted,omitempty"`
}
// Used for single transaction requests / responses
type Transaction struct {
Data struct {
TransactionIDs []string `json:"transaction_ids,omitempty"`
Transaction BaseTransaction `json:"transaction"`
ServerKnowledge int `json:"server_knowledge,omitempty"`
}
}
type TransactionRequest struct {
Transaction BaseTransaction `json:"transaction,omitempty"`
}
// Used for multiple transaction requests / responses
type Transactions struct {
Data struct {
Transactions []BaseTransaction `json:"transactions"`
ServerKnowledge int `json:"server_knowledge"`
} `json:"data"`
}
// Accepts a YNAB account ID and timestamp and returns all transactions in that account
// since the date provided
func (c *Client) GetAccountTransactions(accountID string, sinceDate time.Time) (*Transactions, error) {
response := Transactions{}
urlQuery := url.Values{}
urlQuery.Add("since_date", sinceDate.Format("2006-01-02"))
err := c.get(fmt.Sprintf("/accounts/%s/transactions", accountID), &response, urlQuery)
if err != nil {
return nil, fmt.Errorf("failed to get account transactions: %v", err)
}
return &response, nil
}
// Accepts a YNAB account ID and returns the transaction ID, amount and an error for the
// the first transaction found with Payee Name "Capital Gains or Losses"
func (c *Client) GetTodayYnabCapitalGainsTransaction(accountID string) (string, int, error) {
ynabTransactions, err := c.GetAccountTransactions(accountID, time.Now())
if err != nil {
return "", 0, fmt.Errorf("failed to get ynab transactions: %v", err)
}
for _, transaction := range ynabTransactions.Data.Transactions {
if transaction.PayeeName != "Capital Gains or Losses" {
continue
}
return transaction.ID, transaction.Amount, nil
}
return "", 0, nil
}
// Accepts a YNAB account ID and transaction amount and creates a new YNAB transaction
func (c *Client) CreateTodayYNABCapitalGainsTransaction(accountID string, amount int) error {
transaction := TransactionRequest{}
transaction.Transaction.AccountID = accountID
transaction.Transaction.Amount = amount
transaction.Transaction.Date = time.Now().Format("2006-01-02")
transaction.Transaction.Cleared = "cleared"
transaction.Transaction.Approved = true
transaction.Transaction.PayeeName = "Capital Gains or Losses"
response := &Transaction{}
err := c.post("/transactions", response, transaction)
if err != nil {
return fmt.Errorf("failed to post transaction: %v", err)
}
return nil
}
// Accepts a YNAB account ID and transaction amount and creates a new YNAB transaction
func (c *Client) UpdateTodayYNABCapitalGainsTransaction(accountID string, transactionID string, amount int) error {
transaction := TransactionRequest{}
transaction.Transaction.AccountID = accountID
transaction.Transaction.ID = transactionID
transaction.Transaction.Amount = amount
transaction.Transaction.Date = time.Now().Format("2006-01-02")
transaction.Transaction.Cleared = "cleared"
transaction.Transaction.Approved = true
transaction.Transaction.PayeeName = "Capital Gains or Losses"
response := &Transaction{}
err := c.put(fmt.Sprintf("/transactions/%s", transactionID), response, transaction)
if err != nil {
return fmt.Errorf("failed to put transaction: %v", err)
}
return nil
}