Feat(BE-36,37,38,39): master area, customer, kandang, location, warehouse

This commit is contained in:
Hafizh A. Y
2025-10-02 10:51:15 +07:00
parent dbc1f79a36
commit e8905be856
79 changed files with 3745 additions and 169 deletions
@@ -0,0 +1,140 @@
package controller
import (
"math"
"strconv"
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/dto"
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/services"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/validations"
"gitlab.com/mbugroup/lti-api.git/internal/response"
"github.com/gofiber/fiber/v2"
)
type CustomerController struct {
CustomerService service.CustomerService
}
func NewCustomerController(customerService service.CustomerService) *CustomerController {
return &CustomerController{
CustomerService: customerService,
}
}
func (u *CustomerController) GetAll(c *fiber.Ctx) error {
query := &validation.Query{
Page: c.QueryInt("page", 1),
Limit: c.QueryInt("limit", 10),
Search: c.Query("search", ""),
}
result, totalResults, err := u.CustomerService.GetAll(c, query)
if err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.SuccessWithPaginate[dto.CustomerListDTO]{
Code: fiber.StatusOK,
Status: "success",
Message: "Get all customers successfully",
Meta: response.Meta{
Page: query.Page,
Limit: query.Limit,
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
TotalResults: totalResults,
},
Data: dto.ToCustomerListDTOs(result),
})
}
func (u *CustomerController) 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.CustomerService.GetOne(c, uint(id))
if err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.Success{
Code: fiber.StatusOK,
Status: "success",
Message: "Get customer successfully",
Data: dto.ToCustomerListDTO(*result),
})
}
func (u *CustomerController) 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.CustomerService.CreateOne(c, req)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).
JSON(response.Success{
Code: fiber.StatusCreated,
Status: "success",
Message: "Create customer successfully",
Data: dto.ToCustomerListDTO(*result),
})
}
func (u *CustomerController) 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.CustomerService.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 customer successfully",
Data: dto.ToCustomerListDTO(*result),
})
}
func (u *CustomerController) 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.CustomerService.DeleteOne(c, uint(id)); err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.Common{
Code: fiber.StatusOK,
Status: "success",
Message: "Delete customer successfully",
})
}
@@ -0,0 +1,79 @@
package dto
import (
"time"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)
// === DTO Structs ===
type CustomerBaseDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
PicId uint `json:"pic_id"`
Type string `json:"type"`
Address string `json:"address"`
Phone string `json:"phone"`
Email string `json:"email"`
AccountNumber string `json:"account_number"`
Pic *userDTO.UserBaseDTO `json:"pic"`
}
type CustomerListDTO struct {
CustomerBaseDTO
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type CustomerDetailDTO struct {
CustomerListDTO
}
// === Mapper Functions ===
func ToCustomerBaseDTO(e entity.Customer) CustomerBaseDTO {
var pic *userDTO.UserBaseDTO
if e.Pic.Id != 0 {
mapped := userDTO.ToUserBaseDTO(e.Pic)
pic = &mapped
}
return CustomerBaseDTO{
Id: e.Id,
Name: e.Name,
PicId: e.PicId,
Type: e.Type,
Address: e.Address,
Phone: e.Phone,
Email: e.Email,
AccountNumber: e.AccountNumber,
Pic: pic,
}
}
func ToCustomerListDTO(e entity.Customer) CustomerListDTO {
var createdUser *userDTO.UserBaseDTO
if e.CreatedUser.Id != 0 {
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
createdUser = &mapped
}
return CustomerListDTO{
CustomerBaseDTO: ToCustomerBaseDTO(e),
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
CreatedUser: createdUser,
}
}
func ToCustomerListDTOs(e []entity.Customer) []CustomerListDTO {
result := make([]CustomerListDTO, len(e))
for i, r := range e {
result[i] = ToCustomerListDTO(r)
}
return result
}
@@ -0,0 +1,26 @@
package customers
import (
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
rCustomer "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/repositories"
sCustomer "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/services"
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
)
type CustomerModule struct{}
func (CustomerModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
customerRepo := rCustomer.NewCustomerRepository(db)
userRepo := rUser.NewUserRepository(db)
customerService := sCustomer.NewCustomerService(customerRepo, validate)
userService := sUser.NewUserService(userRepo, validate)
CustomerRoutes(router, userService, customerService)
}
@@ -0,0 +1,35 @@
package repository
import (
"context"
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
"gorm.io/gorm"
)
type CustomerRepository interface {
repository.BaseRepository[entity.Customer]
PicExists(ctx context.Context, areaId uint) (bool, error)
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
}
type CustomerRepositoryImpl struct {
*repository.BaseRepositoryImpl[entity.Customer]
db *gorm.DB
}
func NewCustomerRepository(db *gorm.DB) CustomerRepository {
return &CustomerRepositoryImpl{
BaseRepositoryImpl: repository.NewBaseRepository[entity.Customer](db),
db: db,
}
}
func (r *CustomerRepositoryImpl) PicExists(ctx context.Context, picId uint) (bool, error) {
return repository.Exists[entity.User](ctx, r.db, picId)
}
func (r *CustomerRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
return repository.ExistsByName[entity.Customer](ctx, r.db, name, excludeID)
}
@@ -0,0 +1,28 @@
package customers
import (
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/controllers"
customer "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/services"
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
"github.com/gofiber/fiber/v2"
)
func CustomerRoutes(v1 fiber.Router, u user.UserService, s customer.CustomerService) {
ctrl := controller.NewCustomerController(s)
route := v1.Group("/customers")
// 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)
}
@@ -0,0 +1,179 @@
package service
import (
"errors"
"fmt"
"strings"
common "gitlab.com/mbugroup/lti-api.git/internal/common/service"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/repositories"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/validations"
"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 CustomerService interface {
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Customer, int64, error)
GetOne(ctx *fiber.Ctx, id uint) (*entity.Customer, error)
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Customer, error)
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Customer, error)
DeleteOne(ctx *fiber.Ctx, id uint) error
}
type customerService struct {
Log *logrus.Logger
Validate *validator.Validate
Repository repository.CustomerRepository
}
func NewCustomerService(repo repository.CustomerRepository, validate *validator.Validate) CustomerService {
return &customerService{
Log: utils.Log,
Validate: validate,
Repository: repo,
}
}
func (s customerService) withRelations(db *gorm.DB) *gorm.DB {
return db.Preload("CreatedUser").Preload("Pic")
}
func (s customerService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Customer, int64, error) {
if err := s.Validate.Struct(params); err != nil {
return nil, 0, err
}
offset := (params.Page - 1) * params.Limit
customers, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
db = s.withRelations(db)
if params.Search != "" {
return db.Where("name LIKE ?", "%"+params.Search+"%")
}
return db.Order("created_at DESC").Order("updated_at DESC")
})
if err != nil {
s.Log.Errorf("Failed to get customers: %+v", err)
return nil, 0, err
}
return customers, total, nil
}
func (s customerService) GetOne(c *fiber.Ctx, id uint) (*entity.Customer, error) {
customer, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Customer not found")
}
if err != nil {
s.Log.Errorf("Failed get customer by id: %+v", err)
return nil, err
}
return customer, nil
}
func (s *customerService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Customer, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
if exists, err := s.Repository.NameExists(c.Context(), req.Name, nil); err != nil {
s.Log.Errorf("Failed to check customer name: %+v", err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check customer name")
} else if exists {
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Customer with name %s already exists", req.Name))
}
typ := strings.ToUpper(req.Type)
if !utils.IsValidCustomerSupplierType(typ) {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid customer type")
}
if err := common.EnsureRelations(c.Context(),
common.RelationCheck{Name: "Pic", ID: &req.PicId, Exists: s.Repository.PicExists},
); err != nil {
return nil, err
}
//TODO: created by dummy
createBody := &entity.Customer{
Name: req.Name,
PicId: req.PicId,
Type: typ,
Address: req.Address,
Phone: req.Phone,
Email: req.Email,
AccountNumber: req.AccountNumber,
CreatedBy: 1,
}
if err := s.Repository.CreateOne(c.Context(), createBody, nil); err != nil {
s.Log.Errorf("Failed to create customer: %+v", err)
return nil, err
}
return createBody, nil
}
func (s customerService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Customer, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
updateBody := make(map[string]any)
if req.Name != nil {
if exists, err := s.Repository.NameExists(c.Context(), *req.Name, &id); err != nil {
s.Log.Errorf("Failed to check customer name: %+v", err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check customer name")
} else if exists {
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Customer with name %s already exists", *req.Name))
}
updateBody["name"] = *req.Name
}
if req.PicId != nil {
if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Pic", ID: req.PicId, Exists: s.Repository.PicExists}); err != nil {
return nil, err
}
updateBody["pic_id"] = *req.PicId
}
if req.Type != nil {
typ := strings.ToUpper(*req.Type)
if !utils.IsValidCustomerSupplierType(typ) {
return nil, fiber.NewError(fiber.StatusBadRequest, "invalid customer type")
}
updateBody["type"] = typ
}
if len(updateBody) == 0 {
return s.GetOne(c, id)
}
if err := s.Repository.PatchOne(c.Context(), id, updateBody, nil); err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Customer not found")
}
s.Log.Errorf("Failed to update customer: %+v", err)
return nil, err
}
return s.GetOne(c, id)
}
func (s customerService) 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, "Customer not found")
}
s.Log.Errorf("Failed to delete customer: %+v", err)
return err
}
return nil
}
@@ -0,0 +1,27 @@
package validation
type Create struct {
Name string `json:"name" validate:"required_strict,min=3"`
PicId uint `json:"pic_id" validate:"required_strict,number,gt=0"`
Type string `json:"type" validate:"required_strict"`
Address string `json:"address" validate:"required_strict"`
Phone string `json:"phone" validate:"required_strict,max=20"`
Email string `json:"email" validate:"required_strict,email"`
AccountNumber string `json:"account_number" validate:"required_strict"`
}
type Update struct {
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
PicId *uint `json:"pic_id,omitempty" validate:"omitempty,number,gt=0"`
Type *string `json:"type,omitempty" validate:"omitempty"`
Address *string `json:"address,omitempty" validate:"omitempty"`
Phone *string `json:"phone,omitempty" validate:"omitempty"`
Email *string `json:"email,omitempty" validate:"omitempty"`
AccountNumber *string `json:"account_number,omitempty" validate:"omitempty"`
}
type Query struct {
Page int `query:"page" validate:"omitempty,number,min=1"`
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100"`
Search string `query:"search" validate:"omitempty,max=50"`
}