mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
266 lines
7.2 KiB
Go
266 lines
7.2 KiB
Go
package service
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
|
|
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
|
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/repositories"
|
|
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/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 EmployeesService interface {
|
|
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Employees, int64, error)
|
|
GetOne(ctx *fiber.Ctx, id uint) (*entity.Employees, error)
|
|
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Employees, error)
|
|
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Employees, error)
|
|
DeleteOne(ctx *fiber.Ctx, id uint) error
|
|
}
|
|
|
|
type employeesService struct {
|
|
Log *logrus.Logger
|
|
Validate *validator.Validate
|
|
Repository repository.EmployeesRepository
|
|
}
|
|
|
|
func NewEmployeesService(repo repository.EmployeesRepository, validate *validator.Validate) EmployeesService {
|
|
return &employeesService{
|
|
Log: utils.Log,
|
|
Validate: validate,
|
|
Repository: repo,
|
|
}
|
|
}
|
|
|
|
func (s employeesService) withRelations(db *gorm.DB) *gorm.DB {
|
|
return db.
|
|
Preload("EmployeeKandangs.Kandang").
|
|
Where("employees.deleted_at IS NULL")
|
|
}
|
|
|
|
func (s employeesService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Employees, int64, error) {
|
|
if err := s.Validate.Struct(params); err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
offset := (params.Page - 1) * params.Limit
|
|
|
|
employeess, total, err := s.Repository.GetAll(c.Context(), offset, params.Limit, func(db *gorm.DB) *gorm.DB {
|
|
db = s.withRelations(db)
|
|
if params.Search != "" {
|
|
db = db.Where("LOWER(employees.name) LIKE LOWER(?)", "%"+params.Search+"%")
|
|
}
|
|
if params.KandangId != nil {
|
|
db = db.Joins("JOIN employee_kandangs ek ON ek.employee_id = employees.id").
|
|
Where("ek.kandang_id = ?", *params.KandangId)
|
|
}
|
|
if params.IsActive != nil {
|
|
db = db.Where("employees.is_active = ?", *params.IsActive)
|
|
}
|
|
return db.Order("employees.created_at DESC").Order("employees.updated_at DESC")
|
|
})
|
|
|
|
if err != nil {
|
|
s.Log.Errorf("Failed to get employeess: %+v", err)
|
|
return nil, 0, err
|
|
}
|
|
return employeess, total, nil
|
|
}
|
|
|
|
func (s employeesService) GetOne(c *fiber.Ctx, id uint) (*entity.Employees, error) {
|
|
employees, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, fiber.NewError(fiber.StatusNotFound, "Employees not found")
|
|
}
|
|
if err != nil {
|
|
s.Log.Errorf("Failed get employees by id: %+v", err)
|
|
return nil, err
|
|
}
|
|
return employees, nil
|
|
}
|
|
|
|
func (s *employeesService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Employees, error) {
|
|
if err := s.Validate.Struct(req); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
name := strings.TrimSpace(req.Name)
|
|
if name == "" {
|
|
return nil, fiber.NewError(fiber.StatusBadRequest, "name cannot be empty")
|
|
}
|
|
|
|
kandangIDs := normalizeKandangIDs(req.KandangIDs)
|
|
if len(kandangIDs) == 0 {
|
|
return nil, fiber.NewError(fiber.StatusBadRequest, "kandang_ids must contain at least one valid id")
|
|
}
|
|
|
|
if _, err := s.Repository.First(c.Context(), func(db *gorm.DB) *gorm.DB {
|
|
return db.Where("LOWER(name) = ?", strings.ToLower(name))
|
|
}); err == nil {
|
|
return nil, fiber.NewError(fiber.StatusBadRequest, "employee already exists")
|
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
s.Log.Errorf("Failed checking employee uniqueness: %+v", err)
|
|
return nil, err
|
|
}
|
|
|
|
createBody := &entity.Employees{
|
|
Name: name,
|
|
IsActive: req.IsActive,
|
|
}
|
|
|
|
if err := s.Repository.DB().Transaction(func(tx *gorm.DB) error {
|
|
repoTx := s.Repository.WithTx(tx)
|
|
|
|
if err := repoTx.CreateOne(c.Context(), createBody, nil); err != nil {
|
|
return err
|
|
}
|
|
|
|
relations := make([]entity.EmployeeKandang, 0, len(kandangIDs))
|
|
for _, kandangID := range kandangIDs {
|
|
relations = append(relations, entity.EmployeeKandang{
|
|
EmployeeId: createBody.Id,
|
|
KandangId: kandangID,
|
|
})
|
|
}
|
|
|
|
if len(relations) > 0 {
|
|
if err := tx.WithContext(c.Context()).Create(&relations).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}); err != nil {
|
|
s.Log.Errorf("Failed to create employees: %+v", err)
|
|
return nil, err
|
|
}
|
|
|
|
return s.GetOne(c, createBody.Id)
|
|
}
|
|
|
|
func (s employeesService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Employees, error) {
|
|
if err := s.Validate.Struct(req); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
updateBody := make(map[string]any)
|
|
var (
|
|
kandangIDs []uint
|
|
needKandangUpdate bool
|
|
)
|
|
|
|
if req.Name != nil {
|
|
trimmed := strings.TrimSpace(*req.Name)
|
|
if trimmed == "" {
|
|
return nil, fiber.NewError(fiber.StatusBadRequest, "name cannot be empty")
|
|
}
|
|
|
|
if _, err := s.Repository.First(c.Context(), func(db *gorm.DB) *gorm.DB {
|
|
return db.Where("LOWER(name) = ? AND id <> ?", strings.ToLower(trimmed), id)
|
|
}); err == nil {
|
|
return nil, fiber.NewError(fiber.StatusBadRequest, "employee already exists")
|
|
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
s.Log.Errorf("Failed checking employee uniqueness: %+v", err)
|
|
return nil, err
|
|
}
|
|
|
|
updateBody["name"] = trimmed
|
|
}
|
|
|
|
if req.IsActive != nil {
|
|
updateBody["is_active"] = *req.IsActive
|
|
}
|
|
|
|
if req.KandangIDs != nil {
|
|
ids := normalizeKandangIDs(*req.KandangIDs)
|
|
if len(ids) == 0 {
|
|
return nil, fiber.NewError(fiber.StatusBadRequest, "kandang_ids must contain at least one valid id")
|
|
}
|
|
|
|
kandangIDs = ids
|
|
needKandangUpdate = true
|
|
}
|
|
|
|
if len(updateBody) == 0 && !needKandangUpdate {
|
|
return s.GetOne(c, id)
|
|
}
|
|
|
|
if err := s.Repository.DB().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
|
|
}
|
|
}
|
|
|
|
if needKandangUpdate {
|
|
if err := tx.WithContext(c.Context()).
|
|
Where("employee_id = ?", id).
|
|
Delete(&entity.EmployeeKandang{}).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
relations := make([]entity.EmployeeKandang, 0, len(kandangIDs))
|
|
for _, kandangID := range kandangIDs {
|
|
relations = append(relations, entity.EmployeeKandang{
|
|
EmployeeId: id,
|
|
KandangId: kandangID,
|
|
})
|
|
}
|
|
|
|
if len(relations) > 0 {
|
|
if err := tx.WithContext(c.Context()).Create(&relations).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}); err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, fiber.NewError(fiber.StatusNotFound, "Employees not found")
|
|
}
|
|
s.Log.Errorf("Failed to update employees: %+v", err)
|
|
return nil, err
|
|
}
|
|
|
|
return s.GetOne(c, id)
|
|
}
|
|
|
|
func (s employeesService) 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, "Employees not found")
|
|
}
|
|
s.Log.Errorf("Failed to delete employees: %+v", err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func normalizeKandangIDs(ids []uint) []uint {
|
|
result := make([]uint, 0, len(ids))
|
|
seen := make(map[uint]struct{})
|
|
|
|
for _, id := range ids {
|
|
if id == 0 {
|
|
continue
|
|
}
|
|
|
|
if _, ok := seen[id]; ok {
|
|
continue
|
|
}
|
|
|
|
seen[id] = struct{}{}
|
|
result = append(result, id)
|
|
}
|
|
|
|
return result
|
|
}
|