feat/BE/US-74/pengajuan-flock

This commit is contained in:
ragilap
2025-10-16 10:06:18 +07:00
parent 7392d8a679
commit 6c7ab8a0f8
37 changed files with 2038 additions and 99 deletions
@@ -0,0 +1,140 @@
package controller
import (
"math"
"strconv"
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/services"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/validations"
"gitlab.com/mbugroup/lti-api.git/internal/response"
"github.com/gofiber/fiber/v2"
)
type FlockController struct {
FlockService service.FlockService
}
func NewFlockController(flockService service.FlockService) *FlockController {
return &FlockController{
FlockService: flockService,
}
}
func (u *FlockController) 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.FlockService.GetAll(c, query)
if err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.SuccessWithPaginate[dto.FlockListDTO]{
Code: fiber.StatusOK,
Status: "success",
Message: "Get all flocks successfully",
Meta: response.Meta{
Page: query.Page,
Limit: query.Limit,
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
TotalResults: totalResults,
},
Data: dto.ToFlockListDTOs(result),
})
}
func (u *FlockController) 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.FlockService.GetOne(c, uint(id))
if err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.Success{
Code: fiber.StatusOK,
Status: "success",
Message: "Get flock successfully",
Data: dto.ToFlockListDTO(*result),
})
}
func (u *FlockController) 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.FlockService.CreateOne(c, req)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).
JSON(response.Success{
Code: fiber.StatusCreated,
Status: "success",
Message: "Create flock successfully",
Data: dto.ToFlockListDTO(*result),
})
}
func (u *FlockController) 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.FlockService.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 flock successfully",
Data: dto.ToFlockListDTO(*result),
})
}
func (u *FlockController) 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.FlockService.DeleteOne(c, uint(id)); err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.Common{
Code: fiber.StatusOK,
Status: "success",
Message: "Delete flock successfully",
})
}
@@ -0,0 +1,64 @@
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 FlockBaseDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
}
type FlockListDTO struct {
FlockBaseDTO
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type FlockDetailDTO struct {
FlockListDTO
}
// === Mapper Functions ===
func ToFlockBaseDTO(e entity.Flock) FlockBaseDTO {
return FlockBaseDTO{
Id: e.Id,
Name: e.Name,
}
}
func ToFlockListDTO(e entity.Flock) FlockListDTO {
var createdUser *userDTO.UserBaseDTO
if e.CreatedUser.Id != 0 {
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
createdUser = &mapped
}
return FlockListDTO{
FlockBaseDTO: ToFlockBaseDTO(e),
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
CreatedUser: createdUser,
}
}
func ToFlockListDTOs(e []entity.Flock) []FlockListDTO {
result := make([]FlockListDTO, len(e))
for i, r := range e {
result[i] = ToFlockListDTO(r)
}
return result
}
func ToFlockDetailDTO(e entity.Flock) FlockDetailDTO {
return FlockDetailDTO{
FlockListDTO: ToFlockListDTO(e),
}
}
+25
View File
@@ -0,0 +1,25 @@
package flocks
import (
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
rFlock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/repositories"
sFlock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/services"
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
)
type FlockModule struct{}
func (FlockModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
flockRepo := rFlock.NewFlockRepository(db)
userRepo := rUser.NewUserRepository(db)
flockService := sFlock.NewFlockService(flockRepo, validate)
userService := sUser.NewUserService(userRepo, validate)
FlockRoutes(router, userService, flockService)
}
@@ -0,0 +1,21 @@
package repository
import (
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
"gorm.io/gorm"
)
type FlockRepository interface {
repository.BaseRepository[entity.Flock]
}
type FlockRepositoryImpl struct {
*repository.BaseRepositoryImpl[entity.Flock]
}
func NewFlockRepository(db *gorm.DB) FlockRepository {
return &FlockRepositoryImpl{
BaseRepositoryImpl: repository.NewBaseRepository[entity.Flock](db),
}
}
+28
View File
@@ -0,0 +1,28 @@
package flocks
import (
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/controllers"
flock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/services"
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
"github.com/gofiber/fiber/v2"
)
func FlockRoutes(v1 fiber.Router, u user.UserService, s flock.FlockService) {
ctrl := controller.NewFlockController(s)
route := v1.Group("/flocks")
// 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,130 @@
package service
import (
"errors"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/repositories"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/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 FlockService interface {
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Flock, int64, error)
GetOne(ctx *fiber.Ctx, id uint) (*entity.Flock, error)
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Flock, error)
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Flock, error)
DeleteOne(ctx *fiber.Ctx, id uint) error
}
type flockService struct {
Log *logrus.Logger
Validate *validator.Validate
Repository repository.FlockRepository
}
func NewFlockService(repo repository.FlockRepository, validate *validator.Validate) FlockService {
return &flockService{
Log: utils.Log,
Validate: validate,
Repository: repo,
}
}
func (s flockService) withRelations(db *gorm.DB) *gorm.DB {
return db.Preload("CreatedUser")
}
func (s flockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Flock, int64, error) {
if err := s.Validate.Struct(params); err != nil {
return nil, 0, err
}
offset := (params.Page - 1) * params.Limit
flocks, 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 flocks: %+v", err)
return nil, 0, err
}
return flocks, total, nil
}
func (s flockService) GetOne(c *fiber.Ctx, id uint) (*entity.Flock, error) {
flock, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Flock not found")
}
if err != nil {
s.Log.Errorf("Failed get flock by id: %+v", err)
return nil, err
}
return flock, nil
}
func (s *flockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Flock, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
createBody := &entity.Flock{
Name: req.Name,
CreatedBy: 1,
}
if err := s.Repository.CreateOne(c.Context(), createBody, nil); err != nil {
s.Log.Errorf("Failed to create flock: %+v", err)
return nil, err
}
return s.GetOne(c, createBody.Id)
}
func (s flockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Flock, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
updateBody := make(map[string]any)
if req.Name != nil {
updateBody["name"] = *req.Name
}
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, "Flock not found")
}
s.Log.Errorf("Failed to update flock: %+v", err)
return nil, err
}
return s.GetOne(c, id)
}
func (s flockService) 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, "Flock not found")
}
s.Log.Errorf("Failed to delete flock: %+v", err)
return err
}
return nil
}
@@ -0,0 +1,15 @@
package validation
type Create struct {
Name string `json:"name" validate:"required_strict,min=3"`
}
type Update struct {
Name *string `json:"name,omitempty" validate:"omitempty"`
}
type Query struct {
Page int `query:"page" validate:"omitempty,number,min=1"`
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100"`
Search string `query:"search" validate:"omitempty,max=50"`
}