bottin-agenda/handlers/transaction.go
Victor Lacasse-Beaudoin 7fa4db7ab9 Ajouter transactions
Ajouter POST /v2/transactions

Valide si une transaction avec la même combinaison membre_id + is_perpetual existe déjà dans une des transactions proposées.
2023-06-06 02:22:57 -04:00

77 lines
1.9 KiB
Go

package handlers
import (
"fmt"
"net/http"
"git.agecem.com/agecem/bottin-agenda/data"
"git.agecem.com/agecem/bottin-agenda/models"
"git.agecem.com/agecem/bottin-agenda/responses"
"github.com/labstack/echo/v4"
)
func PostTransactions(c echo.Context) error {
var statusCode int = http.StatusInternalServerError
var response responses.PostTransactionsResponse
var transactions []models.Transaction
if err := c.Bind(&transactions); err != nil {
statusCode = http.StatusBadRequest
response.Message = fmt.Sprintf("Error during c.Bind(): %s", err)
return c.JSON(statusCode, response)
}
client, err := data.NewDataClientFromViper()
if err != nil {
response.Message = fmt.Sprintf("Error during data.NewDataClientFromViper(): %s", err)
return c.JSON(statusCode, response)
}
defer client.DB.Close()
if len(transactions) == 0 {
response.Message = fmt.Sprintf("Nothing to do")
statusCode = http.StatusOK
return c.JSON(statusCode, response)
}
// Check for already-existing transactions
for _, transaction := range transactions {
transaction, err := client.GetTransaction(transaction.MembreID, transaction.IsPerpetual)
if err != nil {
if err.Error() != "sql: no rows in result set" {
response.Message = fmt.Sprintf("Error during client.GetTransaction(): %s", err)
}
}
if transaction.ID != "" {
agendaType := "non-perpetual"
if transaction.IsPerpetual {
agendaType = "perpetual"
}
response.Message = fmt.Sprintf("Membre %s already received %s", transaction.MembreID, agendaType)
statusCode = http.StatusBadRequest
return c.JSON(statusCode, response)
}
}
rows, err := client.InsertTransactions(transactions)
if err != nil {
response.Message = fmt.Sprintf("Error during client.InsertTransactions(): %s", err)
return c.JSON(statusCode, response)
}
response.Data.RowsInserted = rows
statusCode = http.StatusCreated
response.Message = "Insert successful"
return c.JSON(statusCode, response)
}