Last active
November 10, 2017 21:22
-
-
Save wilk/881373641cd214a1b3d15ce0fd052c15 to your computer and use it in GitHub Desktop.
Goxfer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"errors" | |
"strings" | |
"github.com/parnurzeal/gorequest" | |
) | |
type Transaction struct { | |
Date string | |
Account string | |
Description string | |
Amount float64 | |
Tags []string | |
} | |
type AddResponseBody struct { | |
Response struct { | |
Status string `json:"status"` | |
} `json:"response"` | |
} | |
var ( | |
EXPENSE_ACCOUNT_ID int | |
INCOME_ACCOUNT_ID int | |
EXPENSE_ACCOUNT_BUXFER = os.Getenv("EXPENSE_ACCOUNT_BUXFER") | |
BUXFER_API_URL = os.Getenv("BUXFER_API_ENDPOINT") | |
) | |
func addTransaction(transaction Transaction, token string) error { | |
request := gorequest.New() | |
accountId := INCOME_ACCOUNT_ID | |
accountType := "income" | |
if transaction.Account == EXPENSE_ACCOUNT_BUXFER { | |
accountId = EXPENSE_ACCOUNT_ID | |
accountType = "expense" | |
} | |
dates := strings.Split(transaction.Date, "/") | |
date := dates[2] + "-" + dates[1] + "-" + dates[0] | |
payload := map[string]interface{}{ | |
"description": transaction.Description, | |
"amount": transaction.Amount, | |
"accountId": accountId, | |
"tags": strings.Join(transaction.Tags[:], ","), | |
"date": date, | |
"token": token, | |
"type": accountType, | |
} | |
var body AddResponseBody | |
res, _, errs := request.Post(BUXFER_API_URL + "/add_transaction"). | |
Send(payload). | |
EndStruct(&body) | |
if len(errs) > 0 { | |
return errs[0] | |
} | |
if res.StatusCode > 399 { | |
return errors.New(res.Status) | |
} | |
if body.Response.Status != "OK" { | |
return errors.New("An error occurred during the transaction upload") | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment