mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-23 23:05:44 +00:00
add daily checklist module;adjust master data;adjust migration
This commit is contained in:
@@ -0,0 +1,410 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/daily-checklists/repositories"
|
||||
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/daily-checklists/validations"
|
||||
phaseRepo "gitlab.com/mbugroup/lti-api.git/internal/modules/master/phasess/repositories"
|
||||
"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"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type DailyChecklistService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.DailyChecklist, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.DailyChecklist, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.DailyChecklist, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.DailyChecklist, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
AssignPhases(ctx *fiber.Ctx, id uint, req *validation.AssignPhases) error
|
||||
AssignTasks(ctx *fiber.Ctx, id uint, req *validation.AssignTask) error
|
||||
RemoveAssignment(ctx *fiber.Ctx, id uint, employeeID uint) error
|
||||
GetTasks(ctx *fiber.Ctx, checklistID uint) ([]entity.DailyChecklistActivityTask, error)
|
||||
}
|
||||
|
||||
type dailyChecklistService struct {
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
Repository repository.DailyChecklistRepository
|
||||
PhaseRepo phaseRepo.PhasesRepository
|
||||
}
|
||||
|
||||
func NewDailyChecklistService(repo repository.DailyChecklistRepository, phaseRepo phaseRepo.PhasesRepository, validate *validator.Validate) DailyChecklistService {
|
||||
return &dailyChecklistService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
PhaseRepo: phaseRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s dailyChecklistService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db
|
||||
}
|
||||
|
||||
func (s dailyChecklistService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.DailyChecklist, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
offset := (params.Page - 1) * params.Limit
|
||||
|
||||
dailyChecklists, 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 dailyChecklists: %+v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
return dailyChecklists, total, nil
|
||||
}
|
||||
|
||||
func (s dailyChecklistService) GetOne(c *fiber.Ctx, id uint) (*entity.DailyChecklist, error) {
|
||||
dailyChecklist, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "DailyChecklist not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get dailyChecklist by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return dailyChecklist, nil
|
||||
}
|
||||
|
||||
func (s *dailyChecklistService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.DailyChecklist, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
date, err := time.Parse("2006-01-02", req.Date)
|
||||
if err != nil {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "invalid date format, use YYYY-MM-DD")
|
||||
}
|
||||
|
||||
status := req.Status
|
||||
category := req.Category
|
||||
|
||||
createBody := &entity.DailyChecklist{
|
||||
KandangId: req.KandangId,
|
||||
Date: date,
|
||||
Category: category,
|
||||
Status: &status,
|
||||
}
|
||||
|
||||
err = s.Repository.DB().WithContext(c.Context()).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "date"}, {Name: "kandang_id"}, {Name: "category"}},
|
||||
DoUpdates: clause.Assignments(map[string]any{"status": status, "updated_at": time.Now()}),
|
||||
}).Create(createBody).Error
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to upsert dailyChecklist: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s dailyChecklistService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.DailyChecklist, 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, "DailyChecklist not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update dailyChecklist: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s dailyChecklistService) 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, "DailyChecklist not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete dailyChecklist: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s dailyChecklistService) AssignPhases(c *fiber.Ctx, id uint, req *validation.AssignPhases) error {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := s.Repository.GetByID(c.Context(), id, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "DailyChecklist not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
phaseIDs, err := parsePhaseIDs(req.PhaseIDs)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if len(phaseIDs) > 0 {
|
||||
phases, err := s.PhaseRepo.GetByIDs(c.Context(), phaseIDs, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Phase not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if len(phases) != len(phaseIDs) {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Phase not found")
|
||||
}
|
||||
}
|
||||
|
||||
db := s.Repository.DB()
|
||||
if err := db.WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("checklist_id = ?", id).Delete(&entity.DailyChecklistPhase{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(phaseIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
records := make([]entity.DailyChecklistPhase, 0, len(phaseIDs))
|
||||
for _, pid := range phaseIDs {
|
||||
records = append(records, entity.DailyChecklistPhase{
|
||||
ChecklistId: id,
|
||||
PhaseId: pid,
|
||||
})
|
||||
}
|
||||
|
||||
if err := tx.Create(&records).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Where("checklist_id = ?", id).Delete(&entity.DailyChecklistActivityTask{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var activities []entity.PhaseActivity
|
||||
if err := tx.Where("phase_id IN ?", phaseIDs).Find(&activities).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
activityRecords := make([]entity.DailyChecklistActivityTask, 0, len(activities))
|
||||
for _, activity := range activities {
|
||||
activityRecords = append(activityRecords, entity.DailyChecklistActivityTask{
|
||||
ChecklistId: id,
|
||||
PhaseId: activity.PhaseId,
|
||||
PhaseActivityId: activity.Id,
|
||||
TimeType: activity.TimeType,
|
||||
})
|
||||
}
|
||||
|
||||
if len(activityRecords) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return tx.Create(&activityRecords).Error
|
||||
}); err != nil {
|
||||
s.Log.Errorf("Failed to assign phases to daily checklist: %+v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s dailyChecklistService) RemoveAssignment(c *fiber.Ctx, id uint, employeeID uint) error {
|
||||
if _, err := s.Repository.GetByID(c.Context(), id, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "DailyChecklist not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if employeeID == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "Invalid employee id")
|
||||
}
|
||||
|
||||
db := s.Repository.DB()
|
||||
if err := db.WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
var tasks []entity.DailyChecklistActivityTask
|
||||
if err := tx.Where("checklist_id = ?", id).Find(&tasks).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(tasks) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "No activity tasks found for this checklist")
|
||||
}
|
||||
|
||||
taskIDs := collectTaskIDs(tasks)
|
||||
return tx.Where("task_id IN ? AND employee_id = ?", taskIDs, employeeID).
|
||||
Delete(&entity.DailyChecklistActivityTaskAssignment{}).Error
|
||||
}); err != nil {
|
||||
s.Log.Errorf("Failed to remove assignment: %+v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s dailyChecklistService) GetTasks(c *fiber.Ctx, checklistID uint) ([]entity.DailyChecklistActivityTask, error) {
|
||||
if checklistID == 0 {
|
||||
return nil, fiber.NewError(fiber.StatusBadRequest, "checklist_id is required")
|
||||
}
|
||||
|
||||
if _, err := s.Repository.GetByID(c.Context(), checklistID, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "DailyChecklist not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var tasks []entity.DailyChecklistActivityTask
|
||||
if err := s.Repository.DB().WithContext(c.Context()).
|
||||
Where("checklist_id = ?", checklistID).
|
||||
Order("created_at ASC").
|
||||
Find(&tasks).Error; err != nil {
|
||||
s.Log.Errorf("Failed to get daily checklist tasks: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tasks, nil
|
||||
}
|
||||
|
||||
func parsePhaseIDs(raw string) ([]uint, error) {
|
||||
parts := strings.Split(raw, ",")
|
||||
result := make([]uint, 0, len(parts))
|
||||
seen := make(map[uint]struct{})
|
||||
|
||||
for _, part := range parts {
|
||||
value := strings.TrimSpace(part)
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
num, err := strconv.ParseUint(value, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid phase id: " + value)
|
||||
}
|
||||
u := uint(num)
|
||||
if _, ok := seen[u]; ok {
|
||||
continue
|
||||
}
|
||||
seen[u] = struct{}{}
|
||||
result = append(result, u)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func parseIDs(raw string) ([]uint, error) {
|
||||
parts := strings.Split(raw, ",")
|
||||
result := make([]uint, 0, len(parts))
|
||||
seen := make(map[uint]struct{})
|
||||
|
||||
for _, part := range parts {
|
||||
value := strings.TrimSpace(part)
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
num, err := strconv.ParseUint(value, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid employee id: " + value)
|
||||
}
|
||||
u := uint(num)
|
||||
if _, ok := seen[u]; ok {
|
||||
continue
|
||||
}
|
||||
seen[u] = struct{}{}
|
||||
result = append(result, u)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func collectTaskIDs(tasks []entity.DailyChecklistActivityTask) []uint {
|
||||
result := make([]uint, len(tasks))
|
||||
for i, task := range tasks {
|
||||
result[i] = task.Id
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (s dailyChecklistService) AssignTasks(c *fiber.Ctx, id uint, req *validation.AssignTask) error {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
employeeIDs, err := parseIDs(req.EmployeeIDs)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if len(employeeIDs) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "employee_ids cannot be empty")
|
||||
}
|
||||
|
||||
if _, err := s.Repository.GetByID(c.Context(), id, nil); err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "DailyChecklist not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
db := s.Repository.DB()
|
||||
if err := db.WithContext(c.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
var tasks []entity.DailyChecklistActivityTask
|
||||
if err := tx.Where("checklist_id = ?", id).Find(&tasks).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(tasks) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "No activity tasks found for this checklist")
|
||||
}
|
||||
|
||||
assignments := make([]entity.DailyChecklistActivityTaskAssignment, 0, len(tasks)*len(employeeIDs))
|
||||
for _, task := range tasks {
|
||||
for _, empID := range employeeIDs {
|
||||
assignments = append(assignments, entity.DailyChecklistActivityTaskAssignment{
|
||||
TaskId: task.Id,
|
||||
EmployeeId: empID,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "task_id"}, {Name: "employee_id"}},
|
||||
DoUpdates: clause.Assignments(map[string]any{"updated_at": time.Now()}),
|
||||
}).Create(&assignments).Error
|
||||
}); err != nil {
|
||||
s.Log.Errorf("Failed to assign tasks to daily checklist: %+v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user