mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-25 15:55:44 +00:00
Feat[BE-222,223,224]: creating So create delete patch update get getall approval API
This commit is contained in:
+165
@@ -0,0 +1,165 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type DeliveryOrdersController struct {
|
||||
DeliveryOrdersService service.DeliveryOrdersService
|
||||
}
|
||||
|
||||
func NewDeliveryOrdersController(deliveryOrdersService service.DeliveryOrdersService) *DeliveryOrdersController {
|
||||
return &DeliveryOrdersController{
|
||||
DeliveryOrdersService: deliveryOrdersService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *DeliveryOrdersController) GetAll(c *fiber.Ctx) error {
|
||||
query := &validation.Query{
|
||||
Page: c.QueryInt("page", 1),
|
||||
Limit: c.QueryInt("limit", 10),
|
||||
MarketingId: uint(c.QueryInt("marketing_id", 0)),
|
||||
}
|
||||
|
||||
if query.Page < 1 || query.Limit < 1 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "page and limit must be greater than 0")
|
||||
}
|
||||
|
||||
result, totalResults, err := u.DeliveryOrdersService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.DeliveryOrdersListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all deliveryOrderss successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: result,
|
||||
})
|
||||
}
|
||||
|
||||
func (u *DeliveryOrdersController) GetOne(c *fiber.Ctx) error {
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
result, err := u.DeliveryOrdersService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get deliveryOrders successfully",
|
||||
Data: *result,
|
||||
})
|
||||
}
|
||||
|
||||
func (u *DeliveryOrdersController) CreateOne(c *fiber.Ctx) error {
|
||||
req := new(validation.Create)
|
||||
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
|
||||
}
|
||||
|
||||
result, err := u.DeliveryOrdersService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create delivery products successfully",
|
||||
Data: result,
|
||||
})
|
||||
}
|
||||
|
||||
func (u *DeliveryOrdersController) UpdateOne(c *fiber.Ctx) error {
|
||||
req := new(validation.Update)
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
|
||||
}
|
||||
|
||||
result, err := u.DeliveryOrdersService.UpdateOne(c, req, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Update deliveryOrders successfully",
|
||||
Data: dto.ToDeliveryOrdersListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *DeliveryOrdersController) DeleteOne(c *fiber.Ctx) error {
|
||||
param := c.Params("id")
|
||||
|
||||
id, err := strconv.Atoi(param)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
|
||||
}
|
||||
|
||||
if err := u.DeliveryOrdersService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete deliveryOrders successfully",
|
||||
})
|
||||
}
|
||||
|
||||
func (u *DeliveryOrdersController) Approval(c *fiber.Ctx) error {
|
||||
req := new(validation.Approve)
|
||||
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid request body")
|
||||
}
|
||||
|
||||
results, err := u.DeliveryOrdersService.Approval(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Submit delivery order approval successfully",
|
||||
Data: results,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
approvalDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/approvals/dto"
|
||||
userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
|
||||
)
|
||||
|
||||
// === DTO Structs ===
|
||||
|
||||
type MarketingDeliveryProductDTO struct {
|
||||
Id uint `json:"id"`
|
||||
MarketingProductId uint `json:"marketing_product_id"`
|
||||
Qty float64 `json:"qty"`
|
||||
UnitPrice float64 `json:"unit_price"`
|
||||
TotalWeight float64 `json:"total_weight"`
|
||||
AvgWeight float64 `json:"avg_weight"`
|
||||
TotalPrice float64 `json:"total_price"`
|
||||
DeliveryDate *time.Time `json:"delivery_date"`
|
||||
VehicleNumber string `json:"vehicle_number"`
|
||||
}
|
||||
|
||||
type DeliveryOrdersBaseDTO struct {
|
||||
Id uint `json:"id,omitempty"`
|
||||
DeliveryNumber *string `json:"delivery_number,omitempty"`
|
||||
DeliveryDate *time.Time `json:"delivery_date,omitempty"`
|
||||
MarketingId uint `json:"marketing_id"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
type MarketingBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
SoNumber string `json:"so_number"`
|
||||
SoDate time.Time `json:"so_date"`
|
||||
}
|
||||
|
||||
type DeliveryOrdersListDTO struct {
|
||||
DeliveryOrdersBaseDTO
|
||||
Marketing *MarketingBaseDTO `json:"marketing,omitempty"`
|
||||
DeliveryProducts []MarketingDeliveryProductDTO `json:"delivery_products,omitempty"`
|
||||
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Approval *approvalDTO.ApprovalBaseDTO `json:"approval,omitempty"`
|
||||
}
|
||||
|
||||
type DeliveryOrdersDetailDTO struct {
|
||||
DeliveryOrdersListDTO
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToMarketingDeliveryProductDTO(e entity.MarketingDeliveryProduct) MarketingDeliveryProductDTO {
|
||||
return MarketingDeliveryProductDTO{
|
||||
Id: e.Id,
|
||||
MarketingProductId: e.MarketingProductId,
|
||||
Qty: e.Qty,
|
||||
UnitPrice: e.UnitPrice,
|
||||
TotalWeight: e.TotalWeight,
|
||||
AvgWeight: e.AvgWeight,
|
||||
TotalPrice: e.TotalPrice,
|
||||
DeliveryDate: e.DeliveryDate,
|
||||
VehicleNumber: e.VehicleNumber,
|
||||
}
|
||||
}
|
||||
|
||||
func ToDeliveryOrdersBaseDTO(e entity.DeliveryOrders) DeliveryOrdersBaseDTO {
|
||||
var deliveryNumber *string
|
||||
if e.DeliveryNumber != "" {
|
||||
deliveryNumber = &e.DeliveryNumber
|
||||
}
|
||||
|
||||
return DeliveryOrdersBaseDTO{
|
||||
Id: e.Id,
|
||||
DeliveryNumber: deliveryNumber,
|
||||
DeliveryDate: &e.DeliveryDate,
|
||||
MarketingId: e.MarketingId,
|
||||
Notes: e.Notes,
|
||||
}
|
||||
}
|
||||
|
||||
func ToDeliveryOrdersListDTO(e entity.DeliveryOrders) DeliveryOrdersListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser != nil && e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(*e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
var marketing *MarketingBaseDTO
|
||||
if e.Marketing != nil && e.Marketing.Id != 0 {
|
||||
marketing = &MarketingBaseDTO{
|
||||
Id: e.Marketing.Id,
|
||||
SoNumber: e.Marketing.SoNumber,
|
||||
SoDate: e.Marketing.SoDate,
|
||||
}
|
||||
}
|
||||
|
||||
var deliveryProductsDTOs []MarketingDeliveryProductDTO
|
||||
if len(e.DeliveryProducts) > 0 {
|
||||
deliveryProductsDTOs = make([]MarketingDeliveryProductDTO, len(e.DeliveryProducts))
|
||||
for i, dp := range e.DeliveryProducts {
|
||||
deliveryProductsDTOs[i] = ToMarketingDeliveryProductDTO(dp)
|
||||
}
|
||||
}
|
||||
|
||||
return DeliveryOrdersListDTO{
|
||||
DeliveryOrdersBaseDTO: ToDeliveryOrdersBaseDTO(e),
|
||||
Marketing: marketing,
|
||||
DeliveryProducts: deliveryProductsDTOs,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
}
|
||||
}
|
||||
|
||||
func ToDeliveryOrdersListDTOWithProducts(e entity.DeliveryOrders, deliveryProducts []entity.MarketingDeliveryProduct) DeliveryOrdersListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser != nil && e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(*e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
var marketing *MarketingBaseDTO
|
||||
if e.Marketing != nil && e.Marketing.Id != 0 {
|
||||
marketing = &MarketingBaseDTO{
|
||||
Id: e.Marketing.Id,
|
||||
SoNumber: e.Marketing.SoNumber,
|
||||
SoDate: e.Marketing.SoDate,
|
||||
}
|
||||
}
|
||||
|
||||
var deliveryProductsDTOs []MarketingDeliveryProductDTO
|
||||
if len(deliveryProducts) > 0 {
|
||||
deliveryProductsDTOs = make([]MarketingDeliveryProductDTO, len(deliveryProducts))
|
||||
for i, dp := range deliveryProducts {
|
||||
deliveryProductsDTOs[i] = ToMarketingDeliveryProductDTO(dp)
|
||||
}
|
||||
}
|
||||
|
||||
return DeliveryOrdersListDTO{
|
||||
DeliveryOrdersBaseDTO: ToDeliveryOrdersBaseDTO(e),
|
||||
Marketing: marketing,
|
||||
DeliveryProducts: deliveryProductsDTOs,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
}
|
||||
}
|
||||
|
||||
func ToDeliveryOrdersListDTOs(e []entity.DeliveryOrders) []DeliveryOrdersListDTO {
|
||||
result := make([]DeliveryOrdersListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToDeliveryOrdersListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToDeliveryOrdersDetailDTO(e entity.DeliveryOrders) DeliveryOrdersDetailDTO {
|
||||
return DeliveryOrdersDetailDTO{
|
||||
DeliveryOrdersListDTO: ToDeliveryOrdersListDTO(e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package delivery_orderss
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
rMarketingDeliveryProduct "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/marketing-delivery-products/repositories"
|
||||
rDeliveryOrders "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/repositories"
|
||||
sDeliveryOrders "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/services"
|
||||
rMarketing "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/sales-orders/repositories"
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type DeliveryOrdersModule struct{}
|
||||
|
||||
func (DeliveryOrdersModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
deliveryOrdersRepo := rDeliveryOrders.NewDeliveryOrdersRepository(db)
|
||||
marketingRepo := rMarketing.NewMarketingRepository(db)
|
||||
marketingDeliveryProductRepo := rMarketingDeliveryProduct.NewMarketingDeliveryProductRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
approvalRepo := commonRepo.NewApprovalRepository(db)
|
||||
approvalSvc := commonSvc.NewApprovalService(approvalRepo)
|
||||
|
||||
deliveryOrdersService := sDeliveryOrders.NewDeliveryOrdersService(deliveryOrdersRepo, marketingRepo, marketingDeliveryProductRepo, approvalSvc, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
DeliveryOrdersRoutes(router, userService, deliveryOrdersService)
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DeliveryOrdersRepository interface {
|
||||
repository.BaseRepository[entity.DeliveryOrders]
|
||||
}
|
||||
|
||||
type DeliveryOrdersRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.DeliveryOrders]
|
||||
}
|
||||
|
||||
func NewDeliveryOrdersRepository(db *gorm.DB) DeliveryOrdersRepository {
|
||||
return &DeliveryOrdersRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.DeliveryOrders](db),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package delivery_orderss
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/controllers"
|
||||
deliveryOrders "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func DeliveryOrdersRoutes(v1 fiber.Router, u user.UserService, s deliveryOrders.DeliveryOrdersService) {
|
||||
ctrl := controller.NewDeliveryOrdersController(s)
|
||||
|
||||
route := v1.Group("/delivery-orders")
|
||||
|
||||
// route.Get("/", m.Auth(u), ctrl.GetAll)
|
||||
// route.Post("/", m.Auth(u), ctrl.CreateOne)
|
||||
// route.Get("/:id", m.Auth(u), ctrl.GetOne)
|
||||
// route.Patch("/:id", m.Auth(u), ctrl.UpdateOne)
|
||||
// route.Delete("/:id", m.Auth(u), ctrl.DeleteOne)
|
||||
|
||||
route.Get("/", ctrl.GetAll)
|
||||
route.Post("/", ctrl.CreateOne)
|
||||
route.Get("/:id", ctrl.GetOne)
|
||||
route.Patch("/:id", ctrl.UpdateOne)
|
||||
route.Delete("/:id", ctrl.DeleteOne)
|
||||
route.Post("/approvals", ctrl.Approval)
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
marketingDeliveryProductRepo "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/marketing-delivery-products/repositories"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/dto"
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/delivery-orderss/validations"
|
||||
marketingRepo "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/sales-orders/repositories"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/utils"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DeliveryOrdersService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]dto.DeliveryOrdersListDTO, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*dto.DeliveryOrdersListDTO, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*dto.DeliveryOrdersListDTO, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.DeliveryOrders, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
Approval(ctx *fiber.Ctx, req *validation.Approve) ([]entity.DeliveryOrders, error)
|
||||
}
|
||||
|
||||
type deliveryOrdersService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.DeliveryOrdersRepository
|
||||
MarketingRepo marketingRepo.MarketingRepository
|
||||
MarketingDeliveryProductRepo marketingDeliveryProductRepo.MarketingDeliveryProductRepository
|
||||
ApprovalSvc commonSvc.ApprovalService
|
||||
}
|
||||
|
||||
func NewDeliveryOrdersService(
|
||||
repo repository.DeliveryOrdersRepository,
|
||||
marketingRepo marketingRepo.MarketingRepository,
|
||||
marketingDeliveryProductRepo marketingDeliveryProductRepo.MarketingDeliveryProductRepository,
|
||||
approvalSvc commonSvc.ApprovalService,
|
||||
validate *validator.Validate,
|
||||
) DeliveryOrdersService {
|
||||
return &deliveryOrdersService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
MarketingRepo: marketingRepo,
|
||||
MarketingDeliveryProductRepo: marketingDeliveryProductRepo,
|
||||
ApprovalSvc: approvalSvc,
|
||||
}
|
||||
}
|
||||
|
||||
func (s deliveryOrdersService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("CreatedUser").
|
||||
Preload("Marketing")
|
||||
}
|
||||
|
||||
func (s deliveryOrdersService) GetAll(c *fiber.Ctx, params *validation.Query) ([]dto.DeliveryOrdersListDTO, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
// Fetch dari Marketing, bukan DeliveryOrders
|
||||
marketings, total, err := s.MarketingRepo.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
|
||||
db = db.Preload("CreatedUser").
|
||||
Preload("Customer").
|
||||
Preload("SalesPerson").
|
||||
Preload("Products.ProductWarehouse")
|
||||
if params.MarketingId != 0 {
|
||||
return db.Where("id = ?", params.MarketingId)
|
||||
}
|
||||
return db.Order("created_at DESC").Order("updated_at DESC")
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get marketings: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Load delivery products untuk setiap marketing
|
||||
result := make([]dto.DeliveryOrdersListDTO, len(marketings))
|
||||
for i, marketing := range marketings {
|
||||
// Get marketing delivery products
|
||||
var deliveryProducts []entity.MarketingDeliveryProduct
|
||||
if err := s.Repository.DB().WithContext(c.Context()).
|
||||
Preload("MarketingProduct").
|
||||
Where("marketing_product_id IN (?)",
|
||||
s.Repository.DB().WithContext(c.Context()).
|
||||
Model(&entity.MarketingProduct{}).
|
||||
Select("id").
|
||||
Where("marketing_id = ?", marketing.Id)).
|
||||
Find(&deliveryProducts).Error; err != nil {
|
||||
s.Log.Errorf("Failed to load delivery products for marketing %d: %+v", marketing.Id, err)
|
||||
// Continue without products
|
||||
}
|
||||
|
||||
// Create dummy DeliveryOrders untuk dto mapping
|
||||
dummyDO := &entity.DeliveryOrders{
|
||||
MarketingId: marketing.Id,
|
||||
CreatedUser: &marketing.CreatedUser,
|
||||
Marketing: &marketing,
|
||||
DeliveryProducts: deliveryProducts,
|
||||
}
|
||||
|
||||
result[i] = dto.ToDeliveryOrdersListDTOWithProducts(*dummyDO, deliveryProducts)
|
||||
}
|
||||
|
||||
return result, total, nil
|
||||
}
|
||||
|
||||
func (s deliveryOrdersService) GetOne(c *fiber.Ctx, id uint) (*dto.DeliveryOrdersListDTO, error) {
|
||||
// Fetch Marketing by ID, bukan DeliveryOrders
|
||||
marketing, err := s.MarketingRepo.GetByID(c.Context(), id, func(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("CreatedUser").
|
||||
Preload("Customer").
|
||||
Preload("SalesPerson").
|
||||
Preload("Products.ProductWarehouse")
|
||||
})
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Marketing not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get marketing by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Get marketing delivery products
|
||||
var deliveryProducts []entity.MarketingDeliveryProduct
|
||||
if err := s.Repository.DB().WithContext(c.Context()).
|
||||
Preload("MarketingProduct").
|
||||
Where("marketing_product_id IN (?)",
|
||||
s.Repository.DB().WithContext(c.Context()).
|
||||
Model(&entity.MarketingProduct{}).
|
||||
Select("id").
|
||||
Where("marketing_id = ?", marketing.Id)).
|
||||
Find(&deliveryProducts).Error; err != nil {
|
||||
s.Log.Errorf("Failed to load delivery products for marketing %d: %+v", marketing.Id, err)
|
||||
// Continue without products
|
||||
}
|
||||
|
||||
// Create dummy DeliveryOrders untuk dto mapping
|
||||
dummyDO := &entity.DeliveryOrders{
|
||||
MarketingId: marketing.Id,
|
||||
CreatedUser: &marketing.CreatedUser,
|
||||
Marketing: marketing,
|
||||
DeliveryProducts: deliveryProducts,
|
||||
}
|
||||
|
||||
result := dto.ToDeliveryOrdersListDTOWithProducts(*dummyDO, deliveryProducts)
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (s *deliveryOrdersService) CreateOne(c *fiber.Ctx, req *validation.Create) (*dto.DeliveryOrdersListDTO, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Validate marketing exists
|
||||
_, err := s.MarketingRepo.GetByID(c.Context(), req.MarketingId, nil)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Marketing not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to fetch marketing %d: %+v", req.MarketingId, err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch marketing")
|
||||
}
|
||||
|
||||
// Validate marketing approval status - harus sudah di approve ke step Sales Order
|
||||
approvalSvc := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(s.MarketingRepo.DB()))
|
||||
latestApproval, err := approvalSvc.LatestByTarget(c.Context(), utils.ApprovalWorkflowMarketing, req.MarketingId, nil)
|
||||
if err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check approval status")
|
||||
}
|
||||
|
||||
if latestApproval == nil {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Marketing has not been submitted for approval")
|
||||
}
|
||||
|
||||
// Cek apakah status approval sudah Sales Order (step 2) atau lebih
|
||||
if latestApproval.StepNumber < uint16(utils.MarketingStepSalesOrder) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Marketing must be approved to Sales Order step before creating delivery order")
|
||||
}
|
||||
|
||||
if latestApproval.Action == nil || *latestApproval.Action != entity.ApprovalActionApproved {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Marketing is not approved for delivery")
|
||||
}
|
||||
|
||||
// Validate semua delivery products ada dan update mereka
|
||||
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTx *gorm.DB) error {
|
||||
for _, product := range req.DeliveryProducts {
|
||||
// Fetch marketing_product terlebih dahulu untuk pastikan punya marketing_id yang sama
|
||||
var marketingProduct entity.MarketingProduct
|
||||
if err := dbTx.Where("id = ? AND marketing_id = ?", product.MarketingProductId, req.MarketingId).
|
||||
First(&marketingProduct).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Marketing product %d not found for this marketing", product.MarketingProductId))
|
||||
}
|
||||
s.Log.Errorf("Failed to fetch marketing product: %+v", err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch marketing product")
|
||||
}
|
||||
|
||||
// Fetch marketing_delivery_product by marketing_product_id
|
||||
var mdp entity.MarketingDeliveryProduct
|
||||
if err := dbTx.Where("marketing_product_id = ?", marketingProduct.Id).
|
||||
First(&mdp).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Delivery product for marketing product %d not found", product.MarketingProductId))
|
||||
}
|
||||
s.Log.Errorf("Failed to fetch marketing delivery product: %+v", err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch delivery product")
|
||||
}
|
||||
|
||||
// Parse delivery date per item (jika ada), atau gunakan default
|
||||
itemDeliveryDate := time.Now()
|
||||
if product.DeliveryDate != "" {
|
||||
parsedItemDate, err := time.Parse("2006-01-02", product.DeliveryDate)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Invalid delivery date format for product %d", product.MarketingProductId))
|
||||
}
|
||||
itemDeliveryDate = parsedItemDate
|
||||
}
|
||||
|
||||
// Update dengan data dari request - PASTIKAN UPDATE LANGSUNG KE FIELD
|
||||
updates := map[string]interface{}{
|
||||
"qty": product.Qty,
|
||||
"unit_price": product.UnitPrice,
|
||||
"avg_weight": product.AvgWeight,
|
||||
"total_weight": product.TotalWeight,
|
||||
"total_price": product.TotalPrice,
|
||||
"delivery_date": &itemDeliveryDate,
|
||||
"vehicle_number": product.VehicleNumber,
|
||||
}
|
||||
|
||||
if err := dbTx.Model(&mdp).Updates(updates).Error; err != nil {
|
||||
s.Log.Errorf("Failed to update marketing delivery product: %+v", err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update delivery product")
|
||||
}
|
||||
|
||||
s.Log.Infof("Updated MDP %d: qty=%v, unitPrice=%v, totalPrice=%v", mdp.Id, product.Qty, product.UnitPrice, product.TotalPrice)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Fetch marketing dengan delivery products yang sudah di-update
|
||||
marketing, err := s.MarketingRepo.GetByID(c.Context(), req.MarketingId, func(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("CreatedUser").Preload("Products")
|
||||
})
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to fetch marketing after update: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch updated marketing")
|
||||
}
|
||||
|
||||
// Get marketing delivery products
|
||||
var deliveryProducts []entity.MarketingDeliveryProduct
|
||||
if err := s.Repository.DB().WithContext(c.Context()).
|
||||
Preload("MarketingProduct").
|
||||
Where("marketing_product_id IN (?)",
|
||||
s.Repository.DB().WithContext(c.Context()).
|
||||
Model(&entity.MarketingProduct{}).
|
||||
Select("id").
|
||||
Where("marketing_id = ?", req.MarketingId)).
|
||||
Find(&deliveryProducts).Error; err != nil {
|
||||
s.Log.Errorf("Failed to load delivery products: %+v", err)
|
||||
// Continue tanpa delivery products
|
||||
}
|
||||
|
||||
// Create dummy DeliveryOrders untuk dipakai dto mapping
|
||||
dummyDO := &entity.DeliveryOrders{
|
||||
MarketingId: req.MarketingId,
|
||||
Notes: req.Notes,
|
||||
CreatedUser: &marketing.CreatedUser,
|
||||
Marketing: marketing,
|
||||
DeliveryProducts: deliveryProducts,
|
||||
}
|
||||
|
||||
result := dto.ToDeliveryOrdersListDTOWithProducts(*dummyDO, deliveryProducts)
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (s deliveryOrdersService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.DeliveryOrders, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
if req.DeliveryDate != "" {
|
||||
deliveryDate, err := time.Parse("2006-01-02", req.DeliveryDate)
|
||||
if err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid delivery date format")
|
||||
}
|
||||
updateBody["delivery_date"] = deliveryDate
|
||||
}
|
||||
|
||||
if req.Notes != "" {
|
||||
updateBody["notes"] = req.Notes
|
||||
}
|
||||
|
||||
if len(updateBody) == 0 {
|
||||
return s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
}
|
||||
|
||||
if err := s.Repository.PatchOne(c.Context(), id, updateBody, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "DeliveryOrders not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update deliveryOrders: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
}
|
||||
|
||||
func (s deliveryOrdersService) Approval(c *fiber.Ctx, req *validation.Approve) ([]entity.DeliveryOrders, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var action entity.ApprovalAction
|
||||
switch req.Action {
|
||||
case "APPROVED":
|
||||
action = entity.ApprovalActionApproved
|
||||
case "REJECTED":
|
||||
action = entity.ApprovalActionRejected
|
||||
default:
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "action must be APPROVED or REJECTED")
|
||||
}
|
||||
|
||||
approvableIDs := utils.UniqueUintSlice(req.ApprovableIds)
|
||||
if len(approvableIDs) == 0 {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "approvable_ids must contain at least one id")
|
||||
}
|
||||
|
||||
// Validate semua delivery order ada
|
||||
for _, id := range approvableIDs {
|
||||
_, err := s.Repository.GetByID(c.Context(), id, nil)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Delivery order %d not found", id))
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get delivery order %d: %+v", id, err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to get delivery order %d", id))
|
||||
}
|
||||
}
|
||||
|
||||
err := s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTx *gorm.DB) error {
|
||||
approvalSvc := commonSvc.NewApprovalService(commonRepo.NewApprovalRepository(dbTx))
|
||||
|
||||
for _, approvableID := range approvableIDs {
|
||||
actorID := uint(1) // TODO: get from auth context
|
||||
if _, err := approvalSvc.CreateApproval(
|
||||
c.Context(),
|
||||
utils.ApprovalWorkflowMarketing,
|
||||
approvableID,
|
||||
utils.MarketingDeliveryOrder,
|
||||
&action,
|
||||
actorID,
|
||||
req.Notes,
|
||||
); err != nil {
|
||||
s.Log.Errorf("Failed to create approval for %d: %+v", approvableID, err)
|
||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to create approval")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if fiberErr, ok := err.(*fiber.Error); ok {
|
||||
return nil, fiberErr
|
||||
}
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to record approval")
|
||||
}
|
||||
|
||||
updated := make([]entity.DeliveryOrders, 0, len(approvableIDs))
|
||||
for _, id := range approvableIDs {
|
||||
deliveryOrder, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Delivery order %d not found", id))
|
||||
}
|
||||
s.Log.Errorf("Failed to get delivery order %d: %+v", id, err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("Failed to get delivery order %d", id))
|
||||
}
|
||||
updated = append(updated, *deliveryOrder)
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func (s deliveryOrdersService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
if err := s.Repository.DeleteOne(c.Context(), id); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "DeliveryOrders not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete deliveryOrders: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package validation
|
||||
|
||||
type DeliveryProduct struct {
|
||||
MarketingProductId uint `json:"marketing_product_id" validate:"required,gt=0"`
|
||||
Qty float64 `json:"qty" validate:"required,gt=0"`
|
||||
UnitPrice float64 `json:"unit_price" validate:"required,gt=0"`
|
||||
AvgWeight float64 `json:"avg_weight" validate:"required,gt=0"`
|
||||
TotalWeight float64 `json:"total_weight" validate:"required,gt=0"`
|
||||
TotalPrice float64 `json:"total_price" validate:"required,gt=0"`
|
||||
DeliveryDate string `json:"delivery_date" validate:"omitempty,datetime=2006-01-02"`
|
||||
VehicleNumber string `json:"vehicle_number" validate:"omitempty,max=50"`
|
||||
}
|
||||
|
||||
type Create struct {
|
||||
MarketingId uint `json:"marketing_id" validate:"required,gt=0"`
|
||||
DeliveryDate string `json:"delivery_date" validate:"omitempty,datetime=2006-01-02"`
|
||||
DeliveryProducts []DeliveryProduct `json:"delivery_products" validate:"required,min=1,dive"`
|
||||
Notes string `json:"notes" validate:"omitempty,max=500"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
DeliveryDate string `json:"delivery_date" validate:"omitempty,datetime=2006-01-02"`
|
||||
DeliveryProducts []DeliveryProduct `json:"delivery_products" validate:"omitempty,min=1,dive"`
|
||||
Notes string `json:"notes" validate:"omitempty,max=500"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
Page int `query:"page" validate:"omitempty,number,min=1,gt=0"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100,gt=0"`
|
||||
MarketingId uint `query:"marketing_id" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
type Approve struct {
|
||||
Action string `json:"action" validate:"required_strict"`
|
||||
ApprovableIds []uint `json:"approvable_ids" validate:"required_strict,min=1,dive,gt=0"`
|
||||
Notes *string `json:"notes,omitempty" validate:"omitempty,max=500"`
|
||||
}
|
||||
Reference in New Issue
Block a user