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"`
}
@@ -5,6 +5,7 @@ import (
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
"gitlab.com/mbugroup/lti-api.git/internal/utils"
"gorm.io/gorm"
)
@@ -13,6 +14,8 @@ type KandangRepository interface {
LocationExists(ctx context.Context, areaId uint) (bool, error)
PicExists(ctx context.Context, areaId uint) (bool, error)
NameExists(ctx context.Context, name string, excludeID *uint) (bool, error)
ProjectFlockExists(ctx context.Context, projectFlockID uint) (bool, error)
HasActiveKandangForProjectFlock(ctx context.Context, projectFlockID uint, excludeID *uint) (bool, error)
}
type KandangRepositoryImpl struct {
@@ -38,3 +41,31 @@ func (r *KandangRepositoryImpl) PicExists(ctx context.Context, picId uint) (bool
func (r *KandangRepositoryImpl) NameExists(ctx context.Context, name string, excludeID *uint) (bool, error) {
return repository.ExistsByName[entity.Kandang](ctx, r.db, name, excludeID)
}
func (r *KandangRepositoryImpl) ProjectFlockExists(ctx context.Context, projectFlockID uint) (bool, error) {
var count int64
if err := r.db.WithContext(ctx).
Model(&entity.ProjectFlock{}).
Where("id = ?", projectFlockID).
Where("deleted_at IS NULL").
Count(&count).Error; err != nil {
return false, err
}
return count > 0, nil
}
func (r *KandangRepositoryImpl) HasActiveKandangForProjectFlock(ctx context.Context, projectFlockID uint, excludeID *uint) (bool, error) {
var count int64
q := r.db.WithContext(ctx).
Model(&entity.Kandang{}).
Where("project_flock_id = ?", projectFlockID).
Where("status = ?", utils.KandangStatusActive).
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
}
@@ -3,6 +3,7 @@ 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"
@@ -100,13 +101,41 @@ func (s *kandangService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entit
); err != nil {
return nil, err
}
status := strings.ToUpper(req.Status)
if !utils.IsValidKandangStatus(status) {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid kandang status")
}
var projectFlockID *uint
if req.ProjectFlockId != nil {
if exists, err := s.Repository.ProjectFlockExists(c.Context(), *req.ProjectFlockId); err != nil {
s.Log.Errorf("Failed to check project flock existence: %+v", err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check project flock")
} else if !exists {
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Project flock with id %d not found", *req.ProjectFlockId))
}
if status == string(utils.KandangStatusActive) {
if active, err := s.Repository.HasActiveKandangForProjectFlock(c.Context(), *req.ProjectFlockId, nil); err != nil {
s.Log.Errorf("Failed to check kandang activity for project flock %d: %+v", *req.ProjectFlockId, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check active kandang for project flock")
} else if active {
return nil, fiber.NewError(fiber.StatusConflict, "Project flock already has an active kandang")
}
}
idCopy := *req.ProjectFlockId
projectFlockID = &idCopy
}
//TODO: created by dummy
createBody := &entity.Kandang{
Name: req.Name,
LocationId: req.LocationId,
PicId: req.PicId,
CreatedBy: 1,
Name: req.Name,
LocationId: req.LocationId,
Status: status,
PicId: req.PicId,
ProjectFlockId: projectFlockID,
CreatedBy: 1,
}
if err := s.Repository.CreateOne(c.Context(), createBody, nil); err != nil {
@@ -122,6 +151,15 @@ func (s kandangService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint)
return nil, err
}
existing, err := s.Repository.GetByID(c.Context(), id, nil)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Kandang not found")
}
if err != nil {
s.Log.Errorf("Failed to fetch kandang %d before update: %+v", id, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch kandang")
}
updateBody := make(map[string]any)
if req.Name != nil {
@@ -149,6 +187,38 @@ func (s kandangService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint)
updateBody["pic_id"] = *req.PicId
}
finalStatus := strings.ToUpper(existing.Status)
if req.Status != nil {
status := strings.ToUpper(*req.Status)
if !utils.IsValidKandangStatus(status) {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid kandang status")
}
updateBody["status"] = status
finalStatus = status
}
projectFlockIDToUse := existing.ProjectFlockId
if req.ProjectFlockId != nil {
if exists, err := s.Repository.ProjectFlockExists(c.Context(), *req.ProjectFlockId); err != nil {
s.Log.Errorf("Failed to check project flock existence: %+v", err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check project flock")
} else if !exists {
return nil, fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("Project flock with id %d not found", *req.ProjectFlockId))
}
idCopy := *req.ProjectFlockId
projectFlockIDToUse = &idCopy
updateBody["project_flock_id"] = idCopy
}
if projectFlockIDToUse != nil && finalStatus == string(utils.KandangStatusActive) {
if active, err := s.Repository.HasActiveKandangForProjectFlock(c.Context(), *projectFlockIDToUse, &id); err != nil {
s.Log.Errorf("Failed to check kandang activity for project flock %d: %+v", *projectFlockIDToUse, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to check active kandang for project flock")
} else if active {
return nil, fiber.NewError(fiber.StatusConflict, "Project flock already has an active kandang")
}
}
if len(updateBody) == 0 {
return s.GetOne(c, id)
}
@@ -1,15 +1,19 @@
package validation
type Create struct {
Name string `json:"name" validate:"required_strict,min=3"`
LocationId uint `json:"location_id" validate:"required_strict,number,gt=0"`
PicId uint `json:"pic_id" validate:"required_strict,number,gt=0"`
Name string `json:"name" validate:"required_strict,min=3"`
Status string `json:"status" validate:"required_strict,min=3"`
LocationId uint `json:"location_id" validate:"required_strict,number,gt=0"`
PicId uint `json:"pic_id" validate:"required_strict,number,gt=0"`
ProjectFlockId *uint `json:"project_flock_id" validate:"omitempty,number,gt=0"`
}
type Update struct {
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"`
Name *string `json:"name,omitempty" validate:"omitempty"`
Status *string `json:"status,omitempty" validate:"omitempty,min=3"`
LocationId *uint `json:"location_id,omitempty" validate:"omitempty,number,gt=0"`
PicId *uint `json:"pic_id,omitempty" validate:"omitempty,number,gt=0"`
ProjectFlockId *uint `json:"project_flock_id,omitempty" validate:"omitempty,number,gt=0"`
}
type Query struct {
+2
View File
@@ -19,6 +19,7 @@ import (
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"
flocks "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks"
// MODULE IMPORTS
)
@@ -38,6 +39,7 @@ func RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Valida
productcategories.ProductCategoryModule{},
products.ProductModule{},
banks.BankModule{},
flocks.FlockModule{},
// MODULE REGISTRY
}
+13
View File
@@ -0,0 +1,13 @@
package production
import (
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
type ProductionModule struct{}
func (ProductionModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
RegisterRoutes(router, db, validate)
}
@@ -0,0 +1,164 @@
package controller
import (
"math"
"strconv"
"gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/dto"
service "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/services"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/validations"
"gitlab.com/mbugroup/lti-api.git/internal/response"
"github.com/gofiber/fiber/v2"
)
type ProjectflockController struct {
ProjectflockService service.ProjectflockService
}
func NewProjectflockController(projectflockService service.ProjectflockService) *ProjectflockController {
return &ProjectflockController{
ProjectflockService: projectflockService,
}
}
func (u *ProjectflockController) 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.ProjectflockService.GetAll(c, query)
if err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.SuccessWithPaginate[dto.ProjectFlockListDTO]{
Code: fiber.StatusOK,
Status: "success",
Message: "Get all projectflocks successfully",
Meta: response.Meta{
Page: query.Page,
Limit: query.Limit,
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
TotalResults: totalResults,
},
Data: dto.ToProjectFlockListDTOs(result),
})
}
func (u *ProjectflockController) 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.ProjectflockService.GetOne(c, uint(id))
if err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.Success{
Code: fiber.StatusOK,
Status: "success",
Message: "Get projectflock successfully",
Data: dto.ToProjectFlockListDTO(*result),
})
}
func (u *ProjectflockController) 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.ProjectflockService.CreateOne(c, req)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).
JSON(response.Success{
Code: fiber.StatusCreated,
Status: "success",
Message: "Create projectflock successfully",
Data: dto.ToProjectFlockListDTO(*result),
})
}
func (u *ProjectflockController) 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.ProjectflockService.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 projectflock successfully",
Data: dto.ToProjectFlockListDTO(*result),
})
}
func (u *ProjectflockController) 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.ProjectflockService.DeleteOne(c, uint(id)); err != nil {
return err
}
return c.Status(fiber.StatusOK).
JSON(response.Common{
Code: fiber.StatusOK,
Status: "success",
Message: "Delete projectflock successfully",
})
}
func (u *ProjectflockController) GetFlockPeriodSummary(c *fiber.Ctx) error {
param := c.Params("flock_id")
id, err := strconv.Atoi(param)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid Flock Id")
}
summary, err := u.ProjectflockService.GetFlockPeriodSummary(c, uint(id))
if err != nil {
return err
}
responseBody := dto.ToFlockPeriodSummaryDTO(summary.Flock, summary.NextPeriod)
return c.Status(fiber.StatusOK).
JSON(response.Success{
Code: fiber.StatusOK,
Status: "success",
Message: "Get flock period summary successfully",
Data: responseBody,
})
}
@@ -0,0 +1,183 @@
package dto
import (
"time"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)
type ProjectFlockBaseDTO struct {
Id uint `json:"id"`
// FlockId uint `json:"flock_id"`
// AreaId uint `json:"area_id"`
// ProductCategoryId uint `json:"product_category_id"`
// FcrId uint `json:"fcr_id"`
// LocationId uint `json:"location_id"`
Period int `json:"period"`
}
func ToProjectFlockBaseDTO(e entity.ProjectFlock) ProjectFlockBaseDTO {
return ProjectFlockBaseDTO{
Id: e.Id,
// FlockId: e.FlockId,
// AreaId: e.AreaId,
// ProductCategoryId: e.ProductCategoryId,
// FcrId: e.FcrId,
// LocationId: e.LocationId,
Period: e.Period,
}
}
type FlockSummaryDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
}
type AreaSummaryDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
}
type ProductCategorySummaryDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
Code string `json:"code"`
}
type FcrSummaryDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
}
type LocationSummaryDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
Address string `json:"address"`
}
type KandangSummaryDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
}
type ProjectFlockListDTO struct {
ProjectFlockBaseDTO
Flock *FlockSummaryDTO `json:"flock,omitempty"`
Area *AreaSummaryDTO `json:"area,omitempty"`
ProductCategory *ProductCategorySummaryDTO `json:"product_category,omitempty"`
Fcr *FcrSummaryDTO `json:"fcr,omitempty"`
Location *LocationSummaryDTO `json:"location,omitempty"`
Kandangs []KandangSummaryDTO `json:"kandangs,omitempty"`
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type ProjectFlockDetailDTO struct {
ProjectFlockListDTO
}
type FlockPeriodSummaryDTO struct {
Flock FlockSummaryDTO `json:"flock"`
NextPeriod int `json:"next_period"`
}
func ToProjectFlockListDTO(e entity.ProjectFlock) ProjectFlockListDTO {
var createdUser *userDTO.UserBaseDTO
if e.CreatedUser.Id != 0 {
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
createdUser = &mapped
}
var flockSummary *FlockSummaryDTO
if e.Flock.Id != 0 {
summary := ToFlockSummaryDTO(e.Flock)
flockSummary = &summary
}
var areaSummary *AreaSummaryDTO
if e.Area.Id != 0 {
areaSummary = &AreaSummaryDTO{
Id: e.Area.Id,
Name: e.Area.Name,
}
}
var categorySummary *ProductCategorySummaryDTO
if e.ProductCategory.Id != 0 {
categorySummary = &ProductCategorySummaryDTO{
Id: e.ProductCategory.Id,
Name: e.ProductCategory.Name,
Code: e.ProductCategory.Code,
}
}
var fcrSummary *FcrSummaryDTO
if e.Fcr.Id != 0 {
fcrSummary = &FcrSummaryDTO{
Id: e.Fcr.Id,
Name: e.Fcr.Name,
}
}
var locationSummary *LocationSummaryDTO
if e.Location.Id != 0 {
locationSummary = &LocationSummaryDTO{
Id: e.Location.Id,
Name: e.Location.Name,
Address: e.Location.Address,
}
}
kandangSummaries := make([]KandangSummaryDTO, len(e.Kandangs))
for i, kandang := range e.Kandangs {
kandangSummaries[i] = KandangSummaryDTO{
Id: kandang.Id,
Name: kandang.Name,
Status: kandang.Status,
}
}
return ProjectFlockListDTO{
ProjectFlockBaseDTO: ToProjectFlockBaseDTO(e),
Flock: flockSummary,
Area: areaSummary,
ProductCategory: categorySummary,
Fcr: fcrSummary,
Location: locationSummary,
Kandangs: kandangSummaries,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
CreatedUser: createdUser,
}
}
func ToProjectFlockListDTOs(items []entity.ProjectFlock) []ProjectFlockListDTO {
result := make([]ProjectFlockListDTO, len(items))
for i, item := range items {
result[i] = ToProjectFlockListDTO(item)
}
return result
}
func ToProjectFlockDetailDTO(e entity.ProjectFlock) ProjectFlockDetailDTO {
return ProjectFlockDetailDTO{
ProjectFlockListDTO: ToProjectFlockListDTO(e),
}
}
func ToFlockSummaryDTO(e entity.Flock) FlockSummaryDTO {
return FlockSummaryDTO{
Id: e.Id,
Name: e.Name,
}
}
func ToFlockPeriodSummaryDTO(flock entity.Flock, next int) FlockPeriodSummaryDTO {
return FlockPeriodSummaryDTO{
Flock: ToFlockSummaryDTO(flock),
NextPeriod: next,
}
}
@@ -0,0 +1,29 @@
package project_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"
rKandang "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/repositories"
rProjectflock "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/repositories"
sProjectflock "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_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 ProjectflockModule struct{}
func (ProjectflockModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
flockRepo := rFlock.NewFlockRepository(db)
kandangRepo := rKandang.NewKandangRepository(db)
projectflockRepo := rProjectflock.NewProjectflockRepository(db)
userRepo := rUser.NewUserRepository(db)
projectflockService := sProjectflock.NewProjectflockService(projectflockRepo, flockRepo, kandangRepo, validate)
userService := sUser.NewUserService(userRepo, validate)
ProjectflockRoutes(router, userService, projectflockService)
}
@@ -0,0 +1,67 @@
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 ProjectflockRepository interface {
repository.BaseRepository[entity.ProjectFlock]
GetAllByFlock(ctx context.Context, flockID uint) ([]entity.ProjectFlock, error)
GetActiveByFlock(ctx context.Context, flockID uint) (*entity.ProjectFlock, error)
GetMaxPeriodByFlock(ctx context.Context, flockID uint) (int, error)
}
type ProjectflockRepositoryImpl struct {
*repository.BaseRepositoryImpl[entity.ProjectFlock]
}
func NewProjectflockRepository(db *gorm.DB) ProjectflockRepository {
return &ProjectflockRepositoryImpl{
BaseRepositoryImpl: repository.NewBaseRepository[entity.ProjectFlock](db),
}
}
func (r *ProjectflockRepositoryImpl) GetAllByFlock(ctx context.Context, flockID uint) ([]entity.ProjectFlock, error) {
var records []entity.ProjectFlock
if err := r.DB().WithContext(ctx).
Unscoped().
Where("flock_id = ?", flockID).
Order("period ASC").
Find(&records).Error; err != nil {
return nil, err
}
return records, nil
}
func (r *ProjectflockRepositoryImpl) GetActiveByFlock(ctx context.Context, flockID uint) (*entity.ProjectFlock, error) {
var record entity.ProjectFlock
err := r.DB().WithContext(ctx).
Where("flock_id = ?", flockID).
Order("period DESC").
First(&record).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
if err != nil {
return nil, err
}
return &record, nil
}
func (r *ProjectflockRepositoryImpl) GetMaxPeriodByFlock(ctx context.Context, flockID uint) (int, error) {
var max int
if err := r.DB().WithContext(ctx).
Model(&entity.ProjectFlock{}).
Unscoped().
Where("flock_id = ?", flockID).
Select("COALESCE(MAX(period), 0)").
Scan(&max).Error; err != nil {
return 0, err
}
return max, nil
}
@@ -0,0 +1,29 @@
package project_flocks
import (
// m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/controllers"
projectflock "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/services"
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
"github.com/gofiber/fiber/v2"
)
func ProjectflockRoutes(v1 fiber.Router, u user.UserService, s projectflock.ProjectflockService) {
ctrl := controller.NewProjectflockController(s)
route := v1.Group("/project_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)
route.Get("/flocks/:flock_id/periods", ctrl.GetFlockPeriodSummary)
}
@@ -0,0 +1,372 @@
package service
import (
"errors"
"fmt"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
flockRepository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/repositories"
kandangRepository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/repositories"
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/repositories"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_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 ProjectflockService interface {
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlock, int64, error)
GetOne(ctx *fiber.Ctx, id uint) (*entity.ProjectFlock, error)
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.ProjectFlock, error)
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.ProjectFlock, error)
DeleteOne(ctx *fiber.Ctx, id uint) error
GetFlockPeriodSummary(ctx *fiber.Ctx, flockID uint) (*FlockPeriodSummary, error)
}
type projectflockService struct {
Log *logrus.Logger
Validate *validator.Validate
Repository repository.ProjectflockRepository
FlockRepo flockRepository.FlockRepository
KandangRepo kandangRepository.KandangRepository
}
type FlockPeriodSummary struct {
Flock entity.Flock
NextPeriod int
}
func NewProjectflockService(
repo repository.ProjectflockRepository,
flockRepo flockRepository.FlockRepository,
kandangRepo kandangRepository.KandangRepository,
validate *validator.Validate,
) ProjectflockService {
return &projectflockService{
Log: utils.Log,
Validate: validate,
Repository: repo,
FlockRepo: flockRepo,
KandangRepo: kandangRepo,
}
}
func (s projectflockService) withRelations(db *gorm.DB) *gorm.DB {
return db.
Preload("CreatedUser").
Preload("Flock").
Preload("Area").
Preload("ProductCategory").
Preload("Fcr").
Preload("Location").
Preload("Kandangs")
}
func (s projectflockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlock, int64, error) {
if err := s.Validate.Struct(params); err != nil {
return nil, 0, err
}
offset := (params.Page - 1) * params.Limit
projectflocks, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
db = s.withRelations(db)
return db.Order("created_at DESC").Order("updated_at DESC")
})
if err != nil {
s.Log.Errorf("Failed to get projectflocks: %+v", err)
return nil, 0, err
}
return projectflocks, total, nil
}
func (s projectflockService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectFlock, error) {
projectflock, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
}
if err != nil {
s.Log.Errorf("Failed get projectflock by id: %+v", err)
return nil, err
}
return projectflock, nil
}
func (s *projectflockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.ProjectFlock, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
if len(req.KandangIds) == 0 {
return nil, fiber.NewError(fiber.StatusBadRequest, "kandang_ids is required")
}
kandangIDs := uniqueUintSlice(req.KandangIds)
kandangs, err := s.KandangRepo.GetByIDs(c.Context(), kandangIDs, nil)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Some kandangs not found")
}
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch kandangs")
}
if len(kandangs) != len(kandangIDs) {
return nil, fiber.NewError(fiber.StatusNotFound, "Some kandangs not found")
}
for _, kandang := range kandangs {
if kandang.ProjectFlockId != nil {
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Kandang %s sudah memiliki project flock", kandang.Name))
}
}
tx := s.Repository.DB().Begin()
if tx.Error != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to start transaction")
}
projectRepo := s.Repository.WithTx(tx)
createBody := &entity.ProjectFlock{
FlockId: req.FlockId,
AreaId: req.AreaId,
ProductCategoryId: req.ProductCategoryId,
FcrId: req.FcrId,
LocationId: req.LocationId,
Period: req.Period,
CreatedBy: 1,
}
if err := projectRepo.CreateOne(c.Context(), createBody, nil); err != nil {
tx.Rollback()
s.Log.Errorf("Failed to create projectflock: %+v", err)
return nil, err
}
if err := tx.Model(&entity.Kandang{}).
Where("id IN ?", kandangIDs).
Updates(map[string]any{"project_flock_id": createBody.Id}).Error; err != nil {
tx.Rollback()
s.Log.Errorf("Failed to assign kandangs to projectflock: %+v", err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to assign kandangs")
}
if err := tx.Commit().Error; err != nil {
tx.Rollback()
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to commit transaction")
}
return s.GetOne(c, createBody.Id)
}
func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.ProjectFlock, error) {
if err := s.Validate.Struct(req); err != nil {
return nil, err
}
existing, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
}
if err != nil {
s.Log.Errorf("Failed to fetch projectflock %d before update: %+v", id, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch project flock")
}
updateBody := make(map[string]any)
if req.FlockId != nil {
updateBody["flock_id"] = *req.FlockId
}
if req.AreaId != nil {
updateBody["area_id"] = *req.AreaId
}
if req.ProductCategoryId != nil {
updateBody["product_category_id"] = *req.ProductCategoryId
}
if req.FcrId != nil {
updateBody["fcr_id"] = *req.FcrId
}
if req.LocationId != nil {
updateBody["location_id"] = *req.LocationId
}
if req.Period != nil {
updateBody["period"] = *req.Period
}
var newKandangIDs []uint
if req.KandangIds != nil {
if len(req.KandangIds) == 0 {
return nil, fiber.NewError(fiber.StatusBadRequest, "kandang_ids cannot be empty")
}
newKandangIDs = uniqueUintSlice(req.KandangIds)
kandangs, err := s.KandangRepo.GetByIDs(c.Context(), newKandangIDs, nil)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Some kandangs not found")
}
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch kandangs")
}
if len(kandangs) != len(newKandangIDs) {
return nil, fiber.NewError(fiber.StatusNotFound, "Some kandangs not found")
}
for _, k := range kandangs {
if k.ProjectFlockId != nil && *k.ProjectFlockId != id {
return nil, fiber.NewError(fiber.StatusConflict, fmt.Sprintf("Kandang %s sudah terikat dengan project flock lain", k.Name))
}
}
}
tx := s.Repository.DB().Begin()
if tx.Error != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to start transaction")
}
projectRepo := s.Repository.WithTx(tx)
if len(updateBody) > 0 {
if err := projectRepo.PatchOne(c.Context(), id, updateBody, nil); err != nil {
tx.Rollback()
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
}
s.Log.Errorf("Failed to update projectflock: %+v", err)
return nil, err
}
}
if req.KandangIds != nil {
existingIDs := make(map[uint]struct{}, len(existing.Kandangs))
for _, k := range existing.Kandangs {
existingIDs[k.Id] = struct{}{}
}
newSet := make(map[uint]struct{}, len(newKandangIDs))
for _, id := range newKandangIDs {
newSet[id] = struct{}{}
}
var toDetach []uint
for id := range existingIDs {
if _, ok := newSet[id]; !ok {
toDetach = append(toDetach, id)
}
}
var toAttach []uint
for id := range newSet {
if _, ok := existingIDs[id]; !ok {
toAttach = append(toAttach, id)
}
}
if len(toDetach) > 0 {
if err := tx.Model(&entity.Kandang{}).
Where("id IN ?", toDetach).
Updates(map[string]any{"project_flock_id": nil}).Error; err != nil {
tx.Rollback()
s.Log.Errorf("Failed to detach kandangs: %+v", err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to update kandangs")
}
}
if len(toAttach) > 0 {
if err := tx.Model(&entity.Kandang{}).
Where("id IN ?", toAttach).
Updates(map[string]any{"project_flock_id": id}).Error; err != nil {
tx.Rollback()
s.Log.Errorf("Failed to attach kandangs: %+v", err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to update kandangs")
}
}
}
if err := tx.Commit().Error; err != nil {
tx.Rollback()
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to commit transaction")
}
return s.GetOne(c, id)
}
func (s projectflockService) DeleteOne(c *fiber.Ctx, id uint) error {
existing, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
if errors.Is(err, gorm.ErrRecordNotFound) {
return fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
}
if err != nil {
s.Log.Errorf("Failed to fetch projectflock %d before delete: %+v", id, err)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch project flock")
}
tx := s.Repository.DB().Begin()
if tx.Error != nil {
return fiber.NewError(fiber.StatusInternalServerError, "Failed to start transaction")
}
if len(existing.Kandangs) > 0 {
ids := make([]uint, len(existing.Kandangs))
for i, k := range existing.Kandangs {
ids[i] = k.Id
}
if err := tx.Model(&entity.Kandang{}).
Where("id IN ?", ids).
Updates(map[string]any{"project_flock_id": nil}).Error; err != nil {
tx.Rollback()
s.Log.Errorf("Failed to detach kandangs before delete: %+v", err)
return fiber.NewError(fiber.StatusInternalServerError, "Failed to update kandangs")
}
}
if err := s.Repository.WithTx(tx).DeleteOne(c.Context(), id); err != nil {
tx.Rollback()
if errors.Is(err, gorm.ErrRecordNotFound) {
return fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
}
s.Log.Errorf("Failed to delete projectflock: %+v", err)
return err
}
if err := tx.Commit().Error; err != nil {
tx.Rollback()
return fiber.NewError(fiber.StatusInternalServerError, "Failed to commit transaction")
}
return nil
}
func (s projectflockService) GetFlockPeriodSummary(c *fiber.Ctx, flockID uint) (*FlockPeriodSummary, error) {
flock, err := s.FlockRepo.GetByID(c.Context(), flockID, func(db *gorm.DB) *gorm.DB {
return db.Preload("CreatedUser")
})
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Flock not found")
}
if err != nil {
s.Log.Errorf("Failed get flock %d for period summary: %+v", flockID, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch flock")
}
maxPeriod, err := s.Repository.GetMaxPeriodByFlock(c.Context(), flockID)
if err != nil {
s.Log.Errorf("Failed to compute next period for flock %d: %+v", flockID, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to compute next period")
}
return &FlockPeriodSummary{
Flock: *flock,
NextPeriod: maxPeriod + 1,
}, nil
}
func uniqueUintSlice(values []uint) []uint {
seen := make(map[uint]struct{}, len(values))
result := make([]uint, 0, len(values))
for _, v := range values {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
result = append(result, v)
}
return result
}
@@ -0,0 +1,27 @@
package validation
type Create struct {
FlockId uint `json:"flock_id" validate:"required_strict,number,gt=0"`
AreaId uint `json:"area_id" validate:"required_strict,number,gt=0"`
ProductCategoryId uint `json:"product_category_id" validate:"required_strict,number,gt=0"`
FcrId uint `json:"fcr_id" validate:"required_strict,number,gt=0"`
LocationId uint `json:"location_id" validate:"required_strict,number,gt=0"`
Period int `json:"period" validate:"required_strict,number,gt=0"`
KandangIds []uint `json:"kandang_ids" validate:"required,min=1,dive,gt=0"`
}
type Update struct {
FlockId *uint `json:"flock_id,omitempty" validate:"omitempty,number,gt=0"`
AreaId *uint `json:"area_id,omitempty" validate:"omitempty,number,gt=0"`
ProductCategoryId *uint `json:"product_category_id,omitempty" validate:"omitempty,number,gt=0"`
FcrId *uint `json:"fcr_id,omitempty" validate:"omitempty,number,gt=0"`
LocationId *uint `json:"location_id,omitempty" validate:"omitempty,number,gt=0"`
Period *int `json:"period,omitempty" validate:"omitempty,number,gt=0"`
KandangIds []uint `json:"kandang_ids,omitempty" validate:"omitempty,min=1,dive,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"`
}
+25
View File
@@ -0,0 +1,25 @@
package production
import (
"gitlab.com/mbugroup/lti-api.git/internal/modules"
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
projectflocks "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks"
// MODULE IMPORTS
)
func RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
group := router.Group("/production")
allModules := []modules.Module{
projectflocks.ProjectflockModule{},
// MODULE REGISTRY
}
for _, m := range allModules {
m.RegisterRoutes(group, db, validate)
}
}