70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package application
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
|
|
"github.com/gorilla/mux"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func (h ApplicationHandler) CreditWallet(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
userid := vars["userid"]
|
|
|
|
if r.Method != "POST" {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
r.ParseForm()
|
|
|
|
amountStr := r.FormValue("amount")
|
|
|
|
amount, err := strconv.ParseFloat(amountStr, 64)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("could not read amount")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := h.creditWallet(userid, amount); err != nil {
|
|
log.Error().Err(err).Msg("could not credit wallet")
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.Redirect(w, r, r.Referer(), http.StatusFound)
|
|
}
|
|
|
|
func (h *ApplicationHandler) creditWallet(userid string, amount float64) error {
|
|
account, err := h.services.GetAccount(userid)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("could not retrieve account")
|
|
return err
|
|
}
|
|
|
|
if account.Data["wallet"] == nil {
|
|
account.Data["wallet"] = float64(0)
|
|
}
|
|
|
|
account.Data["wallet"] = account.Data["wallet"].(float64) + amount
|
|
accountproto, err := grpcapi.AccountFromStorageType(&account)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("account type transformation issue")
|
|
return err
|
|
}
|
|
|
|
_, err = h.services.GRPC.MobilityAccounts.UpdateData(context.Background(), &grpcapi.UpdateDataRequest{
|
|
Account: accountproto,
|
|
})
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("account type transformation issue")
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|