Example #1
0
// GetTransactionsHandler returns all transactions for an account
func GetTransactionsHandler(w http.ResponseWriter, request *http.Request) {
	userID := context.Get(request, "currentId").(string)
	vars := mux.Vars(request)
	accountID := vars["accountID"]
	from, err := strconv.Atoi(vars["from"])
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	to, err := strconv.Atoi(vars["to"])
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	if accountID == "" {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	if isLink, err := models.IsLinkUserAccount(userID, accountID); err != nil || isLink != true {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}
	transactions, err := models.FindTransactionsForAccount(accountID, from, to)
	if err != nil {
		log.Fatal(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	if err = json.NewEncoder(w).Encode(transactions); err != nil {
		log.Fatal(err)
		w.WriteHeader(http.StatusInternalServerError)
	}
}
Example #2
0
// CreateTransactionHandler creates a transaction from the json body data
func CreateTransactionHandler(w http.ResponseWriter, request *http.Request) {
	userID := context.Get(request, "currentId").(string)
	body, err := JSONBodyParser(request)
	if err != nil {
		log.Fatal(err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	vars := mux.Vars(request)
	accountID := body["accountId"].(string)
	label := body["label"].(string)
	value, ok := body["value"].(float64)
	if ok != true {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	categoryID := body["categoryId"].(string)
	if ok != true || accountID == "" || label == "" || accountID != vars["accountID"] || categoryID == "" {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	if isLink, err := models.IsLinkUserAccount(userID, accountID); err != nil || isLink != true {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	var information string
	if body["information"] != nil {
		information = body["information"].(string)
	}

	transaction := models.Transaction{
		Label:       label,
		Date:        time.Now(),
		Information: information,
		Value:       value,
		Validate:    false,
		AccountID:   accountID,
		CategoryID:  categoryID,
	}
	_, err = models.CreateTransaction(&transaction)
	if err != nil {
		log.Fatal(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	if err = json.NewEncoder(w).Encode(transaction); err != nil {
		log.Fatal(err)
		w.WriteHeader(http.StatusInternalServerError)
	}
}