init project

This commit is contained in:
aditya.siregar
2024-05-28 14:14:55 +07:00
commit 67f1dbc850
141 changed files with 16879 additions and 0 deletions
+79
View File
@@ -0,0 +1,79 @@
package auth
import (
"furtuna-be/internal/constants/role"
"net/http"
"github.com/gin-gonic/gin"
"furtuna-be/internal/common/errors"
auth2 "furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
)
type AuthHandler struct {
service services.Auth
}
func (a *AuthHandler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
authRoute := group.Group("/auth")
authRoute.POST("/login", a.AuthLogin)
}
func NewAuthHandler(service services.Auth) *AuthHandler {
return &AuthHandler{
service: service,
}
}
// AuthLogin handles the authentication process for user login.
// @Summary User login
// @Description Authenticates a user based on the provided credentials and returns a JWT token.
// @Accept json
// @Produce json
// @Param bodyParam body auth2.LoginRequest true "User login credentials"
// @Success 200 {object} response.BaseResponse{data=response.LoginResponse} "Login successful"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/auth/login [post]
// @Tags Auth Login API's
func (h *AuthHandler) AuthLogin(c *gin.Context) {
var bodyParam auth2.LoginRequest
if err := c.ShouldBindJSON(&bodyParam); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
authUser, err := h.service.AuthenticateUser(c, bodyParam.Email, bodyParam.Password)
if err != nil {
response.ErrorWrapper(c, err)
return
}
var branch *response.Branch
if authUser.RoleID != role.SuperAdmin {
branch = &response.Branch{
ID: authUser.BranchID,
Name: authUser.BranchName,
}
}
resp := response.LoginResponse{
Token: authUser.Token,
Branch: branch,
Name: authUser.Name,
Role: response.Role{
ID: int64(authUser.RoleID),
Role: authUser.RoleName,
},
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Message: "Login Success",
Data: resp,
})
}
+264
View File
@@ -0,0 +1,264 @@
package branch
import (
"furtuna-be/internal/common/errors"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
type Handler struct {
service services.Branch
}
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/branch")
route.POST("/", jwt, h.Create)
route.GET("/list", jwt, h.GetAll)
route.PUT("/:id", jwt, h.Update)
route.GET("/:id", jwt, h.GetByID)
route.DELETE("/:id", jwt, h.Delete)
}
func NewHandler(service services.Branch) *Handler {
return &Handler{
service: service,
}
}
// Create handles the creation of a new branch.
// @Summary Create a new branch
// @Description Create a new branch based on the provided data.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param req body request.Branch true "New branch details"
// @Success 200 {object} response.BaseResponse{data=response.Branch} "Branch created successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/branch [post]
// @Tags Branch APIs
func (h *Handler) Create(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.Branch
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
res, err := h.service.Create(ctx, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toBranchResponse(res),
})
}
// Update handles the update of an existing branch.
// @Summary Update an existing branch
// @Description Update the details of an existing branch based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Branch ID to update"
// @Param req body request.Branch true "Updated branch details"
// @Success 200 {object} response.BaseResponse{data=response.Branch} "Branch updated successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/branch/{id} [put]
// @Tags Branch APIs
func (h *Handler) Update(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
branchID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
var req request.Branch
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
updatedBranch, err := h.service.Update(ctx, branchID, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toBranchResponse(updatedBranch),
})
}
// GetAll retrieves a list of branches.
// @Summary Get a list of branches
// @Description Get a paginated list of branches based on query parameters.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param Limit query int false "Number of items to retrieve (default 10)"
// @Param Offset query int false "Offset for pagination (default 0)"
// @Success 200 {object} response.BaseResponse{data=response.BranchList} "List of branches"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/branch/list [get]
// @Tags Branch APIs
func (h *Handler) GetAll(c *gin.Context) {
var req request.BranchParam
if err := c.ShouldBindQuery(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
branchs, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toBranchResponseList(branchs, int64(total), req),
})
}
// Delete handles the deletion of a branch by ID.
// @Summary Delete a branch by ID
// @Description Delete a branch based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Branch ID to delete"
// @Success 200 {object} response.BaseResponse "Branch deleted successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/branch/{id} [delete]
// @Tags Branch APIs
func (h *Handler) Delete(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
// Parse the ID into a uint
branchID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
err = h.service.Delete(ctx, branchID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: nil,
})
}
// GetByID retrieves details of a specific branch by ID.
// @Summary Get details of a branch by ID
// @Description Get details of a branch based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Branch ID to retrieve"
// @Success 200 {object} response.BaseResponse{data=response.Branch} "Branch details"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/branch/{id} [get]
// @Tags Branch APIs
func (h *Handler) GetByID(c *gin.Context) {
id := c.Param("id")
// Parse the ID into a uint
branchID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
res, err := h.service.GetByID(c.Request.Context(), branchID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toBranchResponse(res),
})
}
func (h *Handler) toBranchResponse(resp *entity.Branch) response.Branch {
return response.Branch{
ID: &resp.ID,
Name: resp.Name,
Status: string(resp.Status),
Location: resp.Location,
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
}
}
func (h *Handler) toBranchResponseList(resp []*entity.Branch, total int64, req request.BranchParam) response.BranchList {
var branches []response.Branch
for _, b := range resp {
branches = append(branches, h.toBranchResponse(b))
}
return response.BranchList{
Branches: branches,
Total: total,
Limit: req.Limit,
Offset: req.Offset,
}
}
+205
View File
@@ -0,0 +1,205 @@
package event
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"furtuna-be/internal/common/errors"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
)
type Handler struct {
service services.Event
}
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/event")
route.POST("/", jwt, h.Create)
route.GET("/list", jwt, h.GetAll)
route.PUT("/:id", jwt, h.Update)
route.GET("/:id", jwt, h.GetByID)
route.DELETE("/:id", jwt, h.Delete)
}
func NewHandler(service services.Event) *Handler {
return &Handler{
service: service,
}
}
func (h *Handler) Create(c *gin.Context) {
var req request.Event
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
if err := req.Validate(); err != nil {
response.ErrorWrapper(c, errors.ErrorInvalidRequest)
return
}
res, err := h.service.Create(c.Request.Context(), req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toEventResponse(res),
})
}
func (h *Handler) Update(c *gin.Context) {
id := c.Param("id")
eventID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
var req request.Event
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
if err := req.Validate(); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
updatedEvent, err := h.service.Update(c.Request.Context(), eventID, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toEventResponse(updatedEvent),
})
}
func (h *Handler) GetAll(c *gin.Context) {
var req request.EventParam
if err := c.ShouldBindQuery(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
events, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toEventResponseList(events, int64(total), req),
})
}
func (h *Handler) Delete(c *gin.Context) {
id := c.Param("id")
// Parse the ID into a uint
eventID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
err = h.service.Delete(c.Request.Context(), eventID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: nil,
})
}
func (h *Handler) GetByID(c *gin.Context) {
id := c.Param("id")
// Parse the ID into a uint
eventID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
res, err := h.service.GetByID(c.Request.Context(), eventID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toEventResponse(res),
})
}
func (h *Handler) toEventResponse(resp *entity.Event) response.Event {
return response.Event{
ID: resp.ID,
Name: resp.Name,
Description: resp.Description,
StartDate: resp.StartDate.Format("2006-01-02"),
EndDate: resp.EndDate.Format("2006-01-02"),
StartTime: resp.StartDate.Format("15:04:05"),
EndTime: resp.EndDate.Format("15:04:05"),
Location: resp.Location,
Level: resp.Level,
Included: resp.Included,
Price: resp.Price,
Paid: resp.Paid,
LocationID: resp.LocationID,
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
Status: string(resp.Status),
}
}
func (h *Handler) toEventResponseList(resp []*entity.Event, total int64, req request.EventParam) response.EventList {
var events []response.Event
for _, evt := range resp {
events = append(events, h.toEventResponse(evt))
}
return response.EventList{
Events: events,
Total: total,
Limit: req.Limit,
Offset: req.Offset,
}
}
+409
View File
@@ -0,0 +1,409 @@
package order
import (
"furtuna-be/internal/common/errors"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
type Handler struct {
service services.Order
}
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/order")
route.POST("/", jwt, h.Create)
route.GET("/list", jwt, h.GetAll)
route.GET("/:id", jwt, h.GetByID)
route.GET("/total-revenue", jwt, h.GetTotalRevenue)
route.GET("/yearly-revenue/:year", jwt, h.GetYearlyRevenue)
route.GET("/branch-revenue", jwt, h.GetBranchRevenue)
route.PUT("/update-status/:id", jwt, h.UpdateStatus)
}
func NewHandler(service services.Order) *Handler {
return &Handler{
service: service,
}
}
// Create handles the creation of a new order.
// @Summary Create a new order
// @Description Create a new order with the provided details.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param order body request.Order true "Order details"
// @Success 200 {object} response.BaseResponse "Order created successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/order [post]
// @Tag Order APIs
func (h *Handler) Create(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.Order
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
err := h.service.Create(ctx, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
})
}
// UpdateStatus handles the update of the order status.
// @Summary Update the status of an order
// @Description Update the status of the specified order with the provided details.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path string true "Order ID"
// @Param status body request.UpdateStatus true "Status details"
// @Success 200 {object} response.BaseResponse{data=response.Order} "Order status updated successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Failure 500 {object} response.BaseResponse "Internal server error"
// @Router /api/v1/order/update-status/{id} [put]
// @Tag Order APIs
func (h *Handler) UpdateStatus(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.UpdateStatus
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
id := c.Param("id")
// Parse the ID into a uint
orderID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
res, err := h.service.UpdateStatus(ctx, orderID, req.ToEntity())
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toOrderResponse(res),
})
}
// GetByID retrieves the details of a specific order by ID.
// @Summary Get details of an order by ID
// @Description Retrieve the details of the specified order by ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path string true "Order ID"
// @Success 200 {object} response.BaseResponse{data=response.Order} "Order details retrieved successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Failure 500 {object} response.BaseResponse "Internal server error"
// @Router /api/v1/order/{id} [get]
// @Tag Order APIs
func (h *Handler) GetByID(c *gin.Context) {
id := c.Param("id")
// Parse the ID into a uint
orderID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
res, err := h.service.GetByID(c.Request.Context(), orderID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toOrderResponse(res),
})
}
// GetAll retrieves a list of orders based on the specified parameters.
// @Summary Get a list of orders
// @Description Retrieve a list of orders based on the specified parameters.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param limit query int false "Number of items to retrieve (default: 10)"
// @Param offset query int false "Number of items to skip (default: 0)"
// @Success 200 {object} response.BaseResponse{data=response.OrderList} "List of orders retrieved successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Failure 500 {object} response.BaseResponse "Internal server error"
// @Router /api/v1/order/list [get]
// @Tag Order APIs
func (h *Handler) GetAll(c *gin.Context) {
var req request.OrderParam
if err := c.ShouldBindQuery(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
orders, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toOrderResponseList(orders, int64(total), req),
})
}
// GetTotalRevenue retrieves the total revenue and number of transactions for orders.
// @Summary Get total revenue and number of transactions for orders
// @Description Retrieve the total revenue and number of transactions for orders based on the specified parameters.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param start_date query string false "Start date for filtering (format: 'YYYY-MM-DD')"
// @Param end_date query string false "End date for filtering (format: 'YYYY-MM-DD')"
// @Success 200 {object} response.BaseResponse{data=response.OrderMonthlyRevenue} "Total revenue and transactions retrieved successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Failure 500 {object} response.BaseResponse "Internal server error"
// @Router /api/v1/order/total-revenue [get]
// @Tag Order APIs
func (h *Handler) GetTotalRevenue(c *gin.Context) {
var req request.OrderTotalRevenueParam
if err := c.ShouldBindQuery(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
rev, trans, err := h.service.GetTotalRevenue(c.Request.Context(), req.ToEntity())
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toOrderTotalRevenueResponse(rev, trans),
})
}
// GetYearlyRevenue retrieves the yearly revenue for orders.
// @Summary Get yearly revenue for orders
// @Description Retrieve the yearly revenue for orders based on the specified year.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param year path int true "Year for filtering"
// @Success 200 {object} response.BaseResponse{data=map[int]map[string]float64} "Yearly revenue retrieved successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Failure 500 {object} response.BaseResponse "Internal server error"
// @Router /api/v1/order/yearly-revenue/{year} [get]
// @Tag Order APIs
func (h *Handler) GetYearlyRevenue(c *gin.Context) {
yearParam := c.Param("year")
// Parse the ID into a uint
year, err := strconv.Atoi(yearParam)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
rev, err := h.service.GetYearlyRevenue(c.Request.Context(), year)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toOrderYearlyRevenueResponse(rev),
})
}
// GetBranchRevenue retrieves the branch-wise revenue for orders.
// @Summary Get branch-wise revenue for orders
// @Description Retrieve the branch-wise revenue for orders based on the specified parameters.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param branch_id query int false "Branch ID for filtering"
// @Param start_date query string false "Start date for filtering (format: 'YYYY-MM-DD')"
// @Param end_date query string false "End date for filtering (format: 'YYYY-MM-DD')"
// @Success 200 {object} response.BaseResponse{data=[]response.OrderBranchRevenue} "Branch-wise revenue retrieved successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Failure 500 {object} response.BaseResponse "Internal server error"
// @Router /api/v1/order/branch-revenue [get]
// @Tag Order APIs
func (h *Handler) GetBranchRevenue(c *gin.Context) {
var req request.OrderBranchRevenueParam
if err := c.ShouldBindQuery(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
rev, err := h.service.GetBranchRevenue(c.Request.Context(), req.ToEntity())
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toOrderBranchRevenueResponse(rev),
})
}
func (h *Handler) toOrderResponse(resp *entity.Order) response.Order {
orderItems := []response.OrderItem{}
for _, i := range resp.OrderItem {
orderItems = append(orderItems, response.OrderItem{
OrderItemID: i.OrderItemID,
ItemID: i.ItemID,
ItemType: i.ItemType,
ItemName: i.ItemName,
Price: i.Price,
Qty: i.Qty,
CreatedAt: i.CreatedAt.Format(time.RFC3339),
UpdatedAt: i.CreatedAt.Format(time.RFC3339),
})
}
return response.Order{
ID: resp.ID,
BranchID: resp.BranchID,
BranchName: resp.BranchName,
Amount: resp.Amount,
OrderItem: orderItems,
Status: resp.Status,
CustomerName: resp.CustomerName,
CustomerPhone: resp.CustomerPhone,
Pax: resp.Pax,
PaymentMethod: resp.Transaction.PaymentMethod,
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
}
}
func (h *Handler) toOrderResponseList(resp []*entity.Order, total int64, req request.OrderParam) response.OrderList {
var orders []response.Order
for _, b := range resp {
orders = append(orders, h.toOrderResponse(b))
}
return response.OrderList{
Orders: orders,
Total: total,
Limit: req.Limit,
Offset: req.Offset,
}
}
func (h *Handler) toOrderTotalRevenueResponse(rev float64, trans int64) response.OrderMonthlyRevenue {
return response.OrderMonthlyRevenue{
TotalRevenue: rev,
TotalTransaction: trans,
}
}
func (h *Handler) toOrderYearlyRevenueResponse(data entity.OrderYearlyRevenueList) map[int]map[string]float64 {
result := make(map[int]map[string]float64)
// Initialize result map with 0 values for all months and item types
for i := 1; i <= 12; i++ {
result[i] = map[string]float64{
"PRODUCT": 0,
"STUDIO": 0,
}
}
// Populate result map with actual data
for _, v := range data {
result[v.Month][v.ItemType] = v.Amount
}
return result
}
func (h *Handler) toOrderBranchRevenueResponse(data entity.OrderBranchRevenueList) []response.OrderBranchRevenue {
var resp []response.OrderBranchRevenue
for _, v := range data {
resp = append(resp, response.OrderBranchRevenue{
BranchID: v.BranchID,
BranchName: v.BranchName,
BranchLocation: v.BranchLocation,
TotalTransaction: v.TotalTransaction,
TotalAmount: v.TotalAmount,
})
}
return resp
}
+92
View File
@@ -0,0 +1,92 @@
package oss
import (
"fmt"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
"mime/multipart"
"net/http"
"github.com/gin-gonic/gin"
)
const _oneMB = 1 << 20 // 1MB
const _maxUploadSizeMB = 2 * _oneMB
const _folderName = "/file"
type OssHandler struct {
ossService services.OSSService
}
func (h *OssHandler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/file")
route.POST("/upload", h.UploadFile, jwt)
}
func NewOssHandler(ossService services.OSSService) *OssHandler {
return &OssHandler{
ossService: ossService,
}
}
// UploadFile handles the uploading of a file to OSS.
// @Summary Upload a file to OSS
// @Description Upload a file to Alibaba Cloud OSS with the provided details.
// @Accept mpfd
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param file formData file true "File to upload (max size: 2MB)"
// @Success 200 {object} response.BaseResponse{data=entity.UploadFileResponse} "File uploaded successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Tags File Upload API
// @Router /api/v1/file/upload [post]
func (h *OssHandler) UploadFile(c *gin.Context) {
// Get the oss file from the request form
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, response.BaseResponse{
ErrorMessage: "Failed to retrieve the file",
})
return
}
// Check if the uploaded file is an image (photo)
//if !isPDFFile(file) {
// c.JSON(http.StatusBadRequest, response.BaseResponse{
// ErrorMessage: "Only image files are allowed",
// })
// return
//}
// Check if the file size is not greater than the maximum allowed size
if file.Size > _maxUploadSizeMB {
c.JSON(http.StatusBadRequest, response.BaseResponse{
ErrorMessage: fmt.Sprintf("The file is too big. The maximum size is %d", _maxUploadSizeMB/_oneMB),
})
return
}
// Call the service to oss the file to Alibaba Cloud OSS
ret, err := h.ossService.UploadFile(c, &entity.UploadFileRequest{
FileHeader: file,
FolderName: _folderName,
})
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Data: ret,
Success: true,
})
}
func isPDFFile(file *multipart.FileHeader) bool {
contentType := file.Header.Get("Content-Type")
return contentType == "application/pdf"
}
+265
View File
@@ -0,0 +1,265 @@
package partner
import (
"furtuna-be/internal/common/errors"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/middlewares"
"furtuna-be/internal/services"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
type Handler struct {
service services.Partner
}
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/partner")
isSuperAdmin := middlewares.SuperAdminMiddleware()
route.POST("/", jwt, isSuperAdmin, h.Create)
route.GET("/list", jwt, isSuperAdmin, h.GetAll)
route.PUT("/:id", jwt, isSuperAdmin, h.Update)
route.GET("/:id", jwt, isSuperAdmin, h.GetByID)
route.DELETE("/:id", jwt, isSuperAdmin, h.Delete)
}
func NewHandler(service services.Partner) *Handler {
return &Handler{
service: service,
}
}
// Create handles the creation of a new Partner.
// @Summary Create a new Partner
// @Description Create a new Partner based on the provided data.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param req body request.Partner true "New Partner details"
// @Success 200 {object} response.BaseResponse{data=response.Partner} "Partner created successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/Partner [post]
// @Tags Partner APIs
func (h *Handler) Create(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.Partner
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
res, err := h.service.Create(ctx, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toPartnerResponse(res),
})
}
// Update handles the update of an existing Partner.
// @Summary Update an existing Partner
// @Description Update the details of an existing Partner based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Partner ID to update"
// @Param req body request.Partner true "Updated Partner details"
// @Success 200 {object} response.BaseResponse{data=response.Partner} "Partner updated successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/Partner/{id} [put]
// @Tags Partner APIs
func (h *Handler) Update(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
PartnerID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
var req request.Partner
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
updatedPartner, err := h.service.Update(ctx, PartnerID, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toPartnerResponse(updatedPartner),
})
}
// GetAll retrieves a list of Partneres.
// @Summary Get a list of Partneres
// @Description Get a paginated list of Partneres based on query parameters.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param Limit query int false "Number of items to retrieve (default 10)"
// @Param Offset query int false "Offset for pagination (default 0)"
// @Success 200 {object} response.BaseResponse{data=response.PartnerList} "List of Partneres"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/Partner/list [get]
// @Tags Partner APIs
func (h *Handler) GetAll(c *gin.Context) {
var req request.PartnerParam
if err := c.ShouldBindQuery(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
Partners, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toPartnerResponseList(Partners, int64(total), req),
})
}
// Delete handles the deletion of a Partner by ID.
// @Summary Delete a Partner by ID
// @Description Delete a Partner based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Partner ID to delete"
// @Success 200 {object} response.BaseResponse "Partner deleted successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/Partner/{id} [delete]
// @Tags Partner APIs
func (h *Handler) Delete(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
// Parse the ID into a uint
PartnerID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
err = h.service.Delete(ctx, PartnerID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: nil,
})
}
// GetByID retrieves details of a specific Partner by ID.
// @Summary Get details of a Partner by ID
// @Description Get details of a Partner based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Partner ID to retrieve"
// @Success 200 {object} response.BaseResponse{data=response.Partner} "Partner details"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/Partner/{id} [get]
// @Tags Partner APIs
func (h *Handler) GetByID(c *gin.Context) {
id := c.Param("id")
// Parse the ID into a uint
PartnerID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
res, err := h.service.GetByID(c.Request.Context(), PartnerID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toPartnerResponse(res),
})
}
func (h *Handler) toPartnerResponse(resp *entity.Partner) response.Partner {
return response.Partner{
ID: &resp.ID,
Name: resp.Name,
Status: resp.Status,
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
}
}
func (h *Handler) toPartnerResponseList(resp []*entity.Partner, total int64, req request.PartnerParam) response.PartnerList {
var Partneres []response.Partner
for _, b := range resp {
Partneres = append(Partneres, h.toPartnerResponse(b))
}
return response.PartnerList{
Partners: Partneres,
Total: total,
Limit: req.Limit,
Offset: req.Offset,
}
}
+269
View File
@@ -0,0 +1,269 @@
package product
import (
"furtuna-be/internal/common/errors"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
type Handler struct {
service services.Product
}
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/product")
route.POST("/", jwt, h.Create)
route.GET("/list", jwt, h.GetAll)
route.PUT("/:id", jwt, h.Update)
route.GET("/:id", jwt, h.GetByID)
route.DELETE("/:id", jwt, h.Delete)
}
func NewHandler(service services.Product) *Handler {
return &Handler{
service: service,
}
}
// Create handles the creation of a new product.
// @Summary Create a new product
// @Description Create a new product with the provided details.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param req body request.Product true "Product details to create"
// @Success 200 {object} response.BaseResponse{data=response.Product} "Product created successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Tags Product APIs
// @Router /api/v1/product/ [post]
func (h *Handler) Create(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.Product
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
res, err := h.service.Create(ctx, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toProductResponse(res),
})
}
// Update handles the update of an existing product.
// @Summary Update an existing product
// @Description Update the details of an existing product based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Product ID to update"
// @Param req body request.Product true "Updated product details"
// @Success 200 {object} response.BaseResponse{data=response.Product} "Product updated successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Tags Product APIs
// @Router /api/v1/product/{id} [put]
func (h *Handler) Update(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
productID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
var req request.Product
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
updatedProduct, err := h.service.Update(ctx, productID, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toProductResponse(updatedProduct),
})
}
// GetAll retrieves a list of products.
// @Summary Get a list of products
// @Description Get a paginated list of products based on query parameters.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param Limit query int false "Number of items to retrieve (default 10)"
// @Param Offset query int false "Offset for pagination (default 0)"
// @Success 200 {object} response.BaseResponse{data=response.ProductList} "List of products"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/product/list [get]
// @Tags Product APIs
func (h *Handler) GetAll(c *gin.Context) {
var req request.ProductParam
if err := c.ShouldBindQuery(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
products, total, err := h.service.GetAll(c.Request.Context(), req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toProductResponseList(products, int64(total), req),
})
}
// Delete handles the deletion of a product by ID.
// @Summary Delete a product by ID
// @Description Delete a product based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Product ID to delete"
// @Success 200 {object} response.BaseResponse "Product deleted successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/product/{id} [delete]
// @Tags Product APIs
func (h *Handler) Delete(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
// Parse the ID into a uint
productID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
err = h.service.Delete(ctx, productID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: nil,
})
}
// GetByID retrieves details of a specific product by ID.
// @Summary Get details of a product by ID
// @Description Get details of a product based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Product ID to retrieve"
// @Success 200 {object} response.BaseResponse{data=response.Product} "Product details"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/product/{id} [get]
// @Tags Product APIs
func (h *Handler) GetByID(c *gin.Context) {
id := c.Param("id")
// Parse the ID into a uint
productID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
res, err := h.service.GetByID(c.Request.Context(), productID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toProductResponse(res),
})
}
func (h *Handler) toProductResponse(resp *entity.Product) response.Product {
return response.Product{
ID: resp.ID,
Name: resp.Name,
Type: resp.Type,
Price: resp.Price,
Status: resp.Status,
Description: resp.Description,
Image: resp.Image,
BranchID: resp.BranchID,
StockQty: resp.StockQty,
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
}
}
func (h *Handler) toProductResponseList(resp []*entity.Product, total int64, req request.ProductParam) response.ProductList {
var products []response.Product
for _, b := range resp {
products = append(products, h.toProductResponse(b))
}
return response.ProductList{
Products: products,
Total: total,
Limit: req.Limit,
Offset: req.Offset,
}
}
+232
View File
@@ -0,0 +1,232 @@
package studio
import (
"encoding/json"
"furtuna-be/internal/common/errors"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
type StudioHandler struct {
service services.Studio
}
func (h *StudioHandler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/studio")
route.POST("/", jwt, h.Create)
route.PUT("/:id", jwt, h.Update)
route.GET("/:id", jwt, h.GetByID)
route.GET("/search", jwt, h.Search)
}
func NewStudioHandler(service services.Studio) *StudioHandler {
return &StudioHandler{
service: service,
}
}
// Create handles the creation of a new studio.
// @Summary Create a new studio
// @Description Create a new studio based on the provided details.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param req body request.Studio true "New studio details"
// @Success 200 {object} response.BaseResponse{data=response.Studio} "Studio created successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/studio [post]
// @Tags Studio APIs
func (h *StudioHandler) Create(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.Studio
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
res, err := h.service.Create(ctx, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toStudioResponse(res),
})
}
// Update handles the update of an existing studio.
// @Summary Update an existing studio
// @Description Update the details of an existing studio based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Studio ID to update"
// @Param req body request.Studio true "Updated studio details"
// @Success 200 {object} response.BaseResponse{data=response.Studio} "Studio updated successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/studio/{id} [put]
// @Tags Studio APIs
func (h *StudioHandler) Update(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
studioID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
var req request.Studio
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
updatedStudio, err := h.service.Update(ctx, studioID, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toStudioResponse(updatedStudio),
})
}
// Search retrieves a list of studios based on search criteria.
// @Summary Search for studios
// @Description Search for studios based on query parameters.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param Name query string false "Studio name for search"
// @Param Status query string false "Studio status for search"
// @Param Limit query int false "Number of items to retrieve (default 10)"
// @Param Offset query int false "Offset for pagination (default 0)"
// @Success 200 {object} response.BaseResponse{data=response.StudioList} "List of studios"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/studio/search [get]
// @Tags Studio APIs
func (h *StudioHandler) Search(c *gin.Context) {
var req request.StudioParam
if err := c.ShouldBindQuery(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
studios, total, err := h.service.Search(c.Request.Context(), req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toStudioResponseList(studios, int64(total), req),
})
}
// GetByID retrieves details of a specific studio by ID.
// @Summary Get details of a studio by ID
// @Description Get details of a studio based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "Studio ID to retrieve"
// @Success 200 {object} response.BaseResponse{data=response.Studio} "Studio details"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/studio/{id} [get]
// @Tags Studio APIs
func (h *StudioHandler) GetByID(c *gin.Context) {
id := c.Param("id")
studioID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
res, err := h.service.GetByID(c.Request.Context(), studioID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toStudioResponse(res),
})
}
func (h *StudioHandler) toStudioResponse(resp *entity.Studio) response.Studio {
metadata := make(map[string]interface{})
if err := json.Unmarshal(resp.Metadata, &metadata); err != nil {
//TODO taufanvps
// Handle the error if the metadata cannot be unmarshaled.
}
return response.Studio{
ID: &resp.ID,
BranchId: &resp.BranchId,
Name: resp.Name,
Status: string(resp.Status),
Price: resp.Price,
Metadata: metadata,
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
}
}
func (h *StudioHandler) toStudioResponseList(resp []*entity.Studio, total int64, req request.StudioParam) response.StudioList {
var studios []response.Studio
for _, b := range resp {
studios = append(studios, h.toStudioResponse(b))
}
return response.StudioList{
Studios: studios,
Total: total,
Limit: req.Limit,
Offset: req.Offset,
}
}
+288
View File
@@ -0,0 +1,288 @@
package user
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"furtuna-be/internal/common/errors"
"furtuna-be/internal/entity"
"furtuna-be/internal/handlers/request"
"furtuna-be/internal/handlers/response"
"furtuna-be/internal/services"
)
type Handler struct {
service services.User
}
func (h *Handler) Route(group *gin.RouterGroup, jwt gin.HandlerFunc) {
route := group.Group("/user")
route.POST("/", jwt, h.Create)
route.GET("/list", jwt, h.GetAll)
route.GET("/:id", jwt, h.GetByID)
route.PUT("/:id", jwt, h.Update)
route.DELETE("/:id", jwt, h.Delete)
}
func NewHandler(service services.User) *Handler {
return &Handler{
service: service,
}
}
// Create handles the creation of a new user.
// @Summary Create a new user
// @Description Create a new user based on the provided data.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param req body request.User true "New user details"
// @Success 200 {object} response.BaseResponse{data=response.User} "User created successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/user [post]
// @Tags User APIs
func (h *Handler) Create(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.User
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
if err := req.Validate(); err != nil {
response.ErrorWrapper(c, errors.ErrorInvalidRequest)
return
}
res, err := h.service.Create(ctx, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
resp := response.User{
ID: res.ID,
Name: res.Name,
Email: res.Email,
RoleID: int64(res.RoleID),
PartnerID: res.PartnerID,
Status: string(res.Status),
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: resp,
})
}
// Update handles the update of an existing user.
// @Summary Update an existing user
// @Description Update the details of an existing user based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "User ID to update"
// @Param req body request.User true "Updated user details"
// @Success 200 {object} response.BaseResponse{data=response.User} "User updated successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/user/{id} [put]
// @Tags User APIs
func (h *Handler) Update(c *gin.Context) {
ctx := request.GetMyContext(c)
if !ctx.IsSuperAdmin() {
response.ErrorWrapper(c, errors.ErrorUnauthorized)
return
}
id := c.Param("id")
userID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
var req request.User
if err := c.ShouldBindJSON(&req); err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
updatedUser, err := h.service.Update(ctx, userID, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toUserResponse(updatedUser),
})
}
// GetAll retrieves a list of users.
// @Summary Get a list of users
// @Description Get a paginated list of users based on query parameters.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param Limit query int false "Number of items to retrieve (default 10)"
// @Param Offset query int false "Offset for pagination (default 0)"
// @Success 200 {object} response.BaseResponse{data=response.UserList} "List of users"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/user/list [get]
// @Tags User APIs
func (h *Handler) GetAll(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.UserParam
if err := c.ShouldBindQuery(&req); err != nil {
}
if !ctx.IsSuperAdmin() {
response.ErrorWrapper(c, errors.ErrorUnauthorized)
return
}
users, total, err := h.service.GetAll(ctx, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toUserResponseList(users, int64(total), req),
})
}
// GetByID retrieves details of a specific user by ID.
// @Summary Get details of a user by ID
// @Description Get details of a user based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "User ID to retrieve"
// @Success 200 {object} response.BaseResponse{data=response.User} "User details"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/user/{id} [get]
// @Tags User APIs
func (h *Handler) GetByID(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
// Parse the ID into a uint
userID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
res, err := h.service.GetByID(ctx, userID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toUserResponse(res),
})
}
// Delete handles the deletion of a user by ID.
// @Summary Delete a user by ID
// @Description Delete a user based on the provided ID.
// @Accept json
// @Produce json
// @Param Authorization header string true "JWT token"
// @Param id path int64 true "User ID to delete"
// @Success 200 {object} response.BaseResponse "User deleted successfully"
// @Failure 400 {object} response.BaseResponse{data=errors.Error} "Bad request"
// @Failure 401 {object} response.BaseResponse{data=errors.Error} "Unauthorized"
// @Router /api/v1/user/{id} [delete]
// @Tags User APIs
func (h *Handler) Delete(c *gin.Context) {
ctx := request.GetMyContext(c)
id := c.Param("id")
// Parse the ID into a uint
userID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
err = h.service.Delete(ctx, userID)
if err != nil {
c.JSON(http.StatusInternalServerError, response.BaseResponse{
Success: false,
Status: http.StatusInternalServerError,
Message: err.Error(),
Data: nil,
})
return
}
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: nil,
})
}
func (h *Handler) toUserResponse(resp *entity.User) response.User {
return response.User{
ID: resp.ID,
Name: resp.Name,
Email: resp.Email,
Status: string(resp.Status),
RoleID: int64(resp.RoleID),
RoleName: resp.RoleName,
PartnerID: resp.PartnerID,
BranchName: resp.BranchName,
CreatedAt: resp.CreatedAt.Format(time.RFC3339),
UpdatedAt: resp.CreatedAt.Format(time.RFC3339),
}
}
func (h *Handler) toUserResponseList(resp []*entity.User, total int64, req request.UserParam) response.UserList {
var users []response.User
for _, b := range resp {
users = append(users, h.toUserResponse(b))
}
return response.UserList{
Users: users,
Total: total,
Limit: req.Limit,
Offset: req.Offset,
}
}
+15
View File
@@ -0,0 +1,15 @@
package request
type LoginRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
type ResetPasswordRequest struct {
Email string `json:"email" validate:"required,email"`
}
type ResetPasswordChangeRequest struct {
Token string `json:"token" validate:"required"`
Password string `json:"password" validate:"required"`
}
+36
View File
@@ -0,0 +1,36 @@
package request
import (
"furtuna-be/internal/constants/branch"
"furtuna-be/internal/entity"
)
type BranchParam struct {
Search string `form:"search" json:"search" example:"Ketua Umum"`
Name string `form:"name" json:"name" example:"Ketua Umum"`
Limit int `form:"limit" json:"limit" example:"10"`
Offset int `form:"offset" json:"offset" example:"0"`
}
func (p *BranchParam) ToEntity() entity.BranchSearch {
return entity.BranchSearch{
Search: p.Search,
Name: p.Name,
Limit: p.Limit,
Offset: p.Offset,
}
}
type Branch struct {
Name string `json:"name" validate:"required"`
Location string `json:"location" validate:"required"`
Status branch.BranchStatus `json:"status"`
}
func (e *Branch) ToEntity() *entity.Branch {
return &entity.Branch{
Name: e.Name,
Location: e.Location,
Status: e.Status,
}
}
+21
View File
@@ -0,0 +1,21 @@
package request
import (
"furtuna-be/internal/common/mycontext"
"github.com/gin-gonic/gin"
)
func GetMyContext(c *gin.Context) mycontext.Context {
rawCtx, exists := c.Get("myCtx")
if !exists {
// handle missing context
return mycontext.NewContext(c)
}
myCtx, ok := rawCtx.(mycontext.Context)
if !ok {
return mycontext.NewContext(c)
}
return myCtx
}
+86
View File
@@ -0,0 +1,86 @@
package request
import (
"fmt"
"time"
"github.com/go-playground/validator/v10"
"furtuna-be/internal/entity"
)
type EventParam struct {
Name string `form:"name" json:"name" example:"Ketua Umum"`
Limit int `form:"limit" json:"limit" example:"10"`
Offset int `form:"offset" json:"offset" example:"0"`
}
func (p *EventParam) ToEntity() entity.EventSearch {
return entity.EventSearch{
Name: p.Name,
Limit: p.Limit,
Offset: p.Offset,
}
}
type Event struct {
Name string `json:"name" validate:"required"`
Description string `json:"description"`
StartDate string `json:"start_date" validate:"required"`
StartTime string `json:"start_time"`
EndDate string `json:"end_date" validate:"required"`
EndTime string `json:"end_time"`
Location string `json:"location" validate:"required"`
Level string `json:"level" validate:"required"`
Included []string `json:"included"`
Price float64 `json:"price"`
Paid bool `json:"paid"`
Status entity.Status `json:"status"`
LocationID int64 `json:"location_id"`
startDateTime time.Time
endDateTime time.Time
}
func (e *Event) ToEntity() *entity.Event {
return &entity.Event{
Name: e.Name,
Description: e.Description,
StartDate: e.startDateTime,
EndDate: e.endDateTime,
Location: e.Location,
Level: e.Level,
Included: e.Included,
Price: e.Price,
Paid: e.Paid,
LocationID: &e.LocationID,
Status: e.Status,
}
}
func (e *Event) Validate() error {
validate := validator.New()
if err := validate.Struct(e); err != nil {
return err
}
startDateTimeStr := e.StartDate + "T" + e.StartTime + "Z"
endDateTimeStr := e.EndDate + "T" + e.EndTime + "Z"
startDateTime, err := time.Parse(time.RFC3339, startDateTimeStr)
if err != nil {
fmt.Println("Error parsing start date-time:", err)
return err
}
e.startDateTime = startDateTime
endDateTime, err := time.Parse(time.RFC3339, endDateTimeStr)
if err != nil {
fmt.Println("Error parsing end date-time:", err)
return err
}
e.endDateTime = endDateTime
return nil
}
+116
View File
@@ -0,0 +1,116 @@
package request
import (
"furtuna-be/internal/constants/order"
"furtuna-be/internal/constants/transaction"
"furtuna-be/internal/entity"
"time"
)
type Order struct {
BranchID int64 `json:"branch_id" validate:"required"`
Amount float64 `json:"amount" validate:"required"`
CustomerName string `json:"customer_name" validate:"required"`
CustomerPhone string `json:"customer_phone" validate:"required"`
Pax int `json:"pax" validate:"required"`
PaymentMethod transaction.PaymentMethod `json:"payment_method" validate:"required"`
OrderItem []OrderItem `json:"order_items" validate:"required"`
}
type OrderItem struct {
ItemID int64 `json:"item_id" validate:"required"`
ItemType order.ItemType `json:"item_type" validate:"required"`
Price float64 `json:"price" validate:"required"`
Qty int64 `json:"qty" validate:"required"`
}
type OrderParam struct {
Search string `form:"search" json:"search" example:"name,branch_name,item_name"`
StatusActive order.OrderSearchStatus `form:"status_active" json:"status_active" example:"active,inactive"`
Status order.OrderStatus `form:"status" json:"status" example:"NEW,PAID,CANCEL"`
BranchID int64 `form:"branch_id" json:"branch_id" example:"1"`
Limit int `form:"limit" json:"limit" example:"10"`
Offset int `form:"offset" json:"offset" example:"0"`
}
func (p *OrderParam) ToEntity() entity.OrderSearch {
return entity.OrderSearch{
Search: p.Search,
StatusActive: p.StatusActive,
Status: p.Status,
BranchID: p.BranchID,
Limit: p.Limit,
Offset: p.Offset,
}
}
func (o *Order) ToEntity() *entity.Order {
var ordItems []entity.OrderItem
if len(o.OrderItem) > 0 {
for _, i := range o.OrderItem {
ordItems = append(ordItems, entity.OrderItem{
ItemID: i.ItemID,
ItemType: i.ItemType,
Price: i.Price,
Qty: i.Qty,
})
}
}
transaction := entity.Transaction{
BranchID: o.BranchID,
CustomerName: o.CustomerName,
CustomerPhone: o.CustomerPhone,
PaymentMethod: o.PaymentMethod,
}
return &entity.Order{
BranchID: o.BranchID,
Amount: o.Amount,
CustomerName: o.CustomerName,
CustomerPhone: o.CustomerPhone,
Pax: o.Pax,
Transaction: transaction,
OrderItem: ordItems,
}
}
type OrderTotalRevenueParam struct {
Year int `form:"year" json:"year" example:"1,2,3"`
Month int `form:"month" json:"month" example:"1,2,3"`
BranchID int64 `form:"branch_id" json:"branch_id" example:"1"`
DateStart *time.Time `form:"date_start" json:"date_start" example:"2024-01-01" time_format:"2006-1-2"`
DateEnd *time.Time `form:"date_end" json:"date_end" example:"2024-01-01" time_format:"2006-1-2"`
}
func (p *OrderTotalRevenueParam) ToEntity() entity.OrderTotalRevenueSearch {
return entity.OrderTotalRevenueSearch{
Year: p.Year,
Month: p.Month,
BranchID: p.BranchID,
DateStart: p.DateStart,
DateEnd: p.DateEnd,
}
}
type OrderBranchRevenueParam struct {
DateStart *time.Time `form:"date_start" json:"date_start" example:"2024-01-01" time_format:"2006-1-2"`
DateEnd *time.Time `form:"date_end" json:"date_end" example:"2024-01-01" time_format:"2006-1-2"`
}
func (p *OrderBranchRevenueParam) ToEntity() entity.OrderBranchRevenueSearch {
return entity.OrderBranchRevenueSearch{
DateStart: p.DateStart,
DateEnd: p.DateEnd,
}
}
type UpdateStatus struct {
Status order.OrderStatus `form:"status" json:"status" example:"NEW,PAID,CANCEL"`
}
func (o *UpdateStatus) ToEntity() *entity.Order {
return &entity.Order{
Status: o.Status,
}
}
+35
View File
@@ -0,0 +1,35 @@
package request
import (
"furtuna-be/internal/entity"
)
type PartnerParam struct {
Search string `form:"search" json:"search" example:"Ketua Umum"`
Name string `form:"name" json:"name" example:"Ketua Umum"`
Limit int `form:"limit" json:"limit" example:"10"`
Offset int `form:"offset" json:"offset" example:"0"`
}
func (p *PartnerParam) ToEntity() entity.PartnerSearch {
return entity.PartnerSearch{
Search: p.Search,
Name: p.Name,
Limit: p.Limit,
Offset: p.Offset,
}
}
type Partner struct {
Name string `json:"name" validate:"required"`
Address string `json:"address" validate:"required"`
Status string `json:"status"`
}
func (e *Partner) ToEntity() *entity.Partner {
return &entity.Partner{
Name: e.Name,
Address: e.Address,
Status: e.Status,
}
}
+52
View File
@@ -0,0 +1,52 @@
package request
import (
"furtuna-be/internal/constants/product"
"furtuna-be/internal/entity"
)
type ProductParam struct {
Search string `form:"search" json:"search" example:"Nasi Goreng"`
Name string `form:"name" json:"name" example:"Nasi Goreng"`
Type product.ProductType `form:"type" json:"type" example:"FOOD/BEVERAGE"`
BranchID int64 `form:"branch_id" json:"branch_id" example:"1"`
Available product.ProductStock `form:"available" json:"available" example:"1" example:"AVAILABLE/UNAVAILABLE"`
Limit int `form:"limit" json:"limit" example:"10"`
Offset int `form:"offset" json:"offset" example:"0"`
}
func (p *ProductParam) ToEntity() entity.ProductSearch {
return entity.ProductSearch{
Search: p.Search,
Name: p.Name,
Type: p.Type,
BranchID: p.BranchID,
Available: p.Available,
Limit: p.Limit,
Offset: p.Offset,
}
}
type Product struct {
Name string `json:"name" validate:"required"`
Type product.ProductType `json:"type" validate:"required"`
Price float64 `json:"price" validate:"required"`
Status product.ProductStatus `json:"status" validate:"required"`
Description string `json:"description" `
Image string `json:"image" `
BranchID int64 `json:"branch_id" validate:"required"`
StockQty int64 `json:"stock_qty" `
}
func (e *Product) ToEntity() *entity.Product {
return &entity.Product{
Name: e.Name,
Type: e.Type,
Price: e.Price,
Status: e.Status,
Description: e.Description,
Image: e.Image,
BranchID: e.BranchID,
StockQty: e.StockQty,
}
}
+53
View File
@@ -0,0 +1,53 @@
package request
import (
"encoding/json"
"furtuna-be/internal/constants/studio"
"furtuna-be/internal/entity"
)
type StudioParam struct {
Id string `form:"id" json:"id" example:"1"`
Name string `form:"name" json:"name" example:"Studio A"`
Status studio.StudioStatus `form:"status" json:"status" example:"Active"`
BranchId int64 `form:"branch_id" json:"branch_id" example:"1"`
Limit int `form:"limit" json:"limit" example:"10"`
Offset int `form:"offset" json:"offset" example:"0"`
}
func (p *StudioParam) ToEntity() entity.StudioSearch {
return entity.StudioSearch{
Name: p.Name,
Status: p.Status,
BranchId: p.BranchId,
Limit: p.Limit,
Offset: p.Offset,
}
}
type Studio struct {
Name string `json:"name" validate:"required"`
BranchId int64 `json:"branch_id" validate:"required"`
Status studio.StudioStatus `json:"status"`
Price float64 `json:"price" validate:"required"`
Metadata map[string]interface{} `json:"metadata"`
}
func (e *Studio) ToEntity() *entity.Studio {
studioEntity := &entity.Studio{
BranchId: e.BranchId,
Name: e.Name,
Status: e.Status,
Price: e.Price,
}
if e.Metadata != nil {
jsonData, err := json.Marshal(e.Metadata)
if err != nil {
//TODO @taufanvps
}
studioEntity.Metadata = jsonData
}
return studioEntity
}
+9
View File
@@ -0,0 +1,9 @@
package request
import (
"furtuna-be/internal/constants/transaction"
)
type Transaction struct {
PaymentMethod transaction.PaymentMethod
}
+58
View File
@@ -0,0 +1,58 @@
package request
import (
"furtuna-be/internal/constants/role"
"furtuna-be/internal/entity"
"github.com/go-playground/validator/v10"
)
type User struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required"`
Password string `json:"password" validate:"required"`
PartnerID *int64 `json:"partner_id"`
RoleID int64 `json:"role_id" validate:"required"`
NIK string `json:"nik"`
UserType string `json:"user_type"`
PhoneNumber string `json:"phone_number"`
}
func (e *User) Validate() error {
validate := validator.New()
if err := validate.Struct(e); err != nil {
return err
}
return nil
}
func (u *User) ToEntity() *entity.User {
return &entity.User{
Name: u.Name,
Email: u.Email,
Password: u.Password,
RoleID: role.Role(u.RoleID),
PartnerID: u.PartnerID,
}
}
type UserParam struct {
Search string `form:"search" json:"search" example:"admin,branch1"`
Name string `form:"name" json:"name" example:"Admin 1"`
RoleID int64 `form:"role_id" json:"role_id" example:"1"`
PartnerID int64 `form:"partner_id" json:"partner_id" example:"1"`
Limit int `form:"limit,default=10" json:"limit" example:"10"`
Offset int `form:"offset,default=0" json:"offset" example:"0"`
}
func (p *UserParam) ToEntity() entity.UserSearch {
return entity.UserSearch{
Search: p.Search,
Name: p.Name,
RoleID: p.RoleID,
PartnerID: p.PartnerID,
Limit: p.Limit,
Offset: p.Offset,
}
}
+13
View File
@@ -0,0 +1,13 @@
package response
type LoginResponse struct {
Token string `json:"token"`
Name string `json:"name"`
Role Role `json:"role"`
Branch *Branch `json:"branch"`
}
type Role struct {
ID int64 `json:"id"`
Role string `json:"role_name"`
}
@@ -0,0 +1,12 @@
package response
type BaseResponse struct {
Success bool `json:"success"`
Code string `json:"response_code,omitempty"`
Status int `json:"-"`
Message string `json:"message,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
ErrorDetail interface{} `json:"error_detail,omitempty"`
Data interface{} `json:"data,omitempty"`
PagingMeta *PagingMeta `json:"meta,omitempty"`
}
+17
View File
@@ -0,0 +1,17 @@
package response
type Branch struct {
ID *int64 `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Location string `json:"location"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type BranchList struct {
Branches []Branch `json:"branches"`
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
+27
View File
@@ -0,0 +1,27 @@
package response
type Event struct {
ID int64 `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Description string `json:"description"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time"`
Location string `json:"location"`
Level string `json:"level"`
Included []string `json:"included"`
Price float64 `json:"price"`
Paid bool `json:"paid"`
LocationID *int64 `json:"location_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type EventList struct {
Events []Event `json:"events"`
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
+38
View File
@@ -0,0 +1,38 @@
package response
import (
"github.com/gin-gonic/gin"
"furtuna-be/internal/common/errors"
)
type response struct {
Status int `json:"status"`
Meta interface{} `json:"meta,omitempty"`
Message string `json:"message"`
Data interface{} `json:"data"`
Success bool `json:"success,omitempty"`
}
func ErrorWrapper(c *gin.Context, err error) {
var customError errors.Error
customError = errors.ErrorInternalServer
status := customError.MapErrorsToHTTPCode()
code := customError.MapErrorsToCode()
message := err.Error()
if validErr, ok := err.(errors.Error); ok {
status = validErr.MapErrorsToHTTPCode()
code = validErr.MapErrorsToCode()
message = code.GetMessage()
}
resp := BaseResponse{
ErrorMessage: err.Error(),
Code: code.GetCode(),
Message: message,
}
c.JSON(status, resp)
}
+52
View File
@@ -0,0 +1,52 @@
package response
import (
"furtuna-be/internal/constants/order"
"furtuna-be/internal/constants/transaction"
)
type Order struct {
ID int64 `json:"id" `
BranchID int64 `json:"branch_id" `
BranchName string `json:"branch_name" `
Amount float64 `json:"amount" `
Status order.OrderStatus `json:"status" `
CustomerName string `json:"customer_name" `
CustomerPhone string `json:"customer_phone" `
Pax int `json:"pax" `
PaymentMethod transaction.PaymentMethod `json:"payment_method" `
OrderItem []OrderItem `json:"order_items" `
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type OrderItem struct {
OrderItemID int64 `json:"order_item_id" `
ItemID int64 `json:"item_id" `
ItemType order.ItemType `json:"item_type" `
ItemName string `json:"item_name" `
Price float64 `json:"price" `
Qty int64 `json:"qty" `
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type OrderList struct {
Orders []Order `json:"orders"`
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type OrderMonthlyRevenue struct {
TotalRevenue float64 `json:"total_revenue"`
TotalTransaction int64 `json:"total_transaction"`
}
type OrderBranchRevenue struct {
BranchID string `json:"branch_id"`
BranchName string `json:"name"`
BranchLocation string `json:"location"`
TotalTransaction int `json:"total_trans"`
TotalAmount float64 `json:"total_amount"`
}
+7
View File
@@ -0,0 +1,7 @@
package response
type PagingMeta struct {
Page int `json:"page"`
Limit int `json:"limit"`
Total int64 `json:"total_data"`
}
+17
View File
@@ -0,0 +1,17 @@
package response
type Partner struct {
ID *int64 `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Address string `json:"address"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type PartnerList struct {
Partners []Partner `json:"partners"`
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
+24
View File
@@ -0,0 +1,24 @@
package response
import "furtuna-be/internal/constants/product"
type Product struct {
ID int64 `json:"id"`
Name string `json:"name"`
Type product.ProductType `json:"type"`
Price float64 `json:"price"`
Status product.ProductStatus `json:"status"`
Description string `json:"description" `
Image string `json:"image" `
BranchID int64 `json:"branch_id"`
StockQty int64 `json:"stock_qty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type ProductList struct {
Products []Product `json:"products"`
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
+19
View File
@@ -0,0 +1,19 @@
package response
type Studio struct {
ID *int64 `json:"id"`
BranchId *int64 `json:"branch_id"`
Name string `json:"name"`
Status string `json:"status"`
Price float64 `json:"price"`
CreatedAt string `json:"created_at"`
Metadata map[string]interface{} `json:"metadata"`
UpdatedAt string `json:"updated_at"`
}
type StudioList struct {
Studios []Studio `json:"studios"`
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
+21
View File
@@ -0,0 +1,21 @@
package response
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Status string `json:"status"`
RoleID int64 `json:"role_id"`
RoleName string `json:"role_name"`
PartnerID *int64 `json:"partner_id"`
BranchName string `json:"partner_name"`
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
}
type UserList struct {
Users []User `json:"users"`
Total int64 `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}