add order and payment

This commit is contained in:
aditya.siregar
2024-06-04 02:59:31 +07:00
parent 8a23e72230
commit 4ae9079ff9
34 changed files with 810 additions and 1172 deletions
+65 -323
View File
@@ -6,12 +6,9 @@ import (
"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"
"net/http"
)
type Handler struct {
@@ -21,13 +18,8 @@ type Handler struct {
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)
route.POST("/inquiry", jwt, h.Inquiry)
route.POST("/execute", jwt, h.Execute)
}
func NewHandler(service services.Order) *Handler {
@@ -36,19 +28,7 @@ func NewHandler(service services.Order) *Handler {
}
}
// 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) {
func (h *Handler) Inquiry(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.Order
@@ -57,14 +37,21 @@ func (h *Handler) Create(c *gin.Context) {
return
}
if !ctx.IsCasheer() {
response.ErrorWrapper(c, errors.ErrorBadRequest)
return
}
// override the partner_id
req.PartnerID = *ctx.GetPartnerID()
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
return
}
err := h.service.Create(ctx, req.ToEntity())
order, err := h.service.CreateOrder(ctx, req.ToEntity(ctx.RequestedBy()))
if err != nil {
response.ErrorWrapper(c, err)
return
@@ -73,122 +60,33 @@ func (h *Handler) Create(c *gin.Context) {
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: MapOrderToCreateOrderResponse(order),
})
}
// 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) {
func (h *Handler) Execute(c *gin.Context) {
ctx := request.GetMyContext(c)
var req request.UpdateStatus
var req request.Execute
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 {
if !ctx.IsCasheer() {
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,
})
req.PartnerID = *ctx.GetPartnerID()
validate := validator.New()
if err := validate.Struct(req); err != nil {
response.ErrorWrapper(c, err)
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())
order, err := h.service.Execute(ctx, req.ToOrderExecuteRequest(ctx.RequestedBy()))
if err != nil {
response.ErrorWrapper(c, err)
return
@@ -197,213 +95,57 @@ func (h *Handler) GetAll(c *gin.Context) {
c.JSON(http.StatusOK, response.BaseResponse{
Success: true,
Status: http.StatusOK,
Data: h.toOrderResponseList(orders, int64(total), req),
Data: MapOrderToExecuteOrderResponse(order),
})
}
// 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,
func MapOrderToCreateOrderResponse(orderResponse *entity.OrderResponse) response.CreateOrderResponse {
order := orderResponse.Order
orderItems := make([]response.CreateOrderItemResponse, len(order.OrderItems))
for i, item := range order.OrderItems {
orderItems[i] = response.CreateOrderItemResponse{
ID: item.ID,
ItemID: item.ItemID,
Quantity: item.Quantity,
Price: item.Price,
}
}
// Populate result map with actual data
for _, v := range data {
result[v.Month][v.ItemType] = v.Amount
return response.CreateOrderResponse{
ID: order.ID,
RefID: order.RefID,
PartnerID: order.PartnerID,
Status: order.Status,
Amount: order.Amount,
PaymentType: order.PaymentType,
CreatedAt: order.CreatedAt,
OrderItems: orderItems,
Token: orderResponse.Token,
}
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,
})
func MapOrderToExecuteOrderResponse(orderResponse *entity.ExecuteOrderResponse) response.ExecuteOrderResponse {
order := orderResponse.Order
orderItems := make([]response.CreateOrderItemResponse, len(order.OrderItems))
for i, item := range order.OrderItems {
orderItems[i] = response.CreateOrderItemResponse{
ID: item.ID,
ItemID: item.ItemID,
Quantity: item.Quantity,
Price: item.Price,
}
}
return resp
return response.ExecuteOrderResponse{
ID: order.ID,
RefID: order.RefID,
PartnerID: order.PartnerID,
Status: order.Status,
Amount: order.Amount,
PaymentType: order.PaymentType,
CreatedAt: order.CreatedAt,
OrderItems: orderItems,
PaymentToken: orderResponse.PaymentToken,
RedirectURL: orderResponse.RedirectURL,
}
}
+6 -6
View File
@@ -56,14 +56,14 @@ func (h *Handler) Create(c *gin.Context) {
return
}
req.PartnerID = ctx.GetPartnerID()
if err := req.Validate(); err != nil {
response.ErrorWrapper(c, errors.ErrorInvalidRequest)
return
if !ctx.IsSuperAdmin() {
req.PartnerID = ctx.GetPartnerID()
if err := req.Validate(); err != nil {
response.ErrorWrapper(c, errors.ErrorInvalidRequest)
return
}
}
ctx.IsSuperAdmin()
res, err := h.service.Create(ctx, req.ToEntity())
if err != nil {
response.ErrorWrapper(c, err)
+23 -92
View File
@@ -1,116 +1,47 @@
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"`
PartnerID int64 `json:"partner_id" validate:"required"`
PaymentMethod transaction.PaymentMethod `json:"payment_method" validate:"required"`
OrderItem []OrderItem `json:"order_items" validate:"required"`
OrderItems []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"`
ProductID int64 `json:"product_id" validate:"required"`
Quantity int64 `json:"quantity" 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,
})
func (o *Order) ToEntity(createdBy int64) *entity.OrderRequest {
orderItems := make([]entity.OrderItemRequest, len(o.OrderItems))
for i, item := range o.OrderItems {
orderItems[i] = entity.OrderItemRequest{
ProductID: item.ProductID,
Quantity: item.Quantity,
}
}
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,
return &entity.OrderRequest{
PartnerID: o.PartnerID,
PaymentMethod: string(o.PaymentMethod),
OrderItems: orderItems,
CreatedBy: createdBy,
}
}
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"`
type Execute struct {
PartnerID int64 `json:"partner_id" validate:"required"`
Token string `json:"token"`
}
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,
func (e Execute) ToOrderExecuteRequest(createdBy int64) *entity.OrderExecuteRequest {
return &entity.OrderExecuteRequest{
CreatedBy: createdBy,
PartnerID: e.PartnerID,
Token: e.Token,
}
}
+33
View File
@@ -3,6 +3,7 @@ package response
import (
"furtuna-be/internal/constants/order"
"furtuna-be/internal/constants/transaction"
"time"
)
type Order struct {
@@ -50,3 +51,35 @@ type OrderBranchRevenue struct {
TotalTransaction int `json:"total_trans"`
TotalAmount float64 `json:"total_amount"`
}
type CreateOrderResponse struct {
ID int64 `json:"id"`
RefID string `json:"ref_id"`
PartnerID int64 `json:"partner_id"`
Status string `json:"status"`
Amount float64 `json:"amount"`
PaymentType string `json:"payment_type"`
CreatedAt time.Time `json:"created_at"`
OrderItems []CreateOrderItemResponse `json:"order_items"`
Token string `json:"token"`
}
type ExecuteOrderResponse struct {
ID int64 `json:"id"`
RefID string `json:"ref_id"`
PartnerID int64 `json:"partner_id"`
Status string `json:"status"`
Amount float64 `json:"amount"`
PaymentType string `json:"payment_type"`
CreatedAt time.Time `json:"created_at"`
OrderItems []CreateOrderItemResponse `json:"order_items"`
PaymentToken string `json:"payment_token"`
RedirectURL string `json:"redirect_url"`
}
type CreateOrderItemResponse struct {
ID int64 `json:"id"`
ItemID int64 `json:"item_id"`
Quantity int64 `json:"quantity"`
Price float64 `json:"price"`
}