naise_pos/api/user.go

76 lines
2.1 KiB
Go
Raw Normal View History

2023-03-13 09:24:59 +07:00
package api
import (
"database/sql"
"net/http"
db "git.nochill.in/nochill/naice_pos/db/sqlc"
2023-03-14 12:04:03 +07:00
"git.nochill.in/nochill/naice_pos/util"
2023-03-13 09:24:59 +07:00
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/lib/pq"
)
2023-03-14 12:04:03 +07:00
type createUserMerchantRequest struct {
2023-03-13 09:24:59 +07:00
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"`
}
2023-03-14 12:04:03 +07:00
type createUserMerchantResponse struct {
2023-03-13 09:24:59 +07:00
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"`
}
2023-03-14 12:04:03 +07:00
func (server *Server) createUserMerchant(ctx *gin.Context) {
var req createUserMerchantRequest
2023-03-13 09:24:59 +07:00
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, errorResponse(err))
return
}
2023-03-14 12:04:03 +07:00
hashedPassword, err := util.HashPassword(req.Password)
if err != nil {
ctx.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
2023-03-13 09:24:59 +07:00
arg := db.UserMerchantTxParams{
Email: req.Email,
Fullname: req.Fullname,
2023-03-14 12:04:03 +07:00
Password: hashedPassword,
2023-03-13 09:24:59 +07:00
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
}
2023-03-14 12:04:03 +07:00
res := createUserMerchantResponse{
2023-03-13 09:24:59 +07:00
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)
}