75 lines
2.6 KiB
Go
75 lines
2.6 KiB
Go
package ynab
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"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
|
|
}
|
|
|
|
// Creates a "Capital Gains or Losses" adjustment transaction or updates an existing one if it exists to ensure the account balance
|
|
// for the accountID provided equals the balance provided
|
|
func (c *Client) SetAccountBalance(accountID string, balance int) error {
|
|
|
|
ynabTransactionID, ynabTransactionAmount, err := c.getTodayYnabCapitalGainsTransaction(accountID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get ynab capital gains transaction ID: %v", err)
|
|
}
|
|
|
|
ynabAccount, err := c.getAccount(accountID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get ynab account with id '%s': %v", accountID, err)
|
|
}
|
|
|
|
if balance == ynabAccount.Data.Account.ClearedBalance {
|
|
return nil // The YNAB account already has the balance we're requesting, so there is no need to do anything
|
|
}
|
|
|
|
balanceDelta := balance - ynabAccount.Data.Account.ClearedBalance
|
|
balanceDelta += ynabTransactionAmount // Take into account the existing transaction
|
|
if balanceDelta == 0 {
|
|
return nil // If balanceDelta is 0 do not create a transaction i.e. market is closed today
|
|
}
|
|
|
|
err = c.updateTodayYNABCapitalGainsTransaction(accountID, ynabTransactionID, balanceDelta)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to update YNAB capital gains transaction for account ID '%s': %v", accountID, err)
|
|
}
|
|
log.Printf("Capital gains transaction for YNAB account '%s' amount is: %d", accountID, balanceDelta)
|
|
|
|
return nil
|
|
}
|