mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
add migration;add api create employee
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/dto"
|
||||
service "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/services"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/validations"
|
||||
"gitlab.com/mbugroup/lti-api.git/internal/response"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type EmployeesController struct {
|
||||
EmployeesService service.EmployeesService
|
||||
}
|
||||
|
||||
func NewEmployeesController(employeesService service.EmployeesService) *EmployeesController {
|
||||
return &EmployeesController{
|
||||
EmployeesService: employeesService,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *EmployeesController) GetAll(c *fiber.Ctx) error {
|
||||
query := &validation.Query{
|
||||
Page: c.QueryInt("page", 1),
|
||||
Limit: c.QueryInt("limit", 10),
|
||||
Search: c.Query("search", ""),
|
||||
}
|
||||
|
||||
if query.Page < 1 || query.Limit < 1 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "page and limit must be greater than 0")
|
||||
}
|
||||
|
||||
result, totalResults, err := u.EmployeesService.GetAll(c, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.SuccessWithPaginate[dto.EmployeesListDTO]{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get all employeess successfully",
|
||||
Meta: response.Meta{
|
||||
Page: query.Page,
|
||||
Limit: query.Limit,
|
||||
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
|
||||
TotalResults: totalResults,
|
||||
},
|
||||
Data: dto.ToEmployeesListDTOs(result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *EmployeesController) 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.EmployeesService.GetOne(c, uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Get employees successfully",
|
||||
Data: dto.ToEmployeesListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *EmployeesController) 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.EmployeesService.CreateOne(c, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusCreated).
|
||||
JSON(response.Success{
|
||||
Code: fiber.StatusCreated,
|
||||
Status: "success",
|
||||
Message: "Create employees successfully",
|
||||
Data: dto.ToEmployeesListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *EmployeesController) 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.EmployeesService.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 employees successfully",
|
||||
Data: dto.ToEmployeesListDTO(*result),
|
||||
})
|
||||
}
|
||||
|
||||
func (u *EmployeesController) 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.EmployeesService.DeleteOne(c, uint(id)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).
|
||||
JSON(response.Common{
|
||||
Code: fiber.StatusOK,
|
||||
Status: "success",
|
||||
Message: "Delete employees successfully",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
kandangDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/dto"
|
||||
)
|
||||
|
||||
// === DTO Structs ===
|
||||
|
||||
type EmployeesRelationDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type EmployeesListDTO struct {
|
||||
Id uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
Kandangs []kandangDTO.KandangRelationDTO `json:"kandangs"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type EmployeesDetailDTO struct {
|
||||
EmployeesListDTO
|
||||
}
|
||||
|
||||
// === Mapper Functions ===
|
||||
|
||||
func ToEmployeesRelationDTO(e entity.Employees) EmployeesRelationDTO {
|
||||
return EmployeesRelationDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
}
|
||||
}
|
||||
|
||||
func ToEmployeesListDTO(e entity.Employees) EmployeesListDTO {
|
||||
kandangs := make([]kandangDTO.KandangRelationDTO, 0, len(e.EmployeeKandangs))
|
||||
for _, rel := range e.EmployeeKandangs {
|
||||
if rel.Kandang.Id == 0 {
|
||||
continue
|
||||
}
|
||||
kandangs = append(kandangs, kandangDTO.ToKandangRelationDTO(rel.Kandang))
|
||||
}
|
||||
|
||||
return EmployeesListDTO{
|
||||
Id: e.Id,
|
||||
Name: e.Name,
|
||||
IsActive: e.IsActive,
|
||||
Kandangs: kandangs,
|
||||
CreatedAt: e.CreatedAt,
|
||||
UpdatedAt: e.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func ToEmployeesListDTOs(e []entity.Employees) []EmployeesListDTO {
|
||||
result := make([]EmployeesListDTO, len(e))
|
||||
for i, r := range e {
|
||||
result[i] = ToEmployeesListDTO(r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ToEmployeesDetailDTO(e entity.Employees) EmployeesDetailDTO {
|
||||
return EmployeesDetailDTO{
|
||||
EmployeesListDTO: ToEmployeesListDTO(e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package employeess
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
|
||||
rEmployees "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/repositories"
|
||||
sEmployees "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/services"
|
||||
|
||||
rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
|
||||
sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
)
|
||||
|
||||
type EmployeesModule struct{}
|
||||
|
||||
func (EmployeesModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
|
||||
employeesRepo := rEmployees.NewEmployeesRepository(db)
|
||||
userRepo := rUser.NewUserRepository(db)
|
||||
|
||||
employeesService := sEmployees.NewEmployeesService(employeesRepo, validate)
|
||||
userService := sUser.NewUserService(userRepo, validate)
|
||||
|
||||
EmployeesRoutes(router, userService, employeesService)
|
||||
}
|
||||
@@ -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 EmployeesRepository interface {
|
||||
repository.BaseRepository[entity.Employees]
|
||||
}
|
||||
|
||||
type EmployeesRepositoryImpl struct {
|
||||
*repository.BaseRepositoryImpl[entity.Employees]
|
||||
}
|
||||
|
||||
func NewEmployeesRepository(db *gorm.DB) EmployeesRepository {
|
||||
return &EmployeesRepositoryImpl{
|
||||
BaseRepositoryImpl: repository.NewBaseRepository[entity.Employees](db),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package employeess
|
||||
|
||||
import (
|
||||
m "gitlab.com/mbugroup/lti-api.git/internal/middleware"
|
||||
controller "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/controllers"
|
||||
employees "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees/services"
|
||||
user "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func EmployeesRoutes(v1 fiber.Router, u user.UserService, s employees.EmployeesService) {
|
||||
ctrl := controller.NewEmployeesController(s)
|
||||
|
||||
route := v1.Group("/employees")
|
||||
route.Use(m.Auth(u))
|
||||
|
||||
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,209 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"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").
|
||||
Preload("EmployeeKandangs.Kandang.Location").
|
||||
Preload("EmployeeKandangs.Kandang.Pic").
|
||||
Preload("EmployeeKandangs.Kandang.CreatedUser")
|
||||
}
|
||||
|
||||
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 != "" {
|
||||
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 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, err := parseKandangIDs(req.KandangIDs)
|
||||
if err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
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, "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 parseKandangIDs(raw string) ([]uint, error) {
|
||||
parts := strings.Split(raw, ",")
|
||||
ids := make([]uint, 0, len(parts))
|
||||
seen := make(map[uint]struct{})
|
||||
|
||||
for _, part := range parts {
|
||||
value := strings.TrimSpace(part)
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseUint(value, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid kandang id: %s", value)
|
||||
}
|
||||
|
||||
id := uint(parsed)
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
|
||||
if len(ids) == 0 {
|
||||
return nil, errors.New("kandang_ids must contain at least one valid id")
|
||||
}
|
||||
|
||||
return ids, nil
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package validation
|
||||
|
||||
type Create struct {
|
||||
Name string `json:"name" validate:"required_strict,min=3"`
|
||||
KandangIDs string `json:"kandang_ids" validate:"required"`
|
||||
IsActive bool `json:"is_active"`
|
||||
}
|
||||
|
||||
type Update struct {
|
||||
Name *string `json:"name,omitempty" validate:"omitempty"`
|
||||
KandangIDs *string `json:"kandang_ids,omitempty"`
|
||||
IsActive *bool `json:"is_active,omitempty"`
|
||||
}
|
||||
|
||||
type Query struct {
|
||||
Page int `query:"page" validate:"omitempty,number,min=1,gt=0"`
|
||||
Limit int `query:"limit" validate:"omitempty,number,min=1,max=100,gt=0"`
|
||||
Search string `query:"search" validate:"omitempty,max=50"`
|
||||
}
|
||||
@@ -10,17 +10,18 @@ import (
|
||||
areas "gitlab.com/mbugroup/lti-api.git/internal/modules/master/areas"
|
||||
banks "gitlab.com/mbugroup/lti-api.git/internal/modules/master/banks"
|
||||
customers "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers"
|
||||
employeess "gitlab.com/mbugroup/lti-api.git/internal/modules/master/employees"
|
||||
fcrs "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs"
|
||||
flocks "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks"
|
||||
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"
|
||||
productionStandards "gitlab.com/mbugroup/lti-api.git/internal/modules/master/production-standards"
|
||||
products "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products"
|
||||
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"
|
||||
productionStandards "gitlab.com/mbugroup/lti-api.git/internal/modules/master/production-standards"
|
||||
// MODULE IMPORTS
|
||||
)
|
||||
|
||||
@@ -42,6 +43,7 @@ func RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Valida
|
||||
banks.BankModule{},
|
||||
flocks.FlockModule{},
|
||||
productionStandards.ProductionStandardModule{},
|
||||
employeess.EmployeesModule{},
|
||||
// MODULE REGISTRY
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user