naise_pos/api/user.go

76 lines
2.1 KiB
Go

package api
import (
"database/sql"
"net/http"
db "git.nochill.in/nochill/naice_pos/db/sqlc"
"git.nochill.in/nochill/naice_pos/util"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/lib/pq"
)
type createUserMerchantRequest struct {
Email string `json:"email" binding:"required,email"`
Fullname string `json:"fullname" binding:"required"`
Password string `json:"password" binding:"required"`
OutletName string `json:"outlet_name" binding:"required"`
}
type createUserMerchantResponse struct {
ID uuid.UUID `json:"id"`
IndexID int64 `json:"index_id"`
Email string `json:"email"`
Fullname string `json:"fullname"`
CreatedAt sql.NullTime `json:"created_at"`
UpdatedAt sql.NullTime `json:"updated_at"`
Outlet db.Merchant `json:"outlet"`
}
func (server *Server) createUserMerchant(ctx *gin.Context) {
var req createUserMerchantRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, errorResponse(err))
return
}
hashedPassword, err := util.HashPassword(req.Password)
if err != nil {
ctx.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
arg := db.UserMerchantTxParams{
Email: req.Email,
Fullname: req.Fullname,
Password: hashedPassword,
OutletName: req.OutletName,
}
user, err := server.store.CreateUserMerchantTx(ctx, arg)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
switch pqErr.Code.Name() {
case "foreign_key_violation", "unique_violation":
ctx.JSON(http.StatusConflict, errorResponse(err))
return
}
}
ctx.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
res := createUserMerchantResponse{
ID: user.OwnerProfile.ID,
IndexID: user.OwnerProfile.IndexID,
Email: user.OwnerProfile.Email,
Fullname: user.OwnerProfile.Fullname,
CreatedAt: sql.NullTime{Valid: true, Time: user.OutletProfile.CreatedAt.Time},
UpdatedAt: sql.NullTime{Valid: true, Time: user.OutletProfile.UpdatedAt.Time},
Outlet: user.OutletProfile,
}
ctx.JSON(http.StatusOK, res)
}