Beispiel #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)
	}
}
func TestTransaction(t *testing.T) {
	//load mock values
	defer models.Db.Exec("DELETE FROM users")
	defer models.Db.Exec("DELETE FROM account")
	defer models.Db.Exec("DELETE FROM users_account")
	defer models.Db.Exec("DELETE FROM category")
	defer models.Db.Exec("DELETE FROM transaction")
	if err := models.ExecSQLScript("test_transaction.sql"); err != nil {
		panic(err)
	}

	transactionLabel := "label"
	transactionValue := -120.0
	accountID := "3fd155dc-7a6f-4bac-a74b-902df936ed75"
	categoryID := "fe36bfe6-bf22-45fe-babd-a3db9d324727"
	testDate := time.Now()

	transaction := models.Transaction{
		Label:      transactionLabel,
		Date:       testDate,
		Value:      transactionValue,
		Validate:   false,
		AccountID:  accountID,
		CategoryID: categoryID,
	}

	_, err := models.CreateTransaction(&transaction)
	if err != nil {
		t.Errorf("Error unable to create transaction : %s", err)
	}

	transactions, err := models.FindTransactionsForAccount(accountID, 0, 10)
	if err != nil {
		t.Errorf("Error unable to fetch transactions : %s", err)
	}

	if len(transactions) != 1 {
		t.Errorf("Count transactions failed %d != 1", len(transactions))
		return
	}
	if transactions[0].Label != transactionLabel {
		t.Errorf("Bad transaction label '%s'", transactions[0].Label)
	}
	if transactions[0].Value != transactionValue {
		t.Errorf("Bad transaction label '%s'", transactions[0].Value)
	}
	if transactions[0].Date.Equal(testDate) {
		t.Errorf("Bad transaction label '%s' vs '%s'", transactions[0].Date, testDate)
	}

	//Test trigger
	rows, err := models.Db.Query("SELECT value FROM account")
	if err != nil {
		t.Error(err)
		return
	}
	if rows.Next() {
		var value float64
		err := rows.Scan(&value)
		if err != nil {
			t.Error(err)
			return
		}
		if value != -20.0 {
			t.Errorf("Error trigger : %f != -20.0", value)
		}
	} else {
		t.Errorf("bad query")
	}

}