mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
Feat(BE-36,37,38,39): finish master data management api
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/constants/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type ConstantController struct {
|
||||
ConstantService service.ConstantService
|
||||
}
|
||||
|
||||
func NewConstantController(constantService service.ConstantService) *ConstantController {
|
||||
return &ConstantController{
|
||||
ConstantService: constantService,
|
||||
}
|
||||
}
|
||||
|
||||
func (ctrl *ConstantController) GetAll(c *fiber.Ctx) error {
|
||||
data, err := ctrl.ConstantService.GetAll(c)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(data)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package constants
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rConstant "gitlab.com/mbugroup/lti-api.git/internal/modules/constants/repositories"
|
||||
sConstant "gitlab.com/mbugroup/lti-api.git/internal/modules/constants/services"
|
||||
)
|
||||
|
||||
type ConstantModule struct{}
|
||||
|
||||
func (ConstantModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
constantRepo := rConstant.NewConstantRepository(db)
|
||||
|
||||
constantService := sConstant.NewConstantService(constantRepo, validate)
|
||||
|
||||
ConstantRoutes(router, constantService)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
utils "gitlab.com/mbugroup/lti-api.git/internal/utils"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ConstantRepository interface {
|
||||
GetConstants() map[string]interface{}
|
||||
}
|
||||
|
||||
type ConstantRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Constant]
|
||||
}
|
||||
|
||||
func NewConstantRepository(db *gorm.DB) ConstantRepository {
|
||||
return &ConstantRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Constant](db),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ConstantRepositoryImpl) GetConstants() map[string]interface{} {
|
||||
flagList := make([]string, 0)
|
||||
for f := range utils.AllFlagTypes() {
|
||||
flagList = append(flagList, string(f))
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
"flags": flagList,
|
||||
"warehouse_types": []string{
|
||||
"AREA",
|
||||
"LOKASI",
|
||||
"KANDANG",
|
||||
},
|
||||
"supplier_categories": []string{
|
||||
"BOP",
|
||||
"SAPRONAK",
|
||||
},
|
||||
"customer_supplier_types": []string{
|
||||
"BISNIS",
|
||||
"INDIVIDUAL",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package constants
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/constants/controllers"
|
||||
constant "gitlab.com/mbugroup/lti-api.git/internal/modules/constants/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func ConstantRoutes(v1 fiber.Router, s constant.ConstantService) {
|
||||
ctrl := controller.NewConstantController(s)
|
||||
|
||||
route := v1.Group("/constants")
|
||||
|
||||
route.Get("/", ctrl.GetAll)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/constants/repositories"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type ConstantService interface {
|
||||
GetAll(ctx *fiber.Ctx) (map[string]interface{}, error)
|
||||
}
|
||||
|
||||
type constantService struct {
|
||||
Repository repository.ConstantRepository
|
||||
}
|
||||
|
||||
func NewConstantService(repo repository.ConstantRepository, validate *validator.Validate) ConstantService {
|
||||
return &constantService{
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s constantService) GetAll(c *fiber.Ctx) (map[string]interface{}, error) {
|
||||
return s.Repository.GetConstants(), nil
|
||||
}
|
||||
@@ -56,3 +56,9 @@ func ToAreaListDTOs(e []entity.Area) []AreaListDTO {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToAreaDetailDTO(e entity.Area) AreaDetailDTO {
|
||||
return AreaDetailDTO{
|
||||
AreaListDTO: ToAreaListDTO(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ func (s *areaService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.A
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.Repository.GetByID(c.Context(), createBody.Id, s.withRelations)
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s areaService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Area, error) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type BankController struct {
|
||||
BankService service.BankService
|
||||
}
|
||||
|
||||
func NewBankController(bankService service.BankService) *BankController {
|
||||
return &BankController{
|
||||
BankService: bankService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *BankController) 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.BankService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.BankListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all banks successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToBankListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *BankController) 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.BankService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get bank successfully",
|
||||
Data: dto.ToBankListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *BankController) 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.BankService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create bank successfully",
|
||||
Data: dto.ToBankListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *BankController) 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.BankService.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 bank successfully",
|
||||
Data: dto.ToBankListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *BankController) 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.BankService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete bank successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
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 BankBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Alias string `json:"alias"`
|
||||
Owner *string `json:"owner"`
|
||||
AccountNumber string `json:"account_number"`
|
||||
}
|
||||
|
||||
type BankListDTO struct {
|
||||
BankBaseDTO
|
||||
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type BankDetailDTO struct {
|
||||
BankListDTO
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToBankBaseDTO(e entity.Bank) BankBaseDTO {
|
||||
return BankBaseDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
Alias: e.Alias,
|
||||
Owner: e.Owner,
|
||||
AccountNumber: e.AccountNumber,
|
||||
}
|
||||
}
|
||||
|
||||
func ToBankListDTO(e entity.Bank) BankListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
return BankListDTO{
|
||||
BankBaseDTO: ToBankBaseDTO(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
}
|
||||
}
|
||||
|
||||
func ToBankListDTOs(e []entity.Bank) []BankListDTO {
|
||||
result := make([]BankListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToBankListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToBankDetailDTO(e entity.Bank) BankDetailDTO {
|
||||
return BankDetailDTO{
|
||||
BankListDTO: ToBankListDTO(e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package banks
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rBank "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/repositories"
|
||||
sBank "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type BankModule struct{}
|
||||
|
||||
func (BankModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
bankRepo := rBank.NewBankRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
bankService := sBank.NewBankService(bankRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
BankRoutes(router, userService, bankService)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
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 BankRepository interface {
|
||||
repository.BaseRepository[entity.Bank]
|
||||
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
|
||||
}
|
||||
|
||||
type BankRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Bank]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewBankRepository(db *gorm.DB) BankRepository {
|
||||
return &BankRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Bank](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *BankRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
|
||||
return repository.ExistsByName[entity.Bank](ctx, r.db, name, excludeID)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package banks
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/controllers"
|
||||
bank "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func BankRoutes(v1 fiber.Router, u user.UserService, s bank.BankService) {
|
||||
ctrl := controller.NewBankController(s)
|
||||
|
||||
route := v1.Group("/banks")
|
||||
|
||||
// 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,156 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks/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 BankService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Bank, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.Bank, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Bank, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Bank, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type bankService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.BankRepository
|
||||
}
|
||||
|
||||
func NewBankService(repo repository.BankRepository, validate *validator.Validate) BankService {
|
||||
return &bankService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s bankService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("CreatedUser")
|
||||
}
|
||||
|
||||
func (s bankService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Bank, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
banks, 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 banks: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return banks, total, nil
|
||||
}
|
||||
|
||||
func (s bankService) GetOne(c *fiber.Ctx, id uint) (*entity.Bank, error) {
|
||||
bank, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Bank not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get bank by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return bank, nil
|
||||
}
|
||||
|
||||
func (s *bankService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Bank, 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 bank name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check bank name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Bank with name %s already exists", req.Name))
|
||||
}
|
||||
|
||||
createBody := &entity.Bank{
|
||||
Name: req.Name,
|
||||
Alias: req.Alias,
|
||||
Owner: req.Owner,
|
||||
AccountNumber: req.AccountNumber,
|
||||
CreatedBy: 1,
|
||||
}
|
||||
|
||||
if err := s.Repository.CreateOne(c.Context(), createBody, nil); err != nil {
|
||||
s.Log.Errorf("Failed to create bank: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s bankService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Bank, 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 bank name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check bank name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Bank with name %s already exists", *req.Name))
|
||||
}
|
||||
updateBody["name"] = *req.Name
|
||||
}
|
||||
if req.Alias != nil {
|
||||
updateBody["alias"] = *req.Alias
|
||||
}
|
||||
if req.Owner != nil {
|
||||
updateBody["owner"] = *req.Owner
|
||||
}
|
||||
if req.AccountNumber != nil {
|
||||
updateBody["account_number"] = *req.AccountNumber
|
||||
}
|
||||
|
||||
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, "Bank not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update bank: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s bankService) 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, "Bank not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete bank: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
Alias string `json:"alias" validate:"required_strict"`
|
||||
Owner *string `json:"owner,omitempty" validate:"omitempty"`
|
||||
AccountNumber string `json:"account_number" validate:"required_strict,max=50"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
Alias *string `json:"alias,omitempty" validate:"omitempty"`
|
||||
Owner *string `json:"owner,omitempty" validate:"omitempty"`
|
||||
AccountNumber *string `json:"account_number,omitempty" validate:"omitempty,max=50"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
@@ -10,14 +10,15 @@ import (
|
||||
// === 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"`
|
||||
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"`
|
||||
Balance float64 `json:"balance"`
|
||||
|
||||
Pic *userDTO.UserBaseDTO `json:"pic"`
|
||||
}
|
||||
@@ -77,3 +78,9 @@ func ToCustomerListDTOs(e []entity.Customer) []CustomerListDTO {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToCustomerDetailDTO(e entity.Customer) CustomerDetailDTO {
|
||||
return CustomerDetailDTO{
|
||||
CustomerListDTO: ToCustomerListDTO(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func (s *customerService) CreateOne(c *fiber.Ctx, req *validation.Create) (*enti
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return createBody, nil
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s customerService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Customer, error) {
|
||||
@@ -137,17 +137,18 @@ func (s customerService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint
|
||||
updateBody["name"] = *req.Name
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Pic", ID: req.PicId, Exists: s.Repository.PicExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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")
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid customer type")
|
||||
}
|
||||
updateBody["type"] = typ
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ type Create struct {
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
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"`
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type FcrController struct {
|
||||
FcrService service.FcrService
|
||||
}
|
||||
|
||||
func NewFcrController(fcrService service.FcrService) *FcrController {
|
||||
return &FcrController{
|
||||
FcrService: fcrService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *FcrController) 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.FcrService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.FcrListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all fcrs successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToFcrListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *FcrController) 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.FcrService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get fcr successfully",
|
||||
Data: dto.ToFcrDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *FcrController) 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.FcrService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create fcr successfully",
|
||||
Data: dto.ToFcrDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *FcrController) 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.FcrService.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 fcr successfully",
|
||||
Data: dto.ToFcrDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *FcrController) 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.FcrService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete fcr successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
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 FcrBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type FcrStandardDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Weight float64 `json:"weight"`
|
||||
FcrNumber float64 `json:"fcr_number"`
|
||||
Mortality float64 `json:"mortality"`
|
||||
}
|
||||
|
||||
type FcrListDTO struct {
|
||||
FcrBaseDTO
|
||||
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type FcrDetailDTO struct {
|
||||
FcrListDTO
|
||||
Standards []FcrStandardDTO `json:"fcr_standards"`
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToFcrBaseDTO(e entity.Fcr) FcrBaseDTO {
|
||||
return FcrBaseDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
}
|
||||
}
|
||||
|
||||
func ToFcrListDTO(e entity.Fcr) FcrListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
return FcrListDTO{
|
||||
FcrBaseDTO: ToFcrBaseDTO(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
}
|
||||
}
|
||||
|
||||
func ToFcrListDTOs(e []entity.Fcr) []FcrListDTO {
|
||||
result := make([]FcrListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToFcrListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToFcrDetailDTO(e entity.Fcr) FcrDetailDTO {
|
||||
return FcrDetailDTO{
|
||||
FcrListDTO: ToFcrListDTO(e),
|
||||
Standards: ToFcrStandardDTOs(e.Standards),
|
||||
}
|
||||
}
|
||||
|
||||
func ToFcrStandardDTOs(standards []entity.FcrStandard) []FcrStandardDTO {
|
||||
result := make([]FcrStandardDTO, len(standards))
|
||||
for i, s := range standards {
|
||||
result[i] = FcrStandardDTO{
|
||||
Id: s.Id,
|
||||
Weight: s.Weight,
|
||||
FcrNumber: s.FcrNumber,
|
||||
Mortality: s.Mortality,
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package fcrs
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rFcr "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/repositories"
|
||||
sFcr "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type FcrModule struct{}
|
||||
|
||||
func (FcrModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
fcrRepo := rFcr.NewFcrRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
fcrService := sFcr.NewFcrService(fcrRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
FcrRoutes(router, userService, fcrService)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type FcrRepository interface {
|
||||
repository.BaseRepository[entity.Fcr]
|
||||
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
|
||||
SyncStandardsDiff(ctx context.Context, tx *gorm.DB, fcrID uint, standards []entity.FcrStandard) error
|
||||
}
|
||||
|
||||
type FcrRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Fcr]
|
||||
}
|
||||
|
||||
func NewFcrRepository(db *gorm.DB) FcrRepository {
|
||||
return &FcrRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Fcr](db),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *FcrRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
|
||||
return repository.ExistsByName[entity.Fcr](ctx, r.DB(), name, excludeID)
|
||||
}
|
||||
|
||||
func (r *FcrRepositoryImpl) SyncStandardsDiff(ctx context.Context, tx *gorm.DB, fcrID uint, standards []entity.FcrStandard) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
|
||||
var existing []entity.FcrStandard
|
||||
if err := db.WithContext(ctx).
|
||||
Where("fcr_id = ?", fcrID).
|
||||
Find(&existing).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existingMap := make(map[float64]entity.FcrStandard)
|
||||
for _, st := range existing {
|
||||
existingMap[st.Weight] = st
|
||||
}
|
||||
|
||||
newMap := make(map[float64]entity.FcrStandard)
|
||||
for _, st := range standards {
|
||||
st.FcrID = fcrID
|
||||
newMap[st.Weight] = st
|
||||
}
|
||||
|
||||
baseRepo := repository.NewBaseRepository[entity.FcrStandard](db)
|
||||
|
||||
for weight, newStd := range newMap {
|
||||
if current, ok := existingMap[weight]; ok {
|
||||
if current.FcrNumber != newStd.FcrNumber || current.Mortality != newStd.Mortality {
|
||||
update := map[string]any{
|
||||
"fcr_number": newStd.FcrNumber,
|
||||
"mortality": newStd.Mortality,
|
||||
}
|
||||
if err := baseRepo.PatchOne(ctx, current.Id, update, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
entry := newStd
|
||||
if err := baseRepo.CreateOne(ctx, &entry, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for weight, current := range existingMap {
|
||||
if _, keep := newMap[weight]; !keep {
|
||||
if err := baseRepo.DeleteOne(ctx, current.Id); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package fcrs
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/controllers"
|
||||
fcr "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func FcrRoutes(v1 fiber.Router, u user.UserService, s fcr.FcrService) {
|
||||
ctrl := controller.NewFcrController(s)
|
||||
|
||||
route := v1.Group("/fcrs")
|
||||
|
||||
// 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,219 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/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 FcrService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Fcr, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.Fcr, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Fcr, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Fcr, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type fcrService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.FcrRepository
|
||||
}
|
||||
|
||||
func NewFcrService(repo repository.FcrRepository, validate *validator.Validate) FcrService {
|
||||
return &fcrService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s fcrService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.
|
||||
Preload("CreatedUser").
|
||||
Preload("Standards", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("weight ASC")
|
||||
})
|
||||
}
|
||||
|
||||
func (s fcrService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Fcr, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
fcrs, 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 fcrs: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return fcrs, total, nil
|
||||
}
|
||||
|
||||
func (s fcrService) GetOne(c *fiber.Ctx, id uint) (*entity.Fcr, error) {
|
||||
fcr, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Fcr not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get fcr by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return fcr, nil
|
||||
}
|
||||
|
||||
func (s *fcrService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Fcr, 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 fcr name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check fcr name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Fcr with name %s already exists", req.Name))
|
||||
}
|
||||
|
||||
createBody := &entity.Fcr{
|
||||
Name: req.Name,
|
||||
CreatedBy: 1,
|
||||
}
|
||||
|
||||
err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if err := repoTx.CreateOne(c.Context(), createBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(req.FcrStandards) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
standards := make([]entity.FcrStandard, len(req.FcrStandards))
|
||||
for i, std := range req.FcrStandards {
|
||||
standards[i] = entity.FcrStandard{
|
||||
FcrID: createBody.Id,
|
||||
Weight: std.Weight,
|
||||
FcrNumber: std.FcrNumber,
|
||||
Mortality: std.Mortality,
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.Repository.SyncStandardsDiff(c.Context(), tx, createBody.Id, standards); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to create fcr: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s fcrService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Fcr, 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 fcr name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check fcr name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Fcr with name %s already exists", *req.Name))
|
||||
}
|
||||
updateBody["name"] = *req.Name
|
||||
}
|
||||
|
||||
if len(updateBody) == 0 && req.FcrStandards == nil {
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if len(updateBody) > 0 {
|
||||
if err := repoTx.PatchOne(c.Context(), id, updateBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := repoTx.GetByID(c.Context(), id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if req.FcrStandards != nil {
|
||||
standards := make([]entity.FcrStandard, len(req.FcrStandards))
|
||||
for i, std := range req.FcrStandards {
|
||||
standards[i] = entity.FcrStandard{
|
||||
FcrID: id,
|
||||
Weight: std.Weight,
|
||||
FcrNumber: std.FcrNumber,
|
||||
Mortality: std.Mortality,
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.Repository.SyncStandardsDiff(c.Context(), tx, id, standards); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Fcr not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update fcr: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s fcrService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if err := s.Repository.SyncStandardsDiff(c.Context(), tx, id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return repoTx.DeleteOne(c.Context(), id)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Fcr not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete fcr: %+v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package validation
|
||||
|
||||
type FcrStandard struct {
|
||||
Weight float64 `json:"weight" validate:"required,gte=0"`
|
||||
FcrNumber float64 `json:"fcr_number" validate:"required,gte=0"`
|
||||
Mortality float64 `json:"mortality" validate:"required,gte=0"`
|
||||
}
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3,max=50"`
|
||||
FcrStandards []FcrStandard `json:"fcr_standards" validate:"required,min=1,dive"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty_strict,min=3,max=50"`
|
||||
FcrStandards []FcrStandard `json:"fcr_standards,omitempty" validate:"omitempty,min=1,dive"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
@@ -73,3 +73,9 @@ func ToKandangListDTOs(e []entity.Kandang) []KandangListDTO {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToKandangDetailDTO(e entity.Kandang) KandangDetailDTO {
|
||||
return KandangDetailDTO{
|
||||
KandangListDTO: ToKandangListDTO(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ func (s *kandangService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entit
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.Repository.GetByID(c.Context(), createBody.Id, s.withRelations)
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s kandangService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Kandang, error) {
|
||||
@@ -128,17 +128,18 @@ func (s kandangService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint)
|
||||
updateBody["name"] = *req.Name
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(c.Context(),
|
||||
common.RelationCheck{Name: "Location", ID: req.LocationId, Exists: s.Repository.LocationExists},
|
||||
common.RelationCheck{Name: "Pic", ID: req.PicId, Exists: s.Repository.PicExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.LocationId != nil {
|
||||
if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Location", ID: req.LocationId, Exists: s.Repository.LocationExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updateBody["location_id"] = *req.LocationId
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ type Create struct {
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
LocationId *uint `json:"location_id,omitempty" validate:"omitempty,number,gt=0"`
|
||||
PicId *uint `json:"pic_id,omitempty" validate:"omitempty,number,gt=0"`
|
||||
}
|
||||
|
||||
@@ -67,3 +67,9 @@ func ToLocationListDTOs(e []entity.Location) []LocationListDTO {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToLocationDetailDTO(e entity.Location) LocationDetailDTO {
|
||||
return LocationDetailDTO{
|
||||
LocationListDTO: ToLocationListDTO(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,13 +107,7 @@ func (s *locationService) CreateOne(c *fiber.Ctx, req *validation.Create) (*enti
|
||||
return nil, err
|
||||
}
|
||||
|
||||
created, err := s.Repository.GetByID(c.Context(), createBody.Id, s.withRelations)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to reload created location: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return created, nil
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s locationService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Location, error) {
|
||||
@@ -137,10 +131,11 @@ func (s locationService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint
|
||||
updateBody["address"] = *req.Address
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Area", ID: req.AreaId, Exists: s.Repository.AreaExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.AreaId != nil {
|
||||
if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Area", ID: req.AreaId, Exists: s.Repository.AreaExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updateBody["area_id"] = *req.AreaId
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ type Create struct {
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
Address *string `json:"address,omitempty" validate:"omitempty"`
|
||||
AreaId *uint `json:"area_id,omitempty" validate:"omitempty,number,gt=0"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type NonstockController struct {
|
||||
NonstockService service.NonstockService
|
||||
}
|
||||
|
||||
func NewNonstockController(nonstockService service.NonstockService) *NonstockController {
|
||||
return &NonstockController{
|
||||
NonstockService: nonstockService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.NonstockListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all nonstocks successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToNonstockListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get nonstock successfully",
|
||||
Data: dto.ToNonstockDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create nonstock successfully",
|
||||
Data: dto.ToNonstockDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.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 nonstock successfully",
|
||||
Data: dto.ToNonstockDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *NonstockController) 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.NonstockService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete nonstock successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
supplierDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/dto"
|
||||
uomDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/uoms/dto"
|
||||
userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
|
||||
)
|
||||
|
||||
// === DTO Structs ===
|
||||
|
||||
type NonstockBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
UomID uint `json:"uom_id"`
|
||||
}
|
||||
|
||||
type NonstockListDTO struct {
|
||||
NonstockBaseDTO
|
||||
Uom *uomDTO.UomBaseDTO `json:"uom,omitempty"`
|
||||
Suppliers []supplierDTO.SupplierBaseDTO `json:"suppliers"`
|
||||
Flags []string `json:"flags"`
|
||||
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type NonstockDetailDTO struct {
|
||||
NonstockListDTO
|
||||
Flags []string `json:"flags"`
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToNonstockBaseDTO(e entity.Nonstock) NonstockBaseDTO {
|
||||
return NonstockBaseDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
UomID: e.UomId,
|
||||
}
|
||||
}
|
||||
|
||||
func ToNonstockListDTO(e entity.Nonstock) NonstockListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
var uomRef *uomDTO.UomBaseDTO
|
||||
if e.Uom.Id != 0 {
|
||||
mapped := uomDTO.ToUomBaseDTO(e.Uom)
|
||||
uomRef = &mapped
|
||||
}
|
||||
|
||||
suppliers := make([]supplierDTO.SupplierBaseDTO, len(e.Suppliers))
|
||||
for i, s := range e.Suppliers {
|
||||
suppliers[i] = supplierDTO.ToSupplierBaseDTO(s)
|
||||
}
|
||||
|
||||
flags := make([]string, len(e.Flags))
|
||||
for i, f := range e.Flags {
|
||||
flags[i] = f.Name
|
||||
}
|
||||
|
||||
return NonstockListDTO{
|
||||
NonstockBaseDTO: ToNonstockBaseDTO(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
Uom: uomRef,
|
||||
Suppliers: suppliers,
|
||||
Flags: flags,
|
||||
}
|
||||
}
|
||||
|
||||
func ToNonstockListDTOs(e []entity.Nonstock) []NonstockListDTO {
|
||||
result := make([]NonstockListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToNonstockListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToNonstockDetailDTO(e entity.Nonstock) NonstockDetailDTO {
|
||||
flags := make([]string, len(e.Flags))
|
||||
for i, f := range e.Flags {
|
||||
flags[i] = f.Name
|
||||
}
|
||||
|
||||
return NonstockDetailDTO{
|
||||
NonstockListDTO: ToNonstockListDTO(e),
|
||||
Flags: flags,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package nonstocks
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rNonstock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/repositories"
|
||||
sNonstock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type NonstockModule struct{}
|
||||
|
||||
func (NonstockModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
nonstockRepo := rNonstock.NewNonstockRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
nonstockService := sNonstock.NewNonstockService(nonstockRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
NonstockRoutes(router, userService, nonstockService)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type NonstockRepository interface {
|
||||
repository.BaseRepository[entity.Nonstock]
|
||||
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
|
||||
SyncSuppliersDiff(ctx context.Context, tx *gorm.DB, nonstockID uint, supplierIDs []uint) error
|
||||
UomExists(ctx context.Context, uomID uint) (bool, error)
|
||||
GetSuppliersByIDs(ctx context.Context, supplierIDs []uint) ([]entity.Supplier, error)
|
||||
SyncFlags(ctx context.Context, tx *gorm.DB, nonstockID uint, flags []string) error
|
||||
DeleteFlags(ctx context.Context, tx *gorm.DB, nonstockID uint) error
|
||||
GetFlags(ctx context.Context, nonstockID uint) ([]entity.Flag, error)
|
||||
}
|
||||
|
||||
type NonstockRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Nonstock]
|
||||
}
|
||||
|
||||
func NewNonstockRepository(db *gorm.DB) NonstockRepository {
|
||||
return &NonstockRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Nonstock](db),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
|
||||
return repository.ExistsByName[entity.Nonstock](ctx, r.DB(), name, excludeID)
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) SyncSuppliersDiff(ctx context.Context, tx *gorm.DB, nonstockID uint, supplierIDs []uint) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
|
||||
if supplierIDs == nil {
|
||||
return db.WithContext(ctx).
|
||||
Where("nonstock_id = ?", nonstockID).
|
||||
Delete(&entity.NonstockSupplier{}).
|
||||
Error
|
||||
}
|
||||
|
||||
var existing []entity.NonstockSupplier
|
||||
if err := db.WithContext(ctx).
|
||||
Where("nonstock_id = ?", nonstockID).
|
||||
Find(&existing).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existingMap := make(map[uint]struct{}, len(existing))
|
||||
for _, rel := range existing {
|
||||
existingMap[rel.SupplierID] = struct{}{}
|
||||
}
|
||||
|
||||
incomingMap := make(map[uint]struct{}, len(supplierIDs))
|
||||
for _, id := range supplierIDs {
|
||||
incomingMap[id] = struct{}{}
|
||||
if _, exists := existingMap[id]; exists {
|
||||
continue
|
||||
}
|
||||
record := entity.NonstockSupplier{NonstockID: nonstockID, SupplierID: id}
|
||||
if err := db.WithContext(ctx).Create(&record).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, rel := range existing {
|
||||
if _, keep := incomingMap[rel.SupplierID]; !keep {
|
||||
if err := db.WithContext(ctx).
|
||||
Where("nonstock_id = ? AND supplier_id = ?", nonstockID, rel.SupplierID).
|
||||
Delete(&entity.NonstockSupplier{}).
|
||||
Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) UomExists(ctx context.Context, uomID uint) (bool, error) {
|
||||
var count int64
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Model(&entity.Uom{}).
|
||||
Where("id = ?", uomID).
|
||||
Count(&count).
|
||||
Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) GetSuppliersByIDs(ctx context.Context, supplierIDs []uint) ([]entity.Supplier, error) {
|
||||
if len(supplierIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var suppliers []entity.Supplier
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Select("id", "category").
|
||||
Where("id IN ?", supplierIDs).
|
||||
Find(&suppliers).
|
||||
Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return suppliers, nil
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) SyncFlags(ctx context.Context, tx *gorm.DB, nonstockID uint, flags []string) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
|
||||
// Hapus flags lama terlebih dahulu
|
||||
if err := db.WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", nonstockID, entity.FlagableTypeNonstock).
|
||||
Delete(&entity.Flag{}).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Insert flags baru jika ada
|
||||
if len(flags) > 0 {
|
||||
newFlags := make([]entity.Flag, len(flags))
|
||||
for i, f := range flags {
|
||||
newFlags[i] = entity.Flag{
|
||||
Name: f,
|
||||
FlagableID: nonstockID,
|
||||
FlagableType: entity.FlagableTypeNonstock,
|
||||
}
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(&newFlags).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) DeleteFlags(ctx context.Context, tx *gorm.DB, nonstockID uint) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
return db.WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", nonstockID, entity.FlagableTypeNonstock).
|
||||
Delete(&entity.Flag{}).
|
||||
Error
|
||||
}
|
||||
|
||||
func (r *NonstockRepositoryImpl) GetFlags(ctx context.Context, nonstockID uint) ([]entity.Flag, error) {
|
||||
var flags []entity.Flag
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", nonstockID, entity.FlagableTypeNonstock).
|
||||
Find(&flags).
|
||||
Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return flags, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package nonstocks
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/controllers"
|
||||
nonstock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func NonstockRoutes(v1 fiber.Router, u user.UserService, s nonstock.NonstockService) {
|
||||
ctrl := controller.NewNonstockController(s)
|
||||
|
||||
route := v1.Group("/nonstocks")
|
||||
|
||||
// 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,308 @@
|
||||
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/nonstocks/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks/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 NonstockService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Nonstock, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.Nonstock, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Nonstock, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Nonstock, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type nonstockService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.NonstockRepository
|
||||
}
|
||||
|
||||
func NewNonstockService(repo repository.NonstockRepository, validate *validator.Validate) NonstockService {
|
||||
return &nonstockService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s nonstockService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.
|
||||
Preload("CreatedUser").
|
||||
Preload("Uom").
|
||||
Preload("Flags").
|
||||
Preload("Suppliers", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("suppliers.name ASC")
|
||||
})
|
||||
}
|
||||
|
||||
func (s nonstockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Nonstock, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
nonstocks, 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 nonstocks: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return nonstocks, total, nil
|
||||
}
|
||||
|
||||
func (s nonstockService) GetOne(c *fiber.Ctx, id uint) (*entity.Nonstock, error) {
|
||||
nonstock, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Nonstock not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get nonstock by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return nonstock, nil
|
||||
}
|
||||
|
||||
func (s *nonstockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Nonstock, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
name := strings.TrimSpace(req.Name)
|
||||
|
||||
if exists, err := s.Repository.NameExists(ctx, name, nil); err != nil {
|
||||
s.Log.Errorf("Failed to check nonstock name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check nonstock name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Nonstock with name %s already exists", name))
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(ctx, common.RelationCheck{Name: "Uom", ID: &req.UomID, Exists: s.Repository.UomExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
supplierIDs := utils.UniqueUintSlice(req.SupplierIDs)
|
||||
if len(supplierIDs) > 0 {
|
||||
supplierList, supplierErr := s.Repository.GetSuppliersByIDs(ctx, supplierIDs)
|
||||
if supplierErr != nil {
|
||||
s.Log.Errorf("Failed to validate suppliers: %+v", supplierErr)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate suppliers")
|
||||
}
|
||||
if len(supplierList) != len(supplierIDs) {
|
||||
actualIDs := make([]uint, len(supplierList))
|
||||
for i, supplier := range supplierList {
|
||||
actualIDs[i] = supplier.Id
|
||||
}
|
||||
missing := utils.MissingUintIDs(supplierIDs, actualIDs)
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Suppliers with ids %v not found", missing))
|
||||
}
|
||||
for _, sup := range supplierList {
|
||||
if strings.ToUpper(sup.Category) != string(utils.SupplierCategoryBOP) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Supplier with id %d is not category BOP", sup.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nonstockFlags, flagErr := normalizeNonstockFlags(req.Flags)
|
||||
if flagErr != nil {
|
||||
return nil, flagErr
|
||||
}
|
||||
|
||||
createBody := &entity.Nonstock{
|
||||
Name: req.Name,
|
||||
UomId: req.UomID,
|
||||
CreatedBy: 1,
|
||||
}
|
||||
|
||||
err := s.Repository.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if err := repoTx.CreateOne(ctx, createBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.Repository.SyncFlags(ctx, tx, createBody.Id, nonstockFlags); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.Repository.SyncSuppliersDiff(ctx, tx, createBody.Id, supplierIDs)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to create nonstock: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s nonstockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Nonstock, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
ctx := c.Context()
|
||||
|
||||
if err := common.EnsureRelations(ctx, common.RelationCheck{Name: "Uom", ID: req.UomID, Exists: s.Repository.UomExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
if exists, err := s.Repository.NameExists(ctx, *req.Name, &id); err != nil {
|
||||
s.Log.Errorf("Failed to check nonstock name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check nonstock name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Nonstock with name %s already exists", *req.Name))
|
||||
}
|
||||
|
||||
updateBody["name"] = *req.Name
|
||||
}
|
||||
if req.UomID != nil {
|
||||
updateBody["uom_id"] = *req.UomID
|
||||
}
|
||||
|
||||
var supplierIDs []uint
|
||||
var supplierUpdate bool
|
||||
if req.SupplierIDs != nil {
|
||||
supplierUpdate = true
|
||||
supplierIDs = utils.UniqueUintSlice(*req.SupplierIDs)
|
||||
if len(supplierIDs) > 0 {
|
||||
var supplierList []entity.Supplier
|
||||
var supplierErr error
|
||||
supplierList, supplierErr = s.Repository.GetSuppliersByIDs(ctx, supplierIDs)
|
||||
if supplierErr != nil {
|
||||
s.Log.Errorf("Failed to validate suppliers: %+v", supplierErr)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate suppliers")
|
||||
}
|
||||
if len(supplierList) != len(supplierIDs) {
|
||||
actualIDs := make([]uint, len(supplierList))
|
||||
for i, supplier := range supplierList {
|
||||
actualIDs[i] = supplier.Id
|
||||
}
|
||||
missing := utils.MissingUintIDs(supplierIDs, actualIDs)
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Suppliers with ids %v not found", missing))
|
||||
}
|
||||
for _, sup := range supplierList {
|
||||
if strings.ToUpper(sup.Category) != string(utils.SupplierCategoryBOP) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Supplier with id %d is not category BOP", sup.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
flagUpdate bool
|
||||
flagValues []string
|
||||
)
|
||||
if req.Flags != nil {
|
||||
flagUpdate = true
|
||||
var flagErr error
|
||||
flagValues, flagErr = normalizeNonstockFlags(*req.Flags)
|
||||
if flagErr != nil {
|
||||
return nil, flagErr
|
||||
}
|
||||
}
|
||||
|
||||
if len(updateBody) == 0 && !supplierUpdate && !flagUpdate {
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
err := s.Repository.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if len(updateBody) > 0 {
|
||||
if err := repoTx.PatchOne(ctx, id, updateBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := repoTx.GetByID(ctx, id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if supplierUpdate {
|
||||
var ids []uint
|
||||
if len(supplierIDs) > 0 {
|
||||
ids = supplierIDs
|
||||
}
|
||||
if err := s.Repository.SyncSuppliersDiff(ctx, tx, id, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if flagUpdate {
|
||||
if err := s.Repository.SyncFlags(ctx, tx, id, flagValues); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Nonstock not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update nonstock: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s nonstockService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if err := s.Repository.SyncSuppliersDiff(c.Context(), tx, id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.Repository.DeleteFlags(c.Context(), tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return repoTx.DeleteOne(c.Context(), id)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Nonstock not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete nonstock: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeNonstockFlags(raw []string) ([]string, error) {
|
||||
normalized, invalid := utils.NormalizeFlagsForGroup(raw, utils.FlagGroupNonstock)
|
||||
if len(invalid) > 0 {
|
||||
invalidStr := strings.Join(utils.FlagTypesToStrings(invalid), ", ")
|
||||
allowedStr := strings.Join(utils.FlagTypesToStrings(utils.AllowedFlagTypes(utils.FlagGroupNonstock)), ", ")
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Invalid nonstock flags: %s. Allowed flags: %s", invalidStr, allowedStr))
|
||||
}
|
||||
return utils.FlagTypesToStrings(normalized), nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
UomID uint `json:"uom_id" validate:"required,gt=0"`
|
||||
SupplierIDs []uint `json:"supplier_ids,omitempty" validate:"omitempty,dive,gt=0"`
|
||||
Flags []string `json:"flags,omitempty" validate:"omitempty,dive,max=50"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,min=3"`
|
||||
UomID *uint `json:"uom_id,omitempty" validate:"omitempty,gt=0"`
|
||||
SupplierIDs *[]uint `json:"supplier_ids,omitempty" validate:"omitempty,dive,gt=0"`
|
||||
Flags *[]string `json:"flags,omitempty" validate:"omitempty,dive,max=50"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type ProductCategoryController struct {
|
||||
ProductCategoryService service.ProductCategoryService
|
||||
}
|
||||
|
||||
func NewProductCategoryController(productCategoryService service.ProductCategoryService) *ProductCategoryController {
|
||||
return &ProductCategoryController{
|
||||
ProductCategoryService: productCategoryService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ProductCategoryController) 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.ProductCategoryService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.ProductCategoryListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all product categories successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToProductCategoryListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductCategoryController) 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.ProductCategoryService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get product category successfully",
|
||||
Data: dto.ToProductCategoryDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductCategoryController) 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.ProductCategoryService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create product category successfully",
|
||||
Data: dto.ToProductCategoryDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductCategoryController) 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.ProductCategoryService.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 product category successfully",
|
||||
Data: dto.ToProductCategoryDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductCategoryController) 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.ProductCategoryService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete product category successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
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 ProductCategoryBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
type ProductCategoryListDTO struct {
|
||||
ProductCategoryBaseDTO
|
||||
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ProductCategoryDetailDTO struct {
|
||||
ProductCategoryListDTO
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToProductCategoryBaseDTO(e entity.ProductCategory) ProductCategoryBaseDTO {
|
||||
return ProductCategoryBaseDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
Code: e.Code,
|
||||
}
|
||||
}
|
||||
|
||||
func ToProductCategoryListDTO(e entity.ProductCategory) ProductCategoryListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
return ProductCategoryListDTO{
|
||||
ProductCategoryBaseDTO: ToProductCategoryBaseDTO(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
}
|
||||
}
|
||||
|
||||
func ToProductCategoryListDTOs(e []entity.ProductCategory) []ProductCategoryListDTO {
|
||||
result := make([]ProductCategoryListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToProductCategoryListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToProductCategoryDetailDTO(e entity.ProductCategory) ProductCategoryDetailDTO {
|
||||
return ProductCategoryDetailDTO{
|
||||
ProductCategoryListDTO: ToProductCategoryListDTO(e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package productcategories
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rProductCategory "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/repositories"
|
||||
sProductCategory "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type ProductCategoryModule struct{}
|
||||
|
||||
func (ProductCategoryModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
productCategoryRepo := rProductCategory.NewProductCategoryRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
productCategoryService := sProductCategory.NewProductCategoryService(productCategoryRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
ProductCategoryRoutes(router, userService, productCategoryService)
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
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 ProductCategoryRepository interface {
|
||||
repository.BaseRepository[entity.ProductCategory]
|
||||
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
|
||||
CodeExists(ctx context.Context, code string, excludeID *uint) (bool, error)
|
||||
}
|
||||
|
||||
type ProductCategoryRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.ProductCategory]
|
||||
}
|
||||
|
||||
func NewProductCategoryRepository(db *gorm.DB) ProductCategoryRepository {
|
||||
return &ProductCategoryRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.ProductCategory](db),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ProductCategoryRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
|
||||
return repository.ExistsByName[entity.ProductCategory](ctx, r.DB(), name, excludeID)
|
||||
}
|
||||
|
||||
func (r *ProductCategoryRepositoryImpl) CodeExists(ctx context.Context, code string, excludeID *uint) (bool, error) {
|
||||
var count int64
|
||||
q := r.DB().WithContext(ctx).
|
||||
Model(new(entity.ProductCategory)).
|
||||
Where("code = ?", code).
|
||||
Where("deleted_at IS NULL")
|
||||
if excludeID != nil {
|
||||
q = q.Where("id <> ?", *excludeID)
|
||||
}
|
||||
if err := q.Count(&count).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package productcategories
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/controllers"
|
||||
productCategory "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func ProductCategoryRoutes(v1 fiber.Router, u user.UserService, s productCategory.ProductCategoryService) {
|
||||
ctrl := controller.NewProductCategoryController(s)
|
||||
|
||||
route := v1.Group("/product-categories")
|
||||
|
||||
// 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,175 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/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 ProductCategoryService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.ProductCategory, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.ProductCategory, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.ProductCategory, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.ProductCategory, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type productCategoryService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.ProductCategoryRepository
|
||||
}
|
||||
|
||||
func NewProductCategoryService(repo repository.ProductCategoryRepository, validate *validator.Validate) ProductCategoryService {
|
||||
return &productCategoryService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s productCategoryService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("CreatedUser")
|
||||
}
|
||||
|
||||
func (s productCategoryService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.ProductCategory, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
productCategories, 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 product categories: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return productCategories, total, nil
|
||||
}
|
||||
|
||||
func (s productCategoryService) GetOne(c *fiber.Ctx, id uint) (*entity.ProductCategory, error) {
|
||||
productCategory, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Product category not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get product category by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return productCategory, nil
|
||||
}
|
||||
|
||||
func (s *productCategoryService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.ProductCategory, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
name := strings.TrimSpace(req.Name)
|
||||
code := strings.ToUpper(strings.TrimSpace(req.Code))
|
||||
|
||||
if exists, err := s.Repository.NameExists(ctx, name, nil); err != nil {
|
||||
s.Log.Errorf("Failed to check product category name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product category name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product category with name %s already exists", name))
|
||||
}
|
||||
|
||||
if exists, err := s.Repository.CodeExists(ctx, code, nil); err != nil {
|
||||
s.Log.Errorf("Failed to check product category code: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product category code")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product category with code %s already exists", code))
|
||||
}
|
||||
|
||||
createBody := &entity.ProductCategory{
|
||||
Name: name,
|
||||
Code: code,
|
||||
CreatedBy: 1,
|
||||
}
|
||||
|
||||
if err := s.Repository.CreateOne(ctx, createBody, nil); err != nil {
|
||||
s.Log.Errorf("Failed to create product category: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s productCategoryService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.ProductCategory, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
if req.Name != nil {
|
||||
name := strings.TrimSpace(*req.Name)
|
||||
if name == "" {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Name cannot be empty")
|
||||
}
|
||||
if exists, err := s.Repository.NameExists(c.Context(), name, &id); err != nil {
|
||||
s.Log.Errorf("Failed to check product category name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product category name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product category with name %s already exists", name))
|
||||
}
|
||||
updateBody["name"] = name
|
||||
}
|
||||
|
||||
if req.Code != nil {
|
||||
code := strings.ToUpper(strings.TrimSpace(*req.Code))
|
||||
if code == "" {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Code cannot be empty")
|
||||
}
|
||||
if exists, err := s.Repository.CodeExists(c.Context(), code, &id); err != nil {
|
||||
s.Log.Errorf("Failed to check product category code: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product category code")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product category with code %s already exists", code))
|
||||
}
|
||||
updateBody["code"] = code
|
||||
}
|
||||
|
||||
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, "Product category not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update product category: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s productCategoryService) 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, "Product category not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete product category: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
Code string `json:"code" validate:"required_strict,max=10"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
Code *string `json:"code,omitempty" validate:"omitempty,max=10"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type ProductController struct {
|
||||
ProductService service.ProductService
|
||||
}
|
||||
|
||||
func NewProductController(productService service.ProductService) *ProductController {
|
||||
return &ProductController{
|
||||
ProductService: productService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *ProductController) 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.ProductService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.ProductListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all products successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToProductListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductController) 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.ProductService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get product successfully",
|
||||
Data: dto.ToProductDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductController) 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.ProductService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create product successfully",
|
||||
Data: dto.ToProductDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductController) 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.ProductService.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 product successfully",
|
||||
Data: dto.ToProductDetailDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *ProductController) 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.ProductService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete product successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
productCategoryDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories/dto"
|
||||
supplierDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/dto"
|
||||
uomDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/uoms/dto"
|
||||
userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
|
||||
)
|
||||
|
||||
// === DTO Structs ===
|
||||
|
||||
type ProductBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type ProductListDTO struct {
|
||||
ProductBaseDTO
|
||||
Brand string `json:"brand"`
|
||||
Sku *string `json:"sku,omitempty"`
|
||||
ProductPrice float64 `json:"product_price"`
|
||||
SellingPrice *float64 `json:"selling_price,omitempty"`
|
||||
Tax *float64 `json:"tax,omitempty"`
|
||||
ExpiryPeriod *int `json:"expiry_period,omitempty"`
|
||||
Uom *uomDTO.UomBaseDTO `json:"uom,omitempty"`
|
||||
ProductCategory *productCategoryDTO.ProductCategoryBaseDTO `json:"product_category,omitempty"`
|
||||
Suppliers []supplierDTO.SupplierBaseDTO `json:"suppliers"`
|
||||
Flags []string `json:"flags"`
|
||||
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ProductDetailDTO struct {
|
||||
ProductListDTO
|
||||
Flags []string `json:"flags"`
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToProductBaseDTO(e entity.Product) ProductBaseDTO {
|
||||
return ProductBaseDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
}
|
||||
}
|
||||
|
||||
func ToProductListDTO(e entity.Product) ProductListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
var uomRef *uomDTO.UomBaseDTO
|
||||
if e.Uom.Id != 0 {
|
||||
mapped := uomDTO.ToUomBaseDTO(e.Uom)
|
||||
uomRef = &mapped
|
||||
}
|
||||
|
||||
var categoryRef *productCategoryDTO.ProductCategoryBaseDTO
|
||||
if e.ProductCategory.Id != 0 {
|
||||
mapped := productCategoryDTO.ToProductCategoryBaseDTO(e.ProductCategory)
|
||||
categoryRef = &mapped
|
||||
}
|
||||
|
||||
suppliers := make([]supplierDTO.SupplierBaseDTO, len(e.Suppliers))
|
||||
for i, s := range e.Suppliers {
|
||||
suppliers[i] = supplierDTO.ToSupplierBaseDTO(s)
|
||||
}
|
||||
|
||||
flags := make([]string, len(e.Flags))
|
||||
for i, f := range e.Flags {
|
||||
flags[i] = f.Name
|
||||
}
|
||||
|
||||
return ProductListDTO{
|
||||
Brand: e.Brand,
|
||||
Sku: e.Sku,
|
||||
ProductPrice: e.ProductPrice,
|
||||
SellingPrice: e.SellingPrice,
|
||||
Tax: e.Tax,
|
||||
ExpiryPeriod: e.ExpiryPeriod,
|
||||
ProductBaseDTO: ToProductBaseDTO(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
Uom: uomRef,
|
||||
ProductCategory: categoryRef,
|
||||
Suppliers: suppliers,
|
||||
Flags: flags,
|
||||
}
|
||||
}
|
||||
|
||||
func ToProductListDTOs(e []entity.Product) []ProductListDTO {
|
||||
result := make([]ProductListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToProductListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToProductDetailDTO(e entity.Product) ProductDetailDTO {
|
||||
flags := make([]string, len(e.Flags))
|
||||
for i, f := range e.Flags {
|
||||
flags[i] = f.Name
|
||||
}
|
||||
|
||||
return ProductDetailDTO{
|
||||
ProductListDTO: ToProductListDTO(e),
|
||||
Flags: flags,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package products
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rProduct "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/repositories"
|
||||
sProduct "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type ProductModule struct{}
|
||||
|
||||
func (ProductModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
productRepo := rProduct.NewProductRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
productService := sProduct.NewProductService(productRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
ProductRoutes(router, userService, productService)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
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 ProductRepository interface {
|
||||
repository.BaseRepository[entity.Product]
|
||||
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
|
||||
SkuExists(ctx context.Context, sku string, excludeID *uint) (bool, error)
|
||||
UomExists(ctx context.Context, uomID uint) (bool, error)
|
||||
CategoryExists(ctx context.Context, categoryID uint) (bool, error)
|
||||
GetSuppliersByIDs(ctx context.Context, supplierIDs []uint) ([]entity.Supplier, error)
|
||||
SyncSuppliersDiff(ctx context.Context, tx *gorm.DB, productID uint, supplierIDs []uint) error
|
||||
SyncFlags(ctx context.Context, tx *gorm.DB, productID uint, flags []string) error
|
||||
DeleteFlags(ctx context.Context, tx *gorm.DB, productID uint) error
|
||||
GetFlags(ctx context.Context, productID uint) ([]entity.Flag, error)
|
||||
}
|
||||
|
||||
type ProductRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Product]
|
||||
}
|
||||
|
||||
func NewProductRepository(db *gorm.DB) ProductRepository {
|
||||
return &ProductRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Product](db),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
|
||||
return repository.ExistsByName[entity.Product](ctx, r.DB(), name, excludeID)
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) SkuExists(ctx context.Context, sku string, excludeID *uint) (bool, error) {
|
||||
var count int64
|
||||
q := r.DB().WithContext(ctx).
|
||||
Model(new(entity.Product)).
|
||||
Where("sku = ?", sku).
|
||||
Where("deleted_at IS NULL")
|
||||
if excludeID != nil {
|
||||
q = q.Where("id <> ?", *excludeID)
|
||||
}
|
||||
if err := q.Count(&count).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) UomExists(ctx context.Context, uomID uint) (bool, error) {
|
||||
var count int64
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Model(&entity.Uom{}).
|
||||
Where("id = ?", uomID).
|
||||
Count(&count).
|
||||
Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) CategoryExists(ctx context.Context, categoryID uint) (bool, error) {
|
||||
var count int64
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Model(&entity.ProductCategory{}).
|
||||
Where("id = ?", categoryID).
|
||||
Count(&count).
|
||||
Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetSuppliersByIDs(ctx context.Context, supplierIDs []uint) ([]entity.Supplier, error) {
|
||||
if len(supplierIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var suppliers []entity.Supplier
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Select("id", "category").
|
||||
Where("id IN ?", supplierIDs).
|
||||
Find(&suppliers).
|
||||
Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return suppliers, nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) SyncSuppliersDiff(ctx context.Context, tx *gorm.DB, productID uint, supplierIDs []uint) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
|
||||
if supplierIDs == nil {
|
||||
return db.WithContext(ctx).
|
||||
Where("product_id = ?", productID).
|
||||
Delete(&entity.ProductSupplier{}).
|
||||
Error
|
||||
}
|
||||
|
||||
var existing []entity.ProductSupplier
|
||||
if err := db.WithContext(ctx).
|
||||
Where("product_id = ?", productID).
|
||||
Find(&existing).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existingMap := make(map[uint]struct{}, len(existing))
|
||||
for _, rel := range existing {
|
||||
existingMap[rel.SupplierID] = struct{}{}
|
||||
}
|
||||
|
||||
incomingMap := make(map[uint]struct{}, len(supplierIDs))
|
||||
for _, id := range supplierIDs {
|
||||
incomingMap[id] = struct{}{}
|
||||
if _, exists := existingMap[id]; exists {
|
||||
continue
|
||||
}
|
||||
record := entity.ProductSupplier{ProductID: productID, SupplierID: id}
|
||||
if err := db.WithContext(ctx).Create(&record).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, rel := range existing {
|
||||
if _, keep := incomingMap[rel.SupplierID]; !keep {
|
||||
if err := db.WithContext(ctx).
|
||||
Where("product_id = ? AND supplier_id = ?", productID, rel.SupplierID).
|
||||
Delete(&entity.ProductSupplier{}).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) SyncFlags(ctx context.Context, tx *gorm.DB, productID uint, flags []string) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
|
||||
// Hapus flags lama terlebih dahulu
|
||||
if err := db.WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", productID, entity.FlagableTypeProduct).
|
||||
Delete(&entity.Flag{}).
|
||||
Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Insert flags baru jika ada
|
||||
if len(flags) > 0 {
|
||||
newFlags := make([]entity.Flag, len(flags))
|
||||
for i, f := range flags {
|
||||
newFlags[i] = entity.Flag{
|
||||
Name: f,
|
||||
FlagableID: productID,
|
||||
FlagableType: entity.FlagableTypeProduct,
|
||||
}
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(&newFlags).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) DeleteFlags(ctx context.Context, tx *gorm.DB, productID uint) error {
|
||||
db := tx
|
||||
if db == nil {
|
||||
db = r.DB()
|
||||
}
|
||||
return db.WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", productID, entity.FlagableTypeProduct).
|
||||
Delete(&entity.Flag{}).
|
||||
Error
|
||||
}
|
||||
|
||||
func (r *ProductRepositoryImpl) GetFlags(ctx context.Context, productID uint) ([]entity.Flag, error) {
|
||||
var flags []entity.Flag
|
||||
if err := r.DB().WithContext(ctx).
|
||||
Where("flagable_id = ? AND flagable_type = ?", productID, entity.FlagableTypeProduct).
|
||||
Find(&flags).
|
||||
Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return flags, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package products
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/controllers"
|
||||
product "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func ProductRoutes(v1 fiber.Router, u user.UserService, s product.ProductService) {
|
||||
ctrl := controller.NewProductController(s)
|
||||
|
||||
route := v1.Group("/products")
|
||||
|
||||
// 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,384 @@
|
||||
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/products/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/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 ProductService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Product, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.Product, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Product, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Product, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type productService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.ProductRepository
|
||||
}
|
||||
|
||||
func normalizeProductFlags(raw []string) ([]string, error) {
|
||||
normalized, invalid := utils.NormalizeFlagsForGroup(raw, utils.FlagGroupProduct)
|
||||
if len(invalid) > 0 {
|
||||
invalidStr := strings.Join(utils.FlagTypesToStrings(invalid), ", ")
|
||||
allowedStr := strings.Join(utils.FlagTypesToStrings(utils.AllowedFlagTypes(utils.FlagGroupProduct)), ", ")
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Invalid product flags: %s. Allowed flags: %s", invalidStr, allowedStr))
|
||||
}
|
||||
return utils.FlagTypesToStrings(normalized), nil
|
||||
}
|
||||
|
||||
func NewProductService(repo repository.ProductRepository, validate *validator.Validate) ProductService {
|
||||
return &productService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s productService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.
|
||||
Preload("CreatedUser").
|
||||
Preload("Uom").
|
||||
Preload("ProductCategory").
|
||||
Preload("Flags").
|
||||
Preload("Suppliers", func(db *gorm.DB) *gorm.DB {
|
||||
return db.Order("suppliers.name ASC")
|
||||
})
|
||||
}
|
||||
|
||||
func (s productService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Product, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
products, 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 products: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return products, total, nil
|
||||
}
|
||||
|
||||
func (s productService) GetOne(c *fiber.Ctx, id uint) (*entity.Product, error) {
|
||||
product, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Product not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get product by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return product, nil
|
||||
}
|
||||
|
||||
func (s *productService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Product, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
name := strings.TrimSpace(req.Name)
|
||||
brand := strings.TrimSpace(req.Brand)
|
||||
var sku *string
|
||||
if req.Sku != nil {
|
||||
trimmed := strings.ToUpper(strings.TrimSpace(*req.Sku))
|
||||
if trimmed != "" {
|
||||
sku = &trimmed
|
||||
}
|
||||
}
|
||||
|
||||
if exists, err := s.Repository.NameExists(ctx, name, nil); err != nil {
|
||||
s.Log.Errorf("Failed to check product name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product with name %s already exists", name))
|
||||
}
|
||||
|
||||
if sku != nil {
|
||||
if exists, err := s.Repository.SkuExists(ctx, *sku, nil); err != nil {
|
||||
s.Log.Errorf("Failed to check product sku: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product sku")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product with sku %s already exists", *sku))
|
||||
}
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(ctx,
|
||||
common.RelationCheck{Name: "Uom", ID: &req.UomID, Exists: s.Repository.UomExists},
|
||||
common.RelationCheck{Name: "Product category", ID: &req.ProductCategoryID, Exists: s.Repository.CategoryExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
supplierIDs := utils.UniqueUintSlice(req.SupplierIDs)
|
||||
var err error
|
||||
if len(supplierIDs) > 0 {
|
||||
suppliers, err := s.Repository.GetSuppliersByIDs(ctx, supplierIDs)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to validate suppliers: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate suppliers")
|
||||
}
|
||||
if len(suppliers) != len(supplierIDs) {
|
||||
actual := make([]uint, len(suppliers))
|
||||
for i, supplier := range suppliers {
|
||||
actual[i] = supplier.Id
|
||||
}
|
||||
missing := utils.MissingUintIDs(supplierIDs, actual)
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Suppliers with ids %v not found", missing))
|
||||
}
|
||||
for _, sup := range suppliers {
|
||||
if strings.ToUpper(sup.Category) != string(utils.SupplierCategorySapronak) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Supplier with id %d is not category SAPRONAK", sup.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
productFlags, flagErr := normalizeProductFlags(req.Flags)
|
||||
if flagErr != nil {
|
||||
return nil, flagErr
|
||||
}
|
||||
|
||||
createBody := &entity.Product{
|
||||
Name: name,
|
||||
Brand: brand,
|
||||
Sku: sku,
|
||||
UomId: req.UomID,
|
||||
ProductCategoryId: req.ProductCategoryID,
|
||||
ProductPrice: req.ProductPrice,
|
||||
SellingPrice: req.SellingPrice,
|
||||
Tax: req.Tax,
|
||||
ExpiryPeriod: req.ExpiryPeriod,
|
||||
CreatedBy: 1,
|
||||
}
|
||||
|
||||
err = s.Repository.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if err := repoTx.CreateOne(ctx, createBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.Repository.SyncFlags(ctx, tx, createBody.Id, productFlags); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.Repository.SyncSuppliersDiff(ctx, tx, createBody.Id, supplierIDs)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to create product: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s productService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Product, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updateBody := make(map[string]any)
|
||||
|
||||
if req.Name != nil {
|
||||
name := strings.TrimSpace(*req.Name)
|
||||
if name == "" {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Name cannot be empty")
|
||||
}
|
||||
if exists, err := s.Repository.NameExists(c.Context(), name, &id); err != nil {
|
||||
s.Log.Errorf("Failed to check product name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product with name %s already exists", name))
|
||||
}
|
||||
updateBody["name"] = name
|
||||
}
|
||||
|
||||
if req.Brand != nil {
|
||||
brand := strings.TrimSpace(*req.Brand)
|
||||
if brand == "" {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Brand cannot be empty")
|
||||
}
|
||||
updateBody["brand"] = brand
|
||||
}
|
||||
|
||||
if req.Sku != nil {
|
||||
sku := strings.ToUpper(strings.TrimSpace(*req.Sku))
|
||||
if sku == "" {
|
||||
updateBody["sku"] = nil
|
||||
} else {
|
||||
if exists, err := s.Repository.SkuExists(c.Context(), sku, &id); err != nil {
|
||||
s.Log.Errorf("Failed to check product sku: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check product sku")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Product with sku %s already exists", sku))
|
||||
}
|
||||
updateBody["sku"] = sku
|
||||
}
|
||||
}
|
||||
|
||||
if err := common.EnsureRelations(c.Context(),
|
||||
common.RelationCheck{Name: "Uom", ID: req.UomID, Exists: s.Repository.UomExists},
|
||||
common.RelationCheck{Name: "Product category", ID: req.ProductCategoryID, Exists: s.Repository.CategoryExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if req.UomID != nil {
|
||||
updateBody["uom_id"] = *req.UomID
|
||||
}
|
||||
|
||||
if req.ProductCategoryID != nil {
|
||||
updateBody["product_category_id"] = *req.ProductCategoryID
|
||||
}
|
||||
|
||||
if req.ProductPrice != nil {
|
||||
updateBody["product_price"] = *req.ProductPrice
|
||||
}
|
||||
if req.SellingPrice != nil {
|
||||
updateBody["selling_price"] = req.SellingPrice
|
||||
}
|
||||
if req.Tax != nil {
|
||||
updateBody["tax"] = req.Tax
|
||||
}
|
||||
if req.ExpiryPeriod != nil {
|
||||
updateBody["expiry_period"] = req.ExpiryPeriod
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
|
||||
var suppliers []entity.Supplier
|
||||
var supplierIDs []uint
|
||||
var supplierUpdate bool
|
||||
if req.SupplierIDs != nil {
|
||||
supplierUpdate = true
|
||||
supplierIDs = utils.UniqueUintSlice(*req.SupplierIDs)
|
||||
if len(supplierIDs) > 0 {
|
||||
var err error
|
||||
suppliers, err = s.Repository.GetSuppliersByIDs(ctx, supplierIDs)
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to validate suppliers: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate suppliers")
|
||||
}
|
||||
if len(suppliers) != len(supplierIDs) {
|
||||
actual := make([]uint, len(suppliers))
|
||||
for i, supplier := range suppliers {
|
||||
actual[i] = supplier.Id
|
||||
}
|
||||
missing := utils.MissingUintIDs(supplierIDs, actual)
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Suppliers with ids %v not found", missing))
|
||||
}
|
||||
for _, sup := range suppliers {
|
||||
if strings.ToUpper(sup.Category) != string(utils.SupplierCategorySapronak) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Supplier with id %d is not category SAPRONAK", sup.Id))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
flagUpdate bool
|
||||
flagValues []string
|
||||
)
|
||||
if req.Flags != nil {
|
||||
flagUpdate = true
|
||||
var flagErr error
|
||||
flagValues, flagErr = normalizeProductFlags(*req.Flags)
|
||||
if flagErr != nil {
|
||||
return nil, flagErr
|
||||
}
|
||||
}
|
||||
|
||||
if len(updateBody) == 0 && !supplierUpdate && !flagUpdate {
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
err := s.Repository.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if len(updateBody) > 0 {
|
||||
if err := repoTx.PatchOne(ctx, id, updateBody, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := repoTx.GetByID(ctx, id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if supplierUpdate {
|
||||
var ids []uint
|
||||
if len(supplierIDs) > 0 {
|
||||
ids = supplierIDs
|
||||
}
|
||||
if err := s.Repository.SyncSuppliersDiff(ctx, tx, id, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if flagUpdate {
|
||||
if err := s.Repository.SyncFlags(ctx, tx, id, flagValues); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Product not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update product: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s productService) DeleteOne(c *fiber.Ctx, id uint) error {
|
||||
err := s.Repository.DB().WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
repoTx := s.Repository.WithTx(tx)
|
||||
|
||||
if err := s.Repository.SyncSuppliersDiff(c.Context(), tx, id, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.Repository.DeleteFlags(c.Context(), tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return repoTx.DeleteOne(c.Context(), id)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "Product not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete product: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
Brand string `json:"brand" validate:"required_strict,min=2"`
|
||||
Sku *string `json:"sku,omitempty" validate:"omitempty"`
|
||||
UomID uint `json:"uom_id" validate:"required,gt=0"`
|
||||
ProductCategoryID uint `json:"product_category_id" validate:"required,gt=0"`
|
||||
ProductPrice float64 `json:"product_price" validate:"required"`
|
||||
SellingPrice *float64 `json:"selling_price,omitempty" validate:"omitempty"`
|
||||
Tax *float64 `json:"tax,omitempty" validate:"omitempty"`
|
||||
ExpiryPeriod *int `json:"expiry_period,omitempty" validate:"omitempty,gt=0"`
|
||||
SupplierIDs []uint `json:"supplier_ids,omitempty" validate:"omitempty,dive,gt=0"`
|
||||
Flags []string `json:"flags,omitempty" validate:"omitempty,dive"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,min=3"`
|
||||
Brand *string `json:"brand,omitempty" validate:"omitempty,min=2"`
|
||||
Sku *string `json:"sku,omitempty" validate:"omitempty"`
|
||||
UomID *uint `json:"uom_id,omitempty" validate:"omitempty,gt=0"`
|
||||
ProductCategoryID *uint `json:"product_category_id,omitempty" validate:"omitempty,gt=0"`
|
||||
ProductPrice *float64 `json:"product_price,omitempty" validate:"omitempty"`
|
||||
SellingPrice *float64 `json:"selling_price,omitempty" validate:"omitempty"`
|
||||
Tax *float64 `json:"tax,omitempty" validate:"omitempty"`
|
||||
ExpiryPeriod *int `json:"expiry_period,omitempty" validate:"omitempty,gt=0"`
|
||||
SupplierIDs *[]uint `json:"supplier_ids,omitempty" validate:"omitempty,dive,gt=0"`
|
||||
Flags *[]string `json:"flags,omitempty" validate:"omitempty,dive"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
Page int `query:"page" validate:"omitempty,number,min=1"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1"`
|
||||
Search string `query:"search" validate:"omitempty,max=50"`
|
||||
}
|
||||
@@ -9,10 +9,16 @@ import (
|
||||
|
||||
areas "gitlab.com/mbugroup/lti-api.git/internal/modules/master/areas"
|
||||
customers "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers"
|
||||
fcrs "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs"
|
||||
kandangs "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs"
|
||||
locations "gitlab.com/mbugroup/lti-api.git/internal/modules/master/locations"
|
||||
nonstocks "gitlab.com/mbugroup/lti-api.git/internal/modules/master/nonstocks"
|
||||
productcategories "gitlab.com/mbugroup/lti-api.git/internal/modules/master/product-categories"
|
||||
suppliers "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers"
|
||||
uoms "gitlab.com/mbugroup/lti-api.git/internal/modules/master/uoms"
|
||||
warehouses "gitlab.com/mbugroup/lti-api.git/internal/modules/master/warehouses"
|
||||
products "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products"
|
||||
banks "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks"
|
||||
// MODULE IMPORTS
|
||||
)
|
||||
|
||||
@@ -26,6 +32,12 @@ func RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Valida
|
||||
kandangs.KandangModule{},
|
||||
warehouses.WarehouseModule{},
|
||||
customers.CustomerModule{},
|
||||
suppliers.SupplierModule{},
|
||||
fcrs.FcrModule{},
|
||||
nonstocks.NonstockModule{},
|
||||
productcategories.ProductCategoryModule{},
|
||||
products.ProductModule{},
|
||||
banks.BankModule{},
|
||||
// MODULE REGISTRY
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type SupplierController struct {
|
||||
SupplierService service.SupplierService
|
||||
}
|
||||
|
||||
func NewSupplierController(supplierService service.SupplierService) *SupplierController {
|
||||
return &SupplierController{
|
||||
SupplierService: supplierService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *SupplierController) 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.SupplierService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.SupplierListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all suppliers successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToSupplierListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *SupplierController) 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.SupplierService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get supplier successfully",
|
||||
Data: dto.ToSupplierListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *SupplierController) 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.SupplierService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create supplier successfully",
|
||||
Data: dto.ToSupplierListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *SupplierController) 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.SupplierService.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 supplier successfully",
|
||||
Data: dto.ToSupplierListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *SupplierController) 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.SupplierService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete supplier successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
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 SupplierBaseDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Alias string `json:"alias"`
|
||||
Category string `json:"category"`
|
||||
}
|
||||
|
||||
type SupplierListDTO struct {
|
||||
SupplierBaseDTO
|
||||
Pic string `json:"pic"`
|
||||
Type string `json:"type"`
|
||||
Hatchery *string `json:"hatchery,omitempty"`
|
||||
Phone string `json:"phone"`
|
||||
Email string `json:"email"`
|
||||
Address string `json:"address"`
|
||||
Npwp *string `json:"npwp,omitempty"`
|
||||
AccountNumber *string `json:"account_number,omitempty"`
|
||||
Balance float64 `json:"balance"`
|
||||
DueDate int `json:"due_date"`
|
||||
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type SupplierDetailDTO struct {
|
||||
SupplierListDTO
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToSupplierBaseDTO(e entity.Supplier) SupplierBaseDTO {
|
||||
return SupplierBaseDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
Alias: e.Alias,
|
||||
Category: e.Category,
|
||||
}
|
||||
}
|
||||
|
||||
func ToSupplierListDTO(e entity.Supplier) SupplierListDTO {
|
||||
var createdUser *userDTO.UserBaseDTO
|
||||
if e.CreatedUser.Id != 0 {
|
||||
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
|
||||
createdUser = &mapped
|
||||
}
|
||||
|
||||
return SupplierListDTO{
|
||||
Pic: e.Pic,
|
||||
Type: e.Type,
|
||||
Hatchery: e.Hatchery,
|
||||
Phone: e.Phone,
|
||||
Email: e.Email,
|
||||
Address: e.Address,
|
||||
Npwp: e.Npwp,
|
||||
AccountNumber: e.AccountNumber,
|
||||
Balance: e.Balance,
|
||||
DueDate: e.DueDate,
|
||||
SupplierBaseDTO: ToSupplierBaseDTO(e),
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
CreatedUser: createdUser,
|
||||
}
|
||||
}
|
||||
|
||||
func ToSupplierListDTOs(e []entity.Supplier) []SupplierListDTO {
|
||||
result := make([]SupplierListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToSupplierListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToSupplierDetailDTO(e entity.Supplier) SupplierDetailDTO {
|
||||
return SupplierDetailDTO{
|
||||
SupplierListDTO: ToSupplierListDTO(e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package suppliers
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rSupplier "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/repositories"
|
||||
sSupplier "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type SupplierModule struct{}
|
||||
|
||||
func (SupplierModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
supplierRepo := rSupplier.NewSupplierRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
supplierService := sSupplier.NewSupplierService(supplierRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
SupplierRoutes(router, userService, supplierService)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
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 SupplierRepository interface {
|
||||
repository.BaseRepository[entity.Supplier]
|
||||
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
|
||||
}
|
||||
|
||||
type SupplierRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Supplier]
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewSupplierRepository(db *gorm.DB) SupplierRepository {
|
||||
return &SupplierRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Supplier](db),
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *SupplierRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
|
||||
return repository.ExistsByName[entity.Supplier](ctx, r.db, name, excludeID)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package suppliers
|
||||
|
||||
import (
|
||||
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/controllers"
|
||||
supplier "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func SupplierRoutes(v1 fiber.Router, u user.UserService, s supplier.SupplierService) {
|
||||
ctrl := controller.NewSupplierController(s)
|
||||
|
||||
route := v1.Group("/suppliers")
|
||||
|
||||
// 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,221 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/suppliers/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 SupplierService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Supplier, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.Supplier, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Supplier, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Supplier, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
}
|
||||
|
||||
type supplierService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.SupplierRepository
|
||||
}
|
||||
|
||||
func NewSupplierService(repo repository.SupplierRepository, validate *validator.Validate) SupplierService {
|
||||
return &supplierService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s supplierService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("CreatedUser")
|
||||
}
|
||||
|
||||
func (s supplierService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Supplier, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
suppliers, 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 suppliers: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return suppliers, total, nil
|
||||
}
|
||||
|
||||
func (s supplierService) GetOne(c *fiber.Ctx, id uint) (*entity.Supplier, error) {
|
||||
supplier, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Supplier not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get supplier by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return supplier, nil
|
||||
}
|
||||
|
||||
func (s *supplierService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Supplier, 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 supplier name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check supplier name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Supplier with name %s already exists", req.Name))
|
||||
}
|
||||
|
||||
typ := strings.ToUpper(req.Type)
|
||||
if !utils.IsValidCustomerSupplierType(typ) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid supplier type")
|
||||
}
|
||||
|
||||
category := strings.ToUpper(req.Category)
|
||||
if !utils.IsValidSupplierCategory(category) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid supplier category")
|
||||
}
|
||||
|
||||
alias := strings.TrimSpace(strings.ToUpper(req.Alias))
|
||||
|
||||
//TODO: created by dummy
|
||||
createBody := &entity.Supplier{
|
||||
Name: req.Name,
|
||||
Alias: alias,
|
||||
Pic: req.Pic,
|
||||
Type: typ,
|
||||
Category: category,
|
||||
Hatchery: req.Hatchery,
|
||||
Phone: req.Phone,
|
||||
Email: req.Email,
|
||||
Address: req.Address,
|
||||
Npwp: req.Npwp,
|
||||
AccountNumber: req.AccountNumber,
|
||||
DueDate: req.DueDate,
|
||||
CreatedBy: 1,
|
||||
}
|
||||
|
||||
if err := s.Repository.CreateOne(c.Context(), createBody, nil); err != nil {
|
||||
s.Log.Errorf("Failed to create supplier: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s supplierService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Supplier, 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 supplier name: %+v", err)
|
||||
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check supplier name")
|
||||
} else if exists {
|
||||
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Supplier with name %s already exists", *req.Name))
|
||||
}
|
||||
updateBody["name"] = *req.Name
|
||||
}
|
||||
|
||||
if req.Alias != nil {
|
||||
updateBody["alias"] = strings.TrimSpace(strings.ToUpper(*req.Alias))
|
||||
}
|
||||
|
||||
if req.Pic != nil {
|
||||
updateBody["pic"] = *req.Pic
|
||||
}
|
||||
|
||||
if req.Type != nil {
|
||||
typ := strings.ToUpper(*req.Type)
|
||||
if !utils.IsValidCustomerSupplierType(typ) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid supplier type")
|
||||
}
|
||||
updateBody["type"] = typ
|
||||
}
|
||||
|
||||
if req.Category != nil {
|
||||
category := strings.ToUpper(*req.Category)
|
||||
if !utils.IsValidSupplierCategory(category) {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid supplier category")
|
||||
}
|
||||
updateBody["category"] = category
|
||||
}
|
||||
|
||||
if req.Hatchery != nil {
|
||||
updateBody["hatchery"] = *req.Hatchery
|
||||
}
|
||||
|
||||
if req.Phone != nil {
|
||||
updateBody["phone"] = *req.Phone
|
||||
}
|
||||
|
||||
if req.Email != nil {
|
||||
updateBody["email"] = *req.Email
|
||||
}
|
||||
|
||||
if req.Address != nil {
|
||||
updateBody["address"] = *req.Address
|
||||
}
|
||||
|
||||
if req.Npwp != nil {
|
||||
updateBody["npwp"] = *req.Npwp
|
||||
}
|
||||
|
||||
if req.AccountNumber != nil {
|
||||
updateBody["account_number"] = *req.AccountNumber
|
||||
}
|
||||
|
||||
if req.DueDate != nil {
|
||||
updateBody["due_date"] = *req.DueDate
|
||||
}
|
||||
|
||||
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, "Supplier not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update supplier: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s supplierService) 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, "Supplier not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete supplier: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
Alias string `json:"alias" validate:"required_strict,max=5"`
|
||||
Pic string `json:"pic" validate:"required_strict"`
|
||||
Type string `json:"type" validate:"required_strict"`
|
||||
Category string `json:"category" validate:"required_strict"`
|
||||
Hatchery *string `json:"hatchery,omitempty" validate:"omitempty"`
|
||||
Phone string `json:"phone" validate:"required_strict,max=20"`
|
||||
Email string `json:"email" validate:"required_strict,email"`
|
||||
Address string `json:"address" validate:"required_strict"`
|
||||
Npwp *string `json:"npwp,omitempty" validate:"omitempty,max=50"`
|
||||
AccountNumber *string `json:"account_number,omitempty" validate:"omitempty,max=50"`
|
||||
DueDate int `json:"due_date" validate:"required_strict,number,gt=0"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,min=3"`
|
||||
Alias *string `json:"alias,omitempty" validate:"omitempty,max=5"`
|
||||
Pic *string `json:"pic,omitempty" validate:"omitempty"`
|
||||
Type *string `json:"type,omitempty" validate:"omitempty"`
|
||||
Category *string `json:"category,omitempty" validate:"omitempty"`
|
||||
Hatchery *string `json:"hatchery,omitempty" validate:"omitempty"`
|
||||
Phone *string `json:"phone,omitempty" validate:"omitempty,max=20"`
|
||||
Email *string `json:"email,omitempty" validate:"omitempty,email"`
|
||||
Address *string `json:"address,omitempty" validate:"omitempty"`
|
||||
Npwp *string `json:"npwp,omitempty" validate:"omitempty,max=50"`
|
||||
AccountNumber *string `json:"account_number,omitempty" validate:"omitempty,max=50"`
|
||||
DueDate *int `json:"due_date,omitempty" validate:"omitempty,number,gt=0"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
@@ -56,3 +56,9 @@ func ToUomListDTOs(e []entity.Uom) []UomListDTO {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToUomDetailDTO(e entity.Uom) UomDetailDTO {
|
||||
return UomDetailDTO{
|
||||
UomListDTO: ToUomListDTO(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ func (s *uomService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Uo
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.Repository.GetByID(c.Context(), createBody.Id, s.withRelations)
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s uomService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Uom, error) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
|
||||
@@ -85,3 +85,9 @@ func ToWarehouseListDTOs(e []entity.Warehouse) []WarehouseListDTO {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToWarehouseDetailDTO(e entity.Warehouse) WarehouseDetailDTO {
|
||||
return WarehouseDetailDTO{
|
||||
WarehouseListDTO: ToWarehouseListDTO(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ func (s *warehouseService) CreateOne(c *fiber.Ctx, req *validation.Create) (*ent
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.Repository.GetByID(c.Context(), createBody.Id, s.withRelations)
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s warehouseService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Warehouse, error) {
|
||||
@@ -152,22 +152,20 @@ func (s warehouseService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uin
|
||||
updateBody["type"] = normalizedType
|
||||
req.Type = &normalizedType
|
||||
}
|
||||
if err := common.EnsureRelations(c.Context(),
|
||||
common.RelationCheck{Name: "Area", ID: req.AreaId, Exists: s.Repository.AreaExists},
|
||||
common.RelationCheck{Name: "Location", ID: req.LocationId, Exists: s.Repository.LocationExists},
|
||||
common.RelationCheck{Name: "Kandang", ID: req.KandangId, Exists: s.Repository.KandangExists},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.AreaId != nil {
|
||||
if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Area", ID: req.AreaId, Exists: s.Repository.AreaExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updateBody["area_id"] = *req.AreaId
|
||||
}
|
||||
if req.LocationId != nil {
|
||||
if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Location", ID: req.LocationId, Exists: s.Repository.LocationExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updateBody["location_id"] = req.LocationId
|
||||
}
|
||||
if req.KandangId != nil {
|
||||
if err := common.EnsureRelations(c.Context(), common.RelationCheck{Name: "Kandang", ID: req.KandangId, Exists: s.Repository.KandangExists}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
updateBody["kandang_id"] = req.KandangId
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ type Create struct {
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
Type *string `json:"type,omitempty" validate:"omitempty"`
|
||||
AreaId *uint `json:"area_id,omitempty" validate:"omitempty,number,gt=0"`
|
||||
LocationId *uint `json:"location_id,omitempty" validate:"omitempty,number,gt=0"`
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty,max=50"`
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
|
||||
Reference in New Issue
Block a user