Merge branch 'feat/BE/Sprint-5' of https://gitlab.com/mbugroup/lti-api into dev/teguh

This commit is contained in:
aguhh18
2025-11-21 10:46:50 +07:00
77 changed files with 1453 additions and 3969 deletions
@@ -4,26 +4,26 @@ import (
"time"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
areaBaseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/areas/dto"
fcrBaseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/dto"
flockBaseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
kandangBaseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/dto"
locationBaseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/locations/dto"
areaRelationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/areas/dto"
fcrRelationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/dto"
flockRelationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
kandangRelationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/dto"
locationRelationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/locations/dto"
productDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/dto"
warehouseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/warehouses/dto"
pfutils "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/utils"
userBaseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
userRelationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)
// === DTO Structs (ordered) ===
type ProductWarehouseDTO struct {
Id uint `json:"id"`
Product *productDTO.ProductBaseDTO `json:"product,omitempty"`
Warehouse *warehouseDTO.WarehouseBaseDTO `json:"warehouse,omitempty"`
Id uint `json:"id"`
Product *productDTO.ProductRelationDTO `json:"product,omitempty"`
Warehouse *warehouseDTO.WarehouseRelationDTO `json:"warehouse,omitempty"`
}
type ChickinBaseDTO struct {
type ChickinRelationDTO struct {
Id uint `json:"id"`
ProjectFlockKandangId uint `json:"project_flock_kandang_id"`
ChickInDate time.Time `json:"chick_in_date"`
@@ -35,19 +35,19 @@ type ChickinBaseDTO struct {
}
type ProjectFlockDTO struct {
Id uint `json:"id"`
Period int `json:"period"`
Category string `json:"category"`
Flock *flockBaseDTO.FlockBaseDTO `json:"flock"`
Area *areaBaseDTO.AreaBaseDTO `json:"area"`
Fcr *fcrBaseDTO.FcrBaseDTO `json:"fcr"`
Location *locationBaseDTO.LocationBaseDTO `json:"location"`
Id uint `json:"id"`
Period int `json:"period"`
Category string `json:"category"`
Flock *flockRelationDTO.FlockRelationDTO `json:"flock"`
Area *areaRelationDTO.AreaRelationDTO `json:"area"`
Fcr *fcrRelationDTO.FcrRelationDTO `json:"fcr"`
Location *locationRelationDTO.LocationRelationDTO `json:"location"`
}
type ProjectFlockKandangDTO struct {
Id uint `json:"id"`
ProjectFlock *ProjectFlockDTO `json:"project_flock"`
Kandang *kandangBaseDTO.KandangBaseDTO `json:"kandang"`
Id uint `json:"id"`
ProjectFlock *ProjectFlockDTO `json:"project_flock"`
Kandang *kandangRelationDTO.KandangRelationDTO `json:"kandang"`
}
// gunakan base DTO dari package users
@@ -64,75 +64,76 @@ type ChickinSimpleDTO struct {
}
type ChickinListDTO struct {
ChickinBaseDTO
CreatedUser *userBaseDTO.UserBaseDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ChickinRelationDTO
CreatedUser *userRelationDTO.UserRelationDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type ChickinDetailDTO struct {
Id uint `json:"id"`
ProjectFlockKandangId uint `json:"project_flock_kandang_id"`
ChickInDate time.Time `json:"chick_in_date"`
ProductWarehouseId uint `json:"product_warehouse_id"`
UsageQty float64 `json:"usage_qty"`
PendingUsageQty float64 `json:"pending_usage_qty"`
Notes string `json:"notes"`
CreatedBy uint `json:"created_by"`
CreatedUser *userBaseDTO.UserBaseDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Id uint `json:"id"`
ProjectFlockKandangId uint `json:"project_flock_kandang_id"`
ChickInDate time.Time `json:"chick_in_date"`
ProductWarehouseId uint `json:"product_warehouse_id"`
UsageQty float64 `json:"usage_qty"`
PendingUsageQty float64 `json:"pending_usage_qty"`
Notes string `json:"notes"`
CreatedBy uint `json:"created_by"`
CreatedUser *userRelationDTO.UserRelationDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// === Mapper Functions (ordered) ===
func ToFlockDTO(e entity.Flock) flockBaseDTO.FlockBaseDTO {
return flockBaseDTO.ToFlockBaseDTO(e)
func ToFlockDTO(e entity.Flock) flockRelationDTO.FlockRelationDTO {
return flockRelationDTO.ToFlockRelationDTO(e)
}
func ToKandangDTO(e entity.Kandang) kandangBaseDTO.KandangBaseDTO {
return kandangBaseDTO.ToKandangBaseDTO(e)
func ToKandangDTO(e entity.Kandang) kandangRelationDTO.KandangRelationDTO {
return kandangRelationDTO.ToKandangRelationDTO(e)
}
func ToAreaDTO(e entity.Area) areaBaseDTO.AreaBaseDTO {
return areaBaseDTO.ToAreaBaseDTO(e)
func ToAreaDTO(e entity.Area) areaRelationDTO.AreaRelationDTO {
return areaRelationDTO.ToAreaRelationDTO(e)
}
func ToFcrDTO(e entity.Fcr) fcrBaseDTO.FcrBaseDTO {
return fcrBaseDTO.ToFcrBaseDTO(e)
func ToFcrDTO(e entity.Fcr) fcrRelationDTO.FcrRelationDTO {
return fcrRelationDTO.ToFcrRelationDTO(e)
}
func ToLocationDTO(e entity.Location) locationBaseDTO.LocationBaseDTO {
return locationBaseDTO.ToLocationBaseDTO(e)
func ToLocationDTO(e entity.Location) locationRelationDTO.LocationRelationDTO {
return locationRelationDTO.ToLocationRelationDTO(e)
}
func ToUserBaseDTO(e entity.User) userBaseDTO.UserBaseDTO {
return userBaseDTO.ToUserBaseDTO(e)
func ToUserRelationDTO(e entity.User) userRelationDTO.UserRelationDTO {
return userRelationDTO.ToUserRelationDTO(e)
}
func ToProjectFlockDTO(e entity.ProjectFlock) ProjectFlockDTO {
var flock *flockBaseDTO.FlockBaseDTO
func ToProjectFlockDTO(pfk entity.ProjectFlockKandang) ProjectFlockDTO {
e := pfk.ProjectFlock
var flock *flockRelationDTO.FlockRelationDTO
if base := pfutils.DeriveBaseName(e.FlockName); base != "" {
summary := flockBaseDTO.FlockBaseDTO{Id: 0, Name: base}
summary := flockRelationDTO.FlockRelationDTO{Id: 0, Name: base}
flock = &summary
}
var area *areaBaseDTO.AreaBaseDTO
var area *areaRelationDTO.AreaRelationDTO
if e.Area.Id != 0 {
mapped := areaBaseDTO.ToAreaBaseDTO(e.Area)
mapped := areaRelationDTO.ToAreaRelationDTO(e.Area)
area = &mapped
}
var fcr *fcrBaseDTO.FcrBaseDTO
var fcr *fcrRelationDTO.FcrRelationDTO
if e.Fcr.Id != 0 {
mapped := fcrBaseDTO.ToFcrBaseDTO(e.Fcr)
mapped := fcrRelationDTO.ToFcrRelationDTO(e.Fcr)
fcr = &mapped
}
var location *locationBaseDTO.LocationBaseDTO
var location *locationRelationDTO.LocationRelationDTO
if e.Location.Id != 0 {
mapped := locationBaseDTO.ToLocationBaseDTO(e.Location)
mapped := locationRelationDTO.ToLocationRelationDTO(e.Location)
location = &mapped
}
return ProjectFlockDTO{
Id: e.Id,
Period: e.Period,
Period: pfk.Period,
Category: e.Category,
Flock: flock,
Area: area,
@@ -144,12 +145,12 @@ func ToProjectFlockDTO(e entity.ProjectFlock) ProjectFlockDTO {
func ToProjectFlockKandangDTO(e entity.ProjectFlockKandang) ProjectFlockKandangDTO {
var pf *ProjectFlockDTO
if e.ProjectFlock.Id != 0 {
mapped := ToProjectFlockDTO(e.ProjectFlock)
mapped := ToProjectFlockDTO(e)
pf = &mapped
}
var kandang *kandangBaseDTO.KandangBaseDTO
var kandang *kandangRelationDTO.KandangRelationDTO
if e.Kandang.Id != 0 {
mapped := kandangBaseDTO.ToKandangBaseDTO(e.Kandang)
mapped := kandangRelationDTO.ToKandangRelationDTO(e.Kandang)
kandang = &mapped
}
return ProjectFlockKandangDTO{
@@ -159,7 +160,7 @@ func ToProjectFlockKandangDTO(e entity.ProjectFlockKandang) ProjectFlockKandangD
}
}
func ToChickinBaseDTO(e entity.ProjectChickin) ChickinBaseDTO {
func ToChickinRelationDTO(e entity.ProjectChickin) ChickinRelationDTO {
var projectFlockKandangId uint
// Check if ProjectFlockKandang relation is loaded
if e.ProjectFlockKandang != nil && e.ProjectFlockKandang.Id != 0 {
@@ -174,7 +175,7 @@ func ToChickinBaseDTO(e entity.ProjectChickin) ChickinBaseDTO {
productWarehouse = toProductWarehouseDTO(e.ProductWarehouse)
}
return ChickinBaseDTO{
return ChickinRelationDTO{
Id: e.Id,
ProjectFlockKandangId: projectFlockKandangId,
ChickInDate: e.ChickInDate,
@@ -200,16 +201,16 @@ func ToChickinSimpleDTO(e entity.ProjectChickin) ChickinSimpleDTO {
}
func ToChickinListDTO(e entity.ProjectChickin) ChickinListDTO {
var createdUser *userBaseDTO.UserBaseDTO
var createdUser *userRelationDTO.UserRelationDTO
if e.CreatedUser != nil && e.CreatedUser.Id != 0 {
mapped := userBaseDTO.ToUserBaseDTO(*e.CreatedUser)
mapped := userRelationDTO.ToUserRelationDTO(*e.CreatedUser)
createdUser = &mapped
}
return ChickinListDTO{
ChickinBaseDTO: ToChickinBaseDTO(e),
CreatedUser: createdUser,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
ChickinRelationDTO: ToChickinRelationDTO(e),
CreatedUser: createdUser,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
}
}
@@ -230,9 +231,9 @@ func ToChickinSimpleDTOs(e []entity.ProjectChickin) []ChickinSimpleDTO {
}
func ToChickinDetailDTO(e entity.ProjectChickin) ChickinDetailDTO {
var createdUser *userBaseDTO.UserBaseDTO
var createdUser *userRelationDTO.UserRelationDTO
if e.CreatedUser != nil && e.CreatedUser.Id != 0 {
mapped := userBaseDTO.ToUserBaseDTO(*e.CreatedUser)
mapped := userRelationDTO.ToUserRelationDTO(*e.CreatedUser)
createdUser = &mapped
}
@@ -267,8 +268,8 @@ func ToProductWarehouseDTO(pw *entity.ProductWarehouse) *ProductWarehouseDTO {
return nil
}
product := productDTO.ToProductBaseDTO(pw.Product)
warehouse := warehouseDTO.ToWarehouseBaseDTO(pw.Warehouse)
product := productDTO.ToProductRelationDTO(pw.Product)
warehouse := warehouseDTO.ToWarehouseRelationDTO(pw.Warehouse)
return &ProductWarehouseDTO{
Id: pw.Id,
@@ -4,7 +4,6 @@ import (
"math"
"strconv"
flockDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
"gitlab.com/mbugroup/lti-api.git/internal/modules/production/project-flock-kandangs/dto"
service "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project-flock-kandangs/services"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project-flock-kandangs/validations"
@@ -41,18 +40,14 @@ func (u *ProjectFlockKandangController) GetAll(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusBadRequest, "page and limit must be greater than 0")
}
results, totalResults, flockMap, err := u.ProjectFlockKandangService.GetAll(c, query)
results, totalResults, err := u.ProjectFlockKandangService.GetAll(c, query)
if err != nil {
return err
}
data := make([]dto.ProjectFlockKandangListDTO, 0)
data := make([]dto.ProjectFlockKandangListDTO, 0, len(results))
for _, result := range results {
var flock *flockDTO.FlockBaseDTO
if flockMap != nil {
flock = flockMap[result.ProjectFlock.Id]
}
data = append(data, dto.ToProjectFlockKandangListDTOWithFlock(result, flock))
data = append(data, dto.ToProjectFlockKandangListDTO(result))
}
return c.Status(fiber.StatusOK).
@@ -71,14 +66,12 @@ func (u *ProjectFlockKandangController) GetAll(c *fiber.Ctx) error {
}
func (u *ProjectFlockKandangController) GetOne(c *fiber.Ctx) error {
param := c.Params("id")
id, err := strconv.Atoi(param)
id, err := strconv.Atoi(c.Params("id"))
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
}
result, availableQtys, productWarehouses, flock, err := u.ProjectFlockKandangService.GetOne(c, uint(id))
result, availableQtys, productWarehouses, err := u.ProjectFlockKandangService.GetOne(c, uint(id))
if err != nil {
return err
}
@@ -88,6 +81,6 @@ func (u *ProjectFlockKandangController) GetOne(c *fiber.Ctx) error {
Code: fiber.StatusOK,
Status: "success",
Message: "Get projectFlockKandang successfully",
Data: dto.ToProjectFlockKandangDetailDTOWithAvailableQtyAndFlock(*result, availableQtys, productWarehouses, flock),
Data: dto.ToProjectFlockKandangDetailDTOWithAvailableQty(*result, availableQtys, productWarehouses),
})
}
@@ -5,9 +5,10 @@ import (
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
approvalDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/approvals/dto"
productWarehouseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/dto"
areaDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/areas/dto"
fcrDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/dto"
flockDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
kandangDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/dto"
locationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/locations/dto"
productDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/products/dto"
warehouseDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/warehouses/dto"
@@ -18,36 +19,27 @@ import (
// === DTO Structs (ordered) ===
type ProjectFlockKandangBaseDTO struct {
type ProjectFlockKandangRelationDTO struct {
Id uint `json:"id"`
KandangId uint `json:"kandang_id"`
ProjectFlockId uint `json:"project_flock_id"`
}
type ProjectFlockDTO struct {
Id uint `json:"id"`
Name string `json:"flock_name,omitempty"`
Period int `json:"period"`
Flock *flockDTO.FlockBaseDTO `json:"flock,omitempty"`
Area *areaDTO.AreaBaseDTO `json:"area,omitempty"`
Category string `json:"category"`
Fcr *fcrDTO.FcrBaseDTO `json:"fcr,omitempty"`
Location *locationDTO.LocationBaseDTO `json:"location,omitempty"`
CreatedUser *userDTO.UserBaseDTO `json:"created_user,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type KandangDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
projectFlockDTO.ProjectFlockRelationDTO
Area *areaDTO.AreaRelationDTO `json:"area,omitempty"`
Category string `json:"category"`
Fcr *fcrDTO.FcrRelationDTO `json:"fcr,omitempty"`
Location *locationDTO.LocationRelationDTO `json:"location,omitempty"`
CreatedUser *userDTO.UserRelationDTO `json:"created_user,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type ProductWarehouseDTO struct {
Id uint `json:"id"`
Product *productDTO.ProductBaseDTO `json:"product,omitempty"`
Warehouse *warehouseDTO.WarehouseBaseDTO `json:"warehouse,omitempty"`
productWarehouseDTO.ProductWarehouseRelationDTO
Product *productDTO.ProductRelationDTO `json:"product,omitempty"`
Warehouse *warehouseDTO.WarehouseRelationDTO `json:"warehouse,omitempty"`
}
type AvailableQtyDTO struct {
@@ -56,24 +48,24 @@ type AvailableQtyDTO struct {
}
type ProjectFlockKandangListDTO struct {
ProjectFlockKandangBaseDTO
ProjectFlock *ProjectFlockDTO `json:"project_flock,omitempty"`
Kandang *KandangDTO `json:"kandang,omitempty"`
CreatedUser *userDTO.UserBaseDTO `json:"created_user,omitempty"`
CreatedAt time.Time `json:"created_at"`
Approval *approvalDTO.ApprovalBaseDTO `json:"approval,omitempty"`
ProjectFlockKandangRelationDTO
ProjectFlock *ProjectFlockDTO `json:"project_flock,omitempty"`
Kandang *kandangDTO.KandangRelationDTO `json:"kandang,omitempty"`
CreatedUser *userDTO.UserRelationDTO `json:"created_user,omitempty"`
CreatedAt time.Time `json:"created_at"`
Approval *approvalDTO.ApprovalRelationDTO `json:"approval,omitempty"`
}
type ProjectFlockKandangDetailDTO struct {
ProjectFlockKandangListDTO
Chickins []chickinDTO.ChickinBaseDTO `json:"chickins,omitempty"`
AvailableQtys []AvailableQtyDTO `json:"available_qtys,omitempty"`
Chickins []chickinDTO.ChickinRelationDTO `json:"chickins,omitempty"`
AvailableQtys []AvailableQtyDTO `json:"available_qtys,omitempty"`
}
// === Mapper Functions (ordered) ===
func ToProjectFlockKandangBaseDTO(e entity.ProjectFlockKandang) ProjectFlockKandangBaseDTO {
return ProjectFlockKandangBaseDTO{
func ToProjectFlockKandangRelationDTO(e entity.ProjectFlockKandang) ProjectFlockKandangRelationDTO {
return ProjectFlockKandangRelationDTO{
Id: e.Id,
KandangId: e.KandangId,
ProjectFlockId: e.ProjectFlockId,
@@ -86,38 +78,31 @@ func toProjectFlockDTO(pf *projectFlockDTO.ProjectFlockListDTO) *ProjectFlockDTO
}
return &ProjectFlockDTO{
Id: pf.Id,
Name: pf.FlockName,
Period: pf.Period,
Flock: pf.Flock,
Area: pf.Area,
Category: pf.Category,
Fcr: pf.Fcr,
Location: pf.Location,
CreatedUser: pf.CreatedUser,
CreatedAt: pf.CreatedAt,
UpdatedAt: pf.UpdatedAt,
ProjectFlockRelationDTO: pf.ProjectFlockRelationDTO,
Area: pf.Area,
Category: pf.Category,
Fcr: pf.Fcr,
Location: pf.Location,
CreatedUser: pf.CreatedUser,
CreatedAt: pf.CreatedAt,
UpdatedAt: pf.UpdatedAt,
}
}
func ToProjectFlockKandangDetailDTOWithAvailableQty(e entity.ProjectFlockKandang, availableQtyMap map[uint]float64, productWarehouses []entity.ProductWarehouse) ProjectFlockKandangDetailDTO {
return ToProjectFlockKandangDetailDTOWithAvailableQtyAndFlock(e, availableQtyMap, productWarehouses, nil)
}
func ToProjectFlockKandangDetailDTOWithAvailableQtyAndFlock(e entity.ProjectFlockKandang, availableQtyMap map[uint]float64, productWarehouses []entity.ProductWarehouse, flock *flockDTO.FlockBaseDTO) ProjectFlockKandangDetailDTO {
var projectFlockSummary *projectFlockDTO.ProjectFlockListDTO
if e.ProjectFlock.Id != 0 {
mapped := projectFlockDTO.ToProjectFlockListDTO(e.ProjectFlock, flock)
mapped := projectFlockDTO.ToProjectFlockListDTO(e.ProjectFlock)
projectFlockSummary = &mapped
}
listDTO := ProjectFlockKandangListDTO{
ProjectFlockKandangBaseDTO: ToProjectFlockKandangBaseDTO(e),
ProjectFlock: toProjectFlockDTO(projectFlockSummary),
Kandang: toKandangDTO(e.Kandang),
CreatedAt: e.CreatedAt,
CreatedUser: toCreatedUserDTO(e.ProjectFlock),
Approval: toApprovalDTO(e),
ProjectFlockKandangRelationDTO: ToProjectFlockKandangRelationDTO(e),
ProjectFlock: toProjectFlockDTO(projectFlockSummary),
Kandang: toKandangRelation(e.Kandang),
CreatedAt: e.CreatedAt,
CreatedUser: toCreatedUserDTO(e.ProjectFlock),
Approval: toApprovalDTO(e),
}
return ProjectFlockKandangDetailDTO{
@@ -127,30 +112,16 @@ func ToProjectFlockKandangDetailDTOWithAvailableQtyAndFlock(e entity.ProjectFloc
}
}
func toKandangDTO(kandang entity.Kandang) *KandangDTO {
func toKandangRelation(kandang entity.Kandang) *kandangDTO.KandangRelationDTO {
if kandang.Id == 0 {
return nil
}
return &KandangDTO{
Id: kandang.Id,
Name: kandang.Name,
Status: kandang.Status,
}
mapped := kandangDTO.ToKandangRelationDTO(kandang)
return &mapped
}
func toFlockDTO(flock *entity.Flock) *flockDTO.FlockBaseDTO {
if flock == nil || flock.Id == 0 {
return nil
}
return &flockDTO.FlockBaseDTO{
Id: flock.Id,
Name: flock.Name,
}
}
func toApprovalDTO(e entity.ProjectFlockKandang) *approvalDTO.ApprovalBaseDTO {
func toApprovalDTO(e entity.ProjectFlockKandang) *approvalDTO.ApprovalRelationDTO {
if e.LatestApproval != nil {
mapped := approvalDTO.ToApprovalDTO(*e.LatestApproval)
return &mapped
@@ -159,23 +130,19 @@ func toApprovalDTO(e entity.ProjectFlockKandang) *approvalDTO.ApprovalBaseDTO {
}
func ToProjectFlockKandangListDTO(e entity.ProjectFlockKandang) ProjectFlockKandangListDTO {
return ToProjectFlockKandangListDTOWithFlock(e, nil)
}
func ToProjectFlockKandangListDTOWithFlock(e entity.ProjectFlockKandang, flock *flockDTO.FlockBaseDTO) ProjectFlockKandangListDTO {
var projectFlockSummary *projectFlockDTO.ProjectFlockListDTO
if e.ProjectFlock.Id != 0 {
mapped := projectFlockDTO.ToProjectFlockListDTOWithFlock(e.ProjectFlock, flock)
mapped := projectFlockDTO.ToProjectFlockListDTO(e.ProjectFlock)
projectFlockSummary = &mapped
}
return ProjectFlockKandangListDTO{
ProjectFlockKandangBaseDTO: ToProjectFlockKandangBaseDTO(e),
ProjectFlock: toProjectFlockDTO(projectFlockSummary),
Kandang: toKandangDTO(e.Kandang),
CreatedAt: e.CreatedAt,
CreatedUser: toCreatedUserDTO(e.ProjectFlock),
Approval: toApprovalDTO(e),
ProjectFlockKandangRelationDTO: ToProjectFlockKandangRelationDTO(e),
ProjectFlock: toProjectFlockDTO(projectFlockSummary),
Kandang: toKandangRelation(e.Kandang),
CreatedAt: e.CreatedAt,
CreatedUser: toCreatedUserDTO(e.ProjectFlock),
Approval: toApprovalDTO(e),
}
}
@@ -187,12 +154,12 @@ func ToProjectFlockKandangListDTOs(e []entity.ProjectFlockKandang) []ProjectFloc
return result
}
func toCreatedUserDTO(pf entity.ProjectFlock) *userDTO.UserBaseDTO {
func toCreatedUserDTO(pf entity.ProjectFlock) *userDTO.UserRelationDTO {
if pf.CreatedUser.Id != 0 {
mapped := userDTO.ToUserBaseDTO(pf.CreatedUser)
mapped := userDTO.ToUserRelationDTO(pf.CreatedUser)
return &mapped
} else if pf.CreatedBy != 0 {
return &userDTO.UserBaseDTO{
return &userDTO.UserRelationDTO{
Id: pf.CreatedBy,
IdUser: int64(pf.CreatedBy),
}
@@ -200,14 +167,14 @@ func toCreatedUserDTO(pf entity.ProjectFlock) *userDTO.UserBaseDTO {
return nil
}
func toChickinDTOs(chickins []entity.ProjectChickin) []chickinDTO.ChickinBaseDTO {
func toChickinDTOs(chickins []entity.ProjectChickin) []chickinDTO.ChickinRelationDTO {
if len(chickins) == 0 {
return nil
}
result := make([]chickinDTO.ChickinBaseDTO, len(chickins))
result := make([]chickinDTO.ChickinRelationDTO, len(chickins))
for i, ch := range chickins {
result[i] = chickinDTO.ToChickinBaseDTO(ch)
result[i] = chickinDTO.ToChickinRelationDTO(ch)
}
return result
}
@@ -255,14 +222,23 @@ func ToProductWarehouseDTO(pw *entity.ProductWarehouse) *ProductWarehouseDTO {
return nil
}
chickinPwDTO := chickinDTO.ToProductWarehouseDTO(pw)
if chickinPwDTO == nil {
return nil
base := productWarehouseDTO.ToProductWarehouseRelationDTO(*pw)
var product *productDTO.ProductRelationDTO
if pw.Product.Id != 0 {
mapped := productDTO.ToProductRelationDTO(pw.Product)
product = &mapped
}
var warehouse *warehouseDTO.WarehouseRelationDTO
if pw.Warehouse.Id != 0 {
mapped := warehouseDTO.ToWarehouseRelationDTO(pw.Warehouse)
warehouse = &mapped
}
return &ProductWarehouseDTO{
Id: chickinPwDTO.Id,
Product: chickinPwDTO.Product,
Warehouse: chickinPwDTO.Warehouse,
ProductWarehouseRelationDTO: base,
Product: product,
Warehouse: warehouse,
}
}
@@ -13,7 +13,6 @@ import (
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
rProductWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
rFlock "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/repositories"
rWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/master/warehouses/repositories"
"gitlab.com/mbugroup/lti-api.git/internal/utils"
@@ -29,7 +28,6 @@ func (ProjectFlockKandangModule) RegisterRoutes(router fiber.Router, db *gorm.DB
userRepo := rUser.NewUserRepository(db)
warehouseRepo := rWarehouse.NewWarehouseRepository(db)
productWarehouseRepo := rProductWarehouse.NewProductWarehouseRepository(db)
flockRepo := rFlock.NewFlockRepository(db)
approvalRepo := commonRepo.NewApprovalRepository(db)
approvalService := commonSvc.NewApprovalService(approvalRepo)
@@ -38,7 +36,7 @@ func (ProjectFlockKandangModule) RegisterRoutes(router fiber.Router, db *gorm.DB
panic(fmt.Sprintf("failed to register project flock kandang approval workflow: %v", err))
}
projectFlockKandangService := sProjectFlockKandang.NewProjectFlockKandangService(projectFlockKandangRepo, approvalService, warehouseRepo, productWarehouseRepo, projectFlockPopulationRepo, flockRepo, validate)
projectFlockKandangService := sProjectFlockKandang.NewProjectFlockKandangService(projectFlockKandangRepo, approvalService, warehouseRepo, productWarehouseRepo, projectFlockPopulationRepo, validate)
userService := sUser.NewUserService(userRepo, validate)
ProjectFlockKandangRoutes(router, userService, projectFlockKandangService)
@@ -6,12 +6,9 @@ import (
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
rProductWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
flockDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
flockRepository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/repositories"
rWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/master/warehouses/repositories"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project-flock-kandangs/validations"
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/repositories"
pfutils "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/utils"
"gitlab.com/mbugroup/lti-api.git/internal/utils"
"github.com/go-playground/validator/v10"
@@ -21,8 +18,8 @@ import (
)
type ProjectFlockKandangService interface {
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlockKandang, int64, map[uint]*flockDTO.FlockBaseDTO, error)
GetOne(ctx *fiber.Ctx, id uint) (*entity.ProjectFlockKandang, map[uint]float64, []entity.ProductWarehouse, *flockDTO.FlockBaseDTO, error)
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlockKandang, int64, error)
GetOne(ctx *fiber.Ctx, id uint) (*entity.ProjectFlockKandang, map[uint]float64, []entity.ProductWarehouse, error)
}
// Note: map[uint]float64 adalah mapping dari ProductWarehouse ID ke calculated available quantity
@@ -35,10 +32,9 @@ type projectFlockKandangService struct {
WarehouseRepo rWarehouse.WarehouseRepository
ProductWarehouseRepo rProductWarehouse.ProductWarehouseRepository
PopulationRepo repository.ProjectFlockPopulationRepository
FlockRepo flockRepository.FlockRepository
}
func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository, approvalSvc commonSvc.ApprovalService, warehouseRepo rWarehouse.WarehouseRepository, productWarehouseRepo rProductWarehouse.ProductWarehouseRepository, populationRepo repository.ProjectFlockPopulationRepository, flockRepo flockRepository.FlockRepository, validate *validator.Validate) ProjectFlockKandangService {
func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository, approvalSvc commonSvc.ApprovalService, warehouseRepo rWarehouse.WarehouseRepository, productWarehouseRepo rProductWarehouse.ProductWarehouseRepository, populationRepo repository.ProjectFlockPopulationRepository, validate *validator.Validate) ProjectFlockKandangService {
return &projectFlockKandangService{
Log: utils.Log,
Validate: validate,
@@ -47,13 +43,12 @@ func NewProjectFlockKandangService(repo repository.ProjectFlockKandangRepository
WarehouseRepo: warehouseRepo,
ProductWarehouseRepo: productWarehouseRepo,
PopulationRepo: populationRepo,
FlockRepo: flockRepo,
}
}
func (s projectFlockKandangService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlockKandang, int64, map[uint]*flockDTO.FlockBaseDTO, error) {
func (s projectFlockKandangService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlockKandang, int64, error) {
if err := s.Validate.Struct(params); err != nil {
return nil, 0, nil, err
return nil, 0, err
}
offset := (params.Page - 1) * params.Limit
@@ -62,7 +57,7 @@ func (s projectFlockKandangService) GetAll(c *fiber.Ctx, params *validation.Quer
if err != nil {
s.Log.Errorf("Failed to get projectFlockKandangs: %+v", err)
return nil, 0, nil, err
return nil, 0, err
}
if s.ApprovalSvc != nil {
@@ -85,35 +80,16 @@ func (s projectFlockKandangService) GetAll(c *fiber.Ctx, params *validation.Quer
}
}
flockMap := make(map[uint]*flockDTO.FlockBaseDTO)
for i := range projectFlockKandangs {
if projectFlockKandangs[i].ProjectFlock.Id != 0 {
baseName := pfutils.DeriveBaseName(projectFlockKandangs[i].ProjectFlock.FlockName)
if baseName != "" {
flock, err := s.FlockRepo.GetByName(c.Context(), baseName)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
s.Log.Warnf("Failed to fetch flock %q: %+v", baseName, err)
} else if flock != nil {
flockMap[projectFlockKandangs[i].ProjectFlock.Id] = &flockDTO.FlockBaseDTO{
Id: flock.Id,
Name: flock.Name,
}
}
}
}
}
return projectFlockKandangs, total, flockMap, nil
return projectFlockKandangs, total, nil
}
func (s projectFlockKandangService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectFlockKandang, map[uint]float64, []entity.ProductWarehouse, *flockDTO.FlockBaseDTO, error) {
func (s projectFlockKandangService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectFlockKandang, map[uint]float64, []entity.ProductWarehouse, error) {
projectFlockKandang, err := s.Repository.GetByID(c.Context(), id)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil, nil, nil, fiber.NewError(fiber.StatusNotFound, "ProjectFlockKandang not found")
return nil, nil, nil, fiber.NewError(fiber.StatusNotFound, "ProjectFlockKandang not found")
}
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, err
}
if len(projectFlockKandang.Chickins) > 0 && s.ApprovalSvc != nil {
@@ -147,23 +123,8 @@ func (s projectFlockKandangService) GetOne(c *fiber.Ctx, id uint) (*entity.Proje
productWarehouses = []entity.ProductWarehouse{}
}
}
var flockResult *flockDTO.FlockBaseDTO
if projectFlockKandang.ProjectFlock.Id != 0 {
baseName := pfutils.DeriveBaseName(projectFlockKandang.ProjectFlock.FlockName)
if baseName != "" {
flock, err := s.FlockRepo.GetByName(c.Context(), baseName)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
s.Log.Warnf("Failed to fetch flock %q: %+v", baseName, err)
} else if flock != nil {
flockResult = &flockDTO.FlockBaseDTO{
Id: flock.Id,
Name: flock.Name,
}
}
}
}
return projectFlockKandang, availableQtyMap, productWarehouses, flockResult, nil
return projectFlockKandang, availableQtyMap, productWarehouses, nil
}
func (s projectFlockKandangService) getAvailableQuantities(c *fiber.Ctx, projectFlockKandang *entity.ProjectFlockKandang) (map[uint]float64, error) {
@@ -7,7 +7,6 @@ import (
"strconv"
"strings"
flockDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
"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"
@@ -85,18 +84,20 @@ func (u *ProjectflockController) GetAll(c *fiber.Ctx) error {
query.KandangIds = ids
}
result, totalResults, flockMap, err := u.ProjectflockService.GetAll(c, query)
result, totalResults, _, err := u.ProjectflockService.GetAll(c, query)
if err != nil {
return err
}
data := make([]dto.ProjectFlockListDTO, 0)
for _, projectFlock := range result {
var flock *flockDTO.FlockBaseDTO
if flockMap != nil {
flock = flockMap[projectFlock.Id]
var periodMap map[uint]int
if len(result) > 0 {
ids := make([]uint, len(result))
for i, item := range result {
ids[i] = item.Id
}
if periods, err := u.ProjectflockService.GetProjectPeriods(c, ids); err == nil {
periodMap = periods
}
data = append(data, dto.ToProjectFlockListDTO(projectFlock, flock))
}
return c.Status(fiber.StatusOK).
@@ -110,7 +111,7 @@ func (u *ProjectflockController) GetAll(c *fiber.Ctx) error {
TotalPages: int64(math.Ceil(float64(totalResults) / float64(query.Limit))),
TotalResults: totalResults,
},
Data: data,
Data: dto.ToProjectFlockListDTOsWithPeriods(result, periodMap),
})
}
@@ -122,17 +123,24 @@ func (u *ProjectflockController) GetOne(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusBadRequest, "Invalid Id")
}
result, flock, err := u.ProjectflockService.GetOne(c, uint(id))
result, _, err := u.ProjectflockService.GetOne(c, uint(id))
if err != nil {
return err
}
var period int
if periods, err := u.ProjectflockService.GetProjectPeriods(c, []uint{uint(id)}); err == nil {
if p, ok := periods[uint(id)]; ok {
period = p
}
}
return c.Status(fiber.StatusOK).
JSON(response.Success{
Code: fiber.StatusOK,
Status: "success",
Message: "Get projectflock successfully",
Data: dto.ToProjectFlockListDTO(*result, flock),
Data: dto.ToProjectFlockListDTOWithPeriod(*result, period),
})
}
@@ -153,7 +161,7 @@ func (u *ProjectflockController) CreateOne(c *fiber.Ctx) error {
Code: fiber.StatusCreated,
Status: "success",
Message: "Create projectflock successfully",
Data: dto.ToProjectFlockListDTO(*result, nil),
Data: dto.ToProjectFlockListDTO(*result),
})
}
@@ -180,7 +188,7 @@ func (u *ProjectflockController) UpdateOne(c *fiber.Ctx) error {
Code: fiber.StatusOK,
Status: "success",
Message: "Update projectflock successfully",
Data: dto.ToProjectFlockListDTO(*result, nil),
Data: dto.ToProjectFlockListDTO(*result),
})
}
@@ -219,11 +227,29 @@ func (u *ProjectflockController) Approval(c *fiber.Ctx) error {
data interface{}
message = "Submit projectflock approval successfully"
)
var periodMap map[uint]int
if len(results) > 0 {
ids := make([]uint, len(results))
for i, item := range results {
ids[i] = item.Id
}
if periods, err := u.ProjectflockService.GetProjectPeriods(c, ids); err == nil {
periodMap = periods
}
}
if len(results) == 1 {
data = dto.ToProjectFlockListDTO(results[0], nil)
period := 0
if periodMap != nil {
if p, ok := periodMap[results[0].Id]; ok {
period = p
}
}
data = dto.ToProjectFlockListDTOWithPeriod(results[0], period)
} else {
message = "Submit projectflock approvals successfully"
data = dto.ToProjectFlockListDTOs(results)
data = dto.ToProjectFlockListDTOsWithPeriods(results, periodMap)
}
return c.Status(fiber.StatusOK).
@@ -236,25 +262,32 @@ func (u *ProjectflockController) Approval(c *fiber.Ctx) error {
}
func (u *ProjectflockController) GetFlockPeriodSummary(c *fiber.Ctx) error {
param := c.Params("project_flock_kandang_id")
param := c.Params("location_id")
id, err := strconv.Atoi(param)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid project_flock_kandang_id")
return fiber.NewError(fiber.StatusBadRequest, "Invalid location_id")
}
summary, err := u.ProjectflockService.GetFlockPeriodSummary(c, uint(id))
summaries, err := u.ProjectflockService.GetFlockPeriodSummary(c, uint(id))
if err != nil {
return err
}
responseBody := dto.ToFlockPeriodSummaryDTO(summary.Flock, summary.NextPeriod)
responseBody := make([]dto.KandangPeriodSummaryDTO, 0, len(summaries))
for _, item := range summaries {
responseBody = append(responseBody, dto.KandangPeriodSummaryDTO{
Id: item.Id,
Name: item.Name,
Period: item.Period,
})
}
return c.Status(fiber.StatusOK).
JSON(response.Success{
Code: fiber.StatusOK,
Status: "success",
Message: "Get flock period summary successfully",
Message: "Get kandang period summary successfully",
Data: responseBody,
})
}
@@ -7,7 +7,6 @@ import (
approvalDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/approvals/dto"
areaDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/areas/dto"
fcrDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/dto"
flockDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
kandangDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/dto"
locationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/locations/dto"
@@ -17,44 +16,45 @@ import (
approvalutils "gitlab.com/mbugroup/lti-api.git/internal/utils/approvals"
)
type ProjectFlockBaseDTO struct {
type ProjectFlockRelationDTO struct {
Id uint `json:"id"`
Period int `json:"period"`
FlockName string `json:"flock_name"`
}
type ProjectFlockListDTO struct {
ProjectFlockBaseDTO
Flock *flockDTO.FlockBaseDTO `json:"flock,omitempty"`
Area *areaDTO.AreaBaseDTO `json:"area,omitempty"`
Category string `json:"category"`
Fcr *fcrDTO.FcrBaseDTO `json:"fcr,omitempty"`
Location *locationDTO.LocationBaseDTO `json:"location,omitempty"`
Kandangs []KandangWithProjectFlockIdDTO `json:"kandangs,omitempty"`
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Approval approvalDTO.ApprovalBaseDTO `json:"approval"`
ProjectFlockRelationDTO
Area *areaDTO.AreaRelationDTO `json:"area,omitempty"`
Category string `json:"category"`
Fcr *fcrDTO.FcrRelationDTO `json:"fcr,omitempty"`
Location *locationDTO.LocationRelationDTO `json:"location,omitempty"`
Kandangs []KandangWithProjectFlockIdDTO `json:"kandangs,omitempty"`
CreatedUser *userDTO.UserRelationDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Approval approvalDTO.ApprovalRelationDTO `json:"approval"`
}
type KandangWithProjectFlockIdDTO struct {
kandangDTO.KandangBaseDTO
kandangDTO.KandangRelationDTO
ProjectFlockKandangId uint `json:"project_flock_kandang_id"`
Period int `json:"period"`
}
type ProjectFlockDetailDTO struct {
ProjectFlockListDTO
}
type FlockPeriodDTO struct {
Flock flockDTO.FlockBaseDTO `json:"flock"`
NextPeriod int `json:"next_period"`
type KandangPeriodSummaryDTO struct {
Id uint `json:"id"`
Name string `json:"name"`
Period int `json:"period"`
}
func ToProjectFlockListDTO(e entity.ProjectFlock, flock *flockDTO.FlockBaseDTO) ProjectFlockListDTO {
var createdUser *userDTO.UserBaseDTO
func ToProjectFlockListDTOWithPeriod(e entity.ProjectFlock, period int) ProjectFlockListDTO {
var createdUser *userDTO.UserRelationDTO
if e.CreatedUser.Id != 0 {
mapped := userDTO.ToUserBaseDTO(e.CreatedUser)
mapped := userDTO.ToUserRelationDTO(e.CreatedUser)
createdUser = &mapped
}
@@ -63,43 +63,43 @@ func ToProjectFlockListDTO(e entity.ProjectFlock, flock *flockDTO.FlockBaseDTO)
kandangSummaries = make([]KandangWithProjectFlockIdDTO, len(e.Kandangs))
for i, kandang := range e.Kandangs {
var pfkId uint
var (
pfkId uint
period int
)
for _, kh := range e.KandangHistory {
if kh.KandangId == kandang.Id {
pfkId = kh.Id
period = kh.Period
break
}
}
kandangSummaries[i] = KandangWithProjectFlockIdDTO{
KandangBaseDTO: kandangDTO.ToKandangBaseDTO(kandang),
KandangRelationDTO: kandangDTO.ToKandangRelationDTO(kandang),
ProjectFlockKandangId: pfkId,
Period: period,
}
}
}
var areaSummary *areaDTO.AreaBaseDTO
var areaSummary *areaDTO.AreaRelationDTO
if e.Area.Id != 0 {
mapped := areaDTO.ToAreaBaseDTO(e.Area)
mapped := areaDTO.ToAreaRelationDTO(e.Area)
areaSummary = &mapped
}
var fcrSummary *fcrDTO.FcrBaseDTO
var fcrSummary *fcrDTO.FcrRelationDTO
if e.Fcr.Id != 0 {
mapped := fcrDTO.ToFcrBaseDTO(e.Fcr)
mapped := fcrDTO.ToFcrRelationDTO(e.Fcr)
fcrSummary = &mapped
}
var locationSummary *locationDTO.LocationBaseDTO
var locationSummary *locationDTO.LocationRelationDTO
if e.Location.Id != 0 {
mapped := locationDTO.ToLocationBaseDTO(e.Location)
mapped := locationDTO.ToLocationRelationDTO(e.Location)
locationSummary = &mapped
}
var flockSummary *flockDTO.FlockBaseDTO
if flock != nil && flock.Id != 0 {
flockSummary = flock
}
latestApproval := defaultProjectFlockLatestApproval(e)
if e.LatestApproval != nil {
snapshot := approvalDTO.ToApprovalDTO(*e.LatestApproval)
@@ -107,57 +107,53 @@ func ToProjectFlockListDTO(e entity.ProjectFlock, flock *flockDTO.FlockBaseDTO)
}
return ProjectFlockListDTO{
ProjectFlockBaseDTO: createProjectFlockBaseDTO(e),
Flock: flockSummary,
Area: areaSummary,
Kandangs: kandangSummaries,
Category: e.Category,
Fcr: fcrSummary,
Location: locationSummary,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
CreatedUser: createdUser,
Approval: latestApproval,
ProjectFlockRelationDTO: createProjectFlockRelationDTO(e, period),
Area: areaSummary,
Kandangs: kandangSummaries,
Category: e.Category,
Fcr: fcrSummary,
Location: locationSummary,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
CreatedUser: createdUser,
Approval: latestApproval,
}
}
func ToProjectFlockListDTOWithFlock(e entity.ProjectFlock, flock *flockDTO.FlockBaseDTO) ProjectFlockListDTO {
return ToProjectFlockListDTO(e, flock)
}
func ToProjectFlockListDTOs(items []entity.ProjectFlock) []ProjectFlockListDTO {
result := make([]ProjectFlockListDTO, len(items))
for i, item := range items {
result[i] = ToProjectFlockListDTO(item, nil)
result[i] = ToProjectFlockListDTOWithPeriod(item, 0)
}
return result
}
func ToProjectFlockListDTOsWithFlocks(items []entity.ProjectFlock, flocks map[uint]*entity.Flock) []ProjectFlockListDTO {
func ToProjectFlockListDTO(e entity.ProjectFlock) ProjectFlockListDTO {
return ToProjectFlockListDTOWithPeriod(e, 0)
}
func ToProjectFlockListDTOsWithPeriods(items []entity.ProjectFlock, periods map[uint]int) []ProjectFlockListDTO {
result := make([]ProjectFlockListDTO, len(items))
for i, item := range items {
var flock *flockDTO.FlockBaseDTO
if flocks != nil {
if f := flocks[item.Id]; f != nil {
flock = &flockDTO.FlockBaseDTO{
Id: f.Id,
Name: f.Name,
}
p := 0
if periods != nil {
if v, ok := periods[item.Id]; ok {
p = v
}
}
result[i] = ToProjectFlockListDTOWithFlock(item, flock)
result[i] = ToProjectFlockListDTOWithPeriod(item, p)
}
return result
}
func ToProjectFlockDetailDTO(e entity.ProjectFlock, flock *flockDTO.FlockBaseDTO) ProjectFlockDetailDTO {
func ToProjectFlockDetailDTO(e entity.ProjectFlock) ProjectFlockDetailDTO {
return ProjectFlockDetailDTO{
ProjectFlockListDTO: ToProjectFlockListDTO(e, flock),
ProjectFlockListDTO: ToProjectFlockListDTOWithPeriod(e, 0),
}
}
func defaultProjectFlockLatestApproval(e entity.ProjectFlock) approvalDTO.ApprovalBaseDTO {
result := approvalDTO.ApprovalBaseDTO{}
func defaultProjectFlockLatestApproval(e entity.ProjectFlock) approvalDTO.ApprovalRelationDTO {
result := approvalDTO.ApprovalRelationDTO{}
step := utils.ProjectFlockStepPengajuan
if step > 0 {
@@ -170,9 +166,9 @@ func defaultProjectFlockLatestApproval(e entity.ProjectFlock) approvalDTO.Approv
}
if e.CreatedUser.Id != 0 {
result.ActionBy = userDTO.ToUserBaseDTO(e.CreatedUser)
result.ActionBy = userDTO.ToUserRelationDTO(e.CreatedUser)
} else if e.CreatedBy != 0 {
result.ActionBy = userDTO.UserBaseDTO{
result.ActionBy = userDTO.UserRelationDTO{
Id: e.CreatedBy,
IdUser: int64(e.CreatedBy),
}
@@ -181,24 +177,10 @@ func defaultProjectFlockLatestApproval(e entity.ProjectFlock) approvalDTO.Approv
return result
}
func createProjectFlockBaseDTO(e entity.ProjectFlock) ProjectFlockBaseDTO {
return ProjectFlockBaseDTO{
func createProjectFlockRelationDTO(e entity.ProjectFlock, period int) ProjectFlockRelationDTO {
return ProjectFlockRelationDTO{
Id: e.Id,
Period: e.Period,
Period: period,
FlockName: e.FlockName,
}
}
func ToFlockSummaryDTO(e entity.Flock) flockDTO.FlockBaseDTO {
return flockDTO.FlockBaseDTO{
Id: e.Id,
Name: e.Name,
}
}
func ToFlockPeriodSummaryDTO(flock entity.Flock, next int) FlockPeriodDTO {
return FlockPeriodDTO{
Flock: ToFlockSummaryDTO(flock),
NextPeriod: next,
}
}
@@ -4,43 +4,40 @@ import (
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
areaDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/areas/dto"
fcrDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/fcrs/dto"
flockDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
kandangDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/kandangs/dto"
locationDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/locations/dto"
pfutils "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/utils"
userDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/users/dto"
)
type KandangWithPivotDTO struct {
kandangDTO.KandangBaseDTO
kandangDTO.KandangRelationDTO
AvailableQuantity float64 `json:"available_quantity"`
}
type ProjectFlockWithPivotDTO struct {
ProjectFlockBaseDTO
Flock *flockDTO.FlockBaseDTO `json:"flock,omitempty"`
Area *areaDTO.AreaBaseDTO `json:"area,omitempty"`
Category string `json:"category"`
Fcr *fcrDTO.FcrBaseDTO `json:"fcr,omitempty"`
Location *locationDTO.LocationBaseDTO `json:"location,omitempty"`
Kandangs []KandangWithPivotDTO `json:"kandangs,omitempty"`
CreatedUser *userDTO.UserBaseDTO `json:"created_user,omitempty"`
ProjectFlockRelationDTO
Area *areaDTO.AreaRelationDTO `json:"area,omitempty"`
Category string `json:"category"`
Fcr *fcrDTO.FcrRelationDTO `json:"fcr,omitempty"`
Location *locationDTO.LocationRelationDTO `json:"location,omitempty"`
Kandangs []KandangWithPivotDTO `json:"kandangs,omitempty"`
CreatedUser *userDTO.UserRelationDTO `json:"created_user,omitempty"`
}
type ProjectFlockKandangDTO struct {
Id uint `json:"id"`
ProjectFlockKandangId uint `json:"project_flock_kandang_id"`
ProjectFlockId uint `json:"project_flock_id"`
KandangId uint `json:"kandang_id"`
Kandang *kandangDTO.KandangBaseDTO `json:"kandang,omitempty"`
ProjectFlock *ProjectFlockWithPivotDTO `json:"project_flock,omitempty"`
AvailableQuantity float64 `json:"available_quantity"`
Id uint `json:"id"`
ProjectFlockKandangId uint `json:"project_flock_kandang_id"`
ProjectFlockId uint `json:"project_flock_id"`
KandangId uint `json:"kandang_id"`
Kandang *kandangDTO.KandangRelationDTO `json:"kandang,omitempty"`
ProjectFlock *ProjectFlockWithPivotDTO `json:"project_flock,omitempty"`
AvailableQuantity float64 `json:"available_quantity"`
}
func ToProjectFlockKandangDTO(e entity.ProjectFlockKandang) ProjectFlockKandangDTO {
var kandang *kandangDTO.KandangBaseDTO
var kandang *kandangDTO.KandangRelationDTO
if e.Kandang.Id != 0 {
mapped := kandangDTO.ToKandangBaseDTO(e.Kandang)
mapped := kandangDTO.ToKandangRelationDTO(e.Kandang)
kandang = &mapped
}
@@ -48,40 +45,36 @@ func ToProjectFlockKandangDTO(e entity.ProjectFlockKandang) ProjectFlockKandangD
if e.ProjectFlock.Id != 0 {
pfLocal := ProjectFlockWithPivotDTO{
ProjectFlockBaseDTO: ProjectFlockBaseDTO{
ProjectFlockRelationDTO: ProjectFlockRelationDTO{
Id: e.ProjectFlock.Id,
Period: e.ProjectFlock.Period,
Period: e.Period,
FlockName: e.ProjectFlock.FlockName,
},
Category: e.ProjectFlock.Category,
}
if base := pfutils.DeriveBaseName(e.ProjectFlock.FlockName); base != "" {
summary := flockDTO.FlockBaseDTO{Id: 0, Name: base}
pfLocal.Flock = &summary
}
if e.ProjectFlock.Area.Id != 0 {
mapped := areaDTO.ToAreaBaseDTO(e.ProjectFlock.Area)
mapped := areaDTO.ToAreaRelationDTO(e.ProjectFlock.Area)
pfLocal.Area = &mapped
}
if e.ProjectFlock.Fcr.Id != 0 {
mapped := fcrDTO.ToFcrBaseDTO(e.ProjectFlock.Fcr)
mapped := fcrDTO.ToFcrRelationDTO(e.ProjectFlock.Fcr)
pfLocal.Fcr = &mapped
}
if e.ProjectFlock.Location.Id != 0 {
mapped := locationDTO.ToLocationBaseDTO(e.ProjectFlock.Location)
mapped := locationDTO.ToLocationRelationDTO(e.ProjectFlock.Location)
pfLocal.Location = &mapped
}
if e.ProjectFlock.CreatedUser.Id != 0 {
mapped := userDTO.ToUserBaseDTO(e.ProjectFlock.CreatedUser)
mapped := userDTO.ToUserRelationDTO(e.ProjectFlock.CreatedUser)
pfLocal.CreatedUser = &mapped
}
for _, k := range e.ProjectFlock.Kandangs {
kb := kandangDTO.ToKandangBaseDTO(k)
kb := kandangDTO.ToKandangRelationDTO(k)
pfLocal.Kandangs = append(pfLocal.Kandangs, KandangWithPivotDTO{
KandangBaseDTO: kb,
AvailableQuantity: 0,
KandangRelationDTO: kb,
AvailableQuantity: 0,
})
}
@@ -2,7 +2,6 @@ package repository
import (
"context"
"errors"
"fmt"
"strings"
@@ -10,17 +9,12 @@ import (
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/validations"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const baseNameExpression = "LOWER(TRIM(regexp_replace(flock_name, '\\\\s+\\\\d+(\\\\s+\\\\d+)*$', '', 'g')))"
type ProjectflockRepository interface {
repository.BaseRepository[entity.ProjectFlock]
GetAllByBaseName(ctx context.Context, baseName string) ([]entity.ProjectFlock, error)
GetActiveByBaseName(ctx context.Context, baseName string) (*entity.ProjectFlock, error)
GetMaxPeriodByBaseName(ctx context.Context, baseName string) (int, error)
GetNextSequenceForBase(ctx context.Context, baseName string) (int, error)
GetAllWithFilters(ctx context.Context, offset, limit int, params *validation.Query) ([]entity.ProjectFlock, int64, error)
WithDefaultRelations() func(*gorm.DB) *gorm.DB
ExistsByFlockName(ctx context.Context, flockName string, excludeID *uint) (bool, error)
@@ -39,65 +33,6 @@ func NewProjectflockRepository(db *gorm.DB) ProjectflockRepository {
}
}
func (r *ProjectflockRepositoryImpl) GetAllByBaseName(ctx context.Context, baseName string) ([]entity.ProjectFlock, error) {
var records []entity.ProjectFlock
if err := r.DB().WithContext(ctx).
Unscoped().
Where(baseNameExpression+" = LOWER(?)", baseName).
Order("period ASC").
Find(&records).Error; err != nil {
return nil, err
}
return records, nil
}
func (r *ProjectflockRepositoryImpl) GetActiveByBaseName(ctx context.Context, baseName string) (*entity.ProjectFlock, error) {
var record entity.ProjectFlock
err := r.DB().WithContext(ctx).
Where(baseNameExpression+" = LOWER(?)", baseName).
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) GetMaxPeriodByBaseName(ctx context.Context, baseName string) (int, error) {
var max int
if err := r.DB().WithContext(ctx).
Model(&entity.ProjectFlock{}).
Where(baseNameExpression+" = LOWER(?)", baseName).
Select("COALESCE(MAX(period), 0)").
Scan(&max).Error; err != nil {
return 0, err
}
return max, nil
}
func (r *ProjectflockRepositoryImpl) GetNextSequenceForBase(ctx context.Context, baseName string) (int, error) {
var payload struct {
Period int
}
if err := r.DB().WithContext(ctx).
Model(&entity.ProjectFlock{}).
Where(baseNameExpression+" = LOWER(?)", baseName).
Clauses(clause.Locking{Strength: "UPDATE"}).
Order("period DESC").
Limit(1).
Select("period").
Scan(&payload).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return 1, nil
}
return 0, err
}
return payload.Period + 1, nil
}
func (r *ProjectflockRepositoryImpl) GetAllWithFilters(ctx context.Context, offset, limit int, params *validation.Query) ([]entity.ProjectFlock, int64, error) {
return r.GetAll(ctx, offset, limit, func(db *gorm.DB) *gorm.DB {
db = r.withDefaultRelations(db)
@@ -137,7 +72,13 @@ func (r *ProjectflockRepositoryImpl) applyQueryFilters(db *gorm.DB, params *vali
db = db.Where("project_flocks.location_id = ?", params.LocationId)
}
if params.Period > 0 {
db = db.Where("project_flocks.period = ?", params.Period)
db = db.Where(`
EXISTS (
SELECT 1
FROM project_flock_kandangs pfk
WHERE pfk.project_flock_id = project_flocks.id
AND pfk.period = ?
)`, params.Period)
}
if len(params.KandangIds) > 0 {
db = db.Where(`
@@ -184,10 +125,15 @@ func (r *ProjectflockRepositoryImpl) applySearchFilters(db *gorm.DB, rawSearch s
OR LOWER(created_users.email) LIKE ?
OR LOWER(project_flocks.flock_name) LIKE ?
OR LOWER(TRIM(regexp_replace(project_flocks.flock_name, '\\s+\\d+(\\s+\\d+)*$', '', 'g'))) LIKE ?
OR LOWER(CAST(project_flocks.period AS TEXT)) LIKE ?
OR EXISTS (
SELECT 1 FROM project_flock_kandangs
WHERE project_flock_kandangs.project_flock_id = project_flocks.id
AND LOWER(CAST(project_flock_kandangs.period AS TEXT)) LIKE ?
)
OR EXISTS (
SELECT 1 FROM kandangs
WHERE kandangs.project_flock_id = project_flocks.id
JOIN project_flock_kandangs pfk ON pfk.kandang_id = kandangs.id
WHERE pfk.project_flock_id = project_flocks.id
AND LOWER(kandangs.name) LIKE ?
)
`,
@@ -241,7 +187,7 @@ func (r *ProjectflockRepositoryImpl) buildOrderExpressions(sortBy, sortOrder str
}
case "period":
return []string{
fmt.Sprintf("project_flocks.period %s", direction),
fmt.Sprintf("(SELECT COALESCE(MAX(period), 0) FROM project_flock_kandangs pfk WHERE pfk.project_flock_id = project_flocks.id) %s", direction),
fmt.Sprintf("project_flocks.id %s", direction),
}
default:
@@ -22,6 +22,7 @@ type ProjectFlockKandangRepository interface {
HasKandangsLinkedToOtherProject(ctx context.Context, kandangIDs []uint, exceptProjectID *uint) (bool, error)
FindKandangsWithRecordings(ctx context.Context, projectFlockID uint, kandangIDs []uint) ([]entity.Kandang, error)
MaxPeriodByBaseName(ctx context.Context, baseName string) (int, error)
ProjectPeriodsByProjectIDs(ctx context.Context, projectIDs []uint) (map[uint]int, error)
WithTx(tx *gorm.DB) ProjectFlockKandangRepository
IdExists(ctx context.Context, id uint) (bool, error)
DB() *gorm.DB
@@ -304,7 +305,33 @@ func (r *projectFlockKandangRepositoryImpl) MaxPeriodByBaseName(ctx context.Cont
Table("project_flock_kandangs pfk").
Joins("JOIN project_flocks pf ON pf.id = pfk.project_flock_id").
Where(flockBaseNameExpression+" = LOWER(?)", baseName).
Select("COALESCE(MAX(pf.period), 0)").
Select("COALESCE(MAX(pfk.period), 0)").
Scan(&max).Error
return max, err
}
func (r *projectFlockKandangRepositoryImpl) ProjectPeriodsByProjectIDs(ctx context.Context, projectIDs []uint) (map[uint]int, error) {
result := make(map[uint]int)
if len(projectIDs) == 0 {
return result, nil
}
type row struct {
ProjectFlockID uint
Period int
}
var rows []row
if err := r.db.WithContext(ctx).
Table("project_flock_kandangs").
Where("project_flock_id IN ?", projectIDs).
Select("project_flock_id, COALESCE(MAX(period), 0) AS period").
Group("project_flock_id").
Scan(&rows).Error; err != nil {
return nil, err
}
for _, item := range rows {
result[item.ProjectFlockID] = item.Period
}
return result, nil
}
@@ -1,6 +1,7 @@
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"
@@ -12,12 +13,6 @@ func ProjectflockRoutes(v1 fiber.Router, u user.UserService, s projectflock.Proj
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.Use(m.Auth(u))
route.Get("/", ctrl.GetAll)
@@ -28,6 +23,6 @@ func ProjectflockRoutes(v1 fiber.Router, u user.UserService, s projectflock.Proj
route.Get("/kandangs/:project_flock_kandang_id/periods", ctrl.GetFlockPeriodSummary)
route.Get("/kandangs/lookup", ctrl.LookupProjectFlockKandang)
route.Post("/approvals", ctrl.Approval)
route.Get("/kandangs/:project_flock_kandang_id/periods", ctrl.GetFlockPeriodSummary)
route.Get("/kandangs/:location_id/periods", ctrl.GetFlockPeriodSummary)
}
@@ -10,6 +10,8 @@ import (
commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
// authmiddleware "gitlab.com/mbugroup/lti-api.git/internal/middleware"
productWarehouseRepository "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
flockDTO "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/dto"
flockRepository "gitlab.com/mbugroup/lti-api.git/internal/modules/master/flocks/repositories"
@@ -28,14 +30,15 @@ import (
)
type ProjectflockService interface {
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlock, int64, map[uint]*flockDTO.FlockBaseDTO, error)
GetOne(ctx *fiber.Ctx, id uint) (*entity.ProjectFlock, *flockDTO.FlockBaseDTO, error)
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlock, int64, map[uint]*flockDTO.FlockRelationDTO, error)
GetOne(ctx *fiber.Ctx, id uint) (*entity.ProjectFlock, *flockDTO.FlockRelationDTO, error)
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.ProjectFlock, error)
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.ProjectFlock, error)
GetAvailableDocQuantity(ctx *fiber.Ctx, kandangID uint) (float64, error)
DeleteOne(ctx *fiber.Ctx, id uint) error
GetProjectFlockKandangByProjectAndKandang(ctx *fiber.Ctx, projectFlockID uint, kandangID uint) (*entity.ProjectFlockKandang, float64, error)
GetFlockPeriodSummary(ctx *fiber.Ctx, flockID uint) (*FlockPeriodSummary, error)
GetFlockPeriodSummary(ctx *fiber.Ctx, locationID uint) ([]KandangPeriodSummary, error)
GetProjectPeriods(ctx *fiber.Ctx, projectIDs []uint) (map[uint]int, error)
Approval(ctx *fiber.Ctx, req *validation.Approve) ([]entity.ProjectFlock, error)
}
@@ -52,9 +55,10 @@ type projectflockService struct {
approvalWorkflow approvalutils.ApprovalWorkflowKey
}
type FlockPeriodSummary struct {
Flock entity.Flock
NextPeriod int
type KandangPeriodSummary struct {
Id uint
Name string
Period int
}
func NewProjectflockService(
@@ -93,7 +97,7 @@ func (s projectflockService) withRelations(db *gorm.DB) *gorm.DB {
Preload("KandangHistory.Kandang")
}
func (s projectflockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlock, int64, map[uint]*flockDTO.FlockBaseDTO, error) {
func (s projectflockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.ProjectFlock, int64, map[uint]*flockDTO.FlockRelationDTO, error) {
if err := s.Validate.Struct(params); err != nil {
return nil, 0, nil, err
}
@@ -121,7 +125,7 @@ func (s projectflockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]e
}
latestMap, err := s.ApprovalSvc.LatestByTargets(c.Context(), s.approvalWorkflow, ids, func(db *gorm.DB) *gorm.DB {
return db.Preload("ActionUser")
return s.withRelations(db)
})
if err != nil {
s.Log.Warnf("Unable to load latest approvals for projectflocks: %+v", err)
@@ -134,7 +138,7 @@ func (s projectflockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]e
}
}
flockMap := make(map[uint]*flockDTO.FlockBaseDTO)
flockMap := make(map[uint]*flockDTO.FlockRelationDTO)
for i := range projectflocks {
if projectflocks[i].FlockName != "" {
baseName := pfutils.DeriveBaseName(projectflocks[i].FlockName)
@@ -143,7 +147,7 @@ func (s projectflockService) GetAll(c *fiber.Ctx, params *validation.Query) ([]e
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
s.Log.Warnf("Failed to fetch flock %q: %+v", baseName, err)
} else if flock != nil {
flockMap[projectflocks[i].Id] = &flockDTO.FlockBaseDTO{
flockMap[projectflocks[i].Id] = &flockDTO.FlockRelationDTO{
Id: flock.Id,
Name: flock.Name,
}
@@ -167,7 +171,7 @@ func (s projectflockService) getOneEntityOnly(c *fiber.Ctx, id uint) (*entity.Pr
if s.ApprovalSvc != nil {
approvals, err := s.ApprovalSvc.ListByTarget(c.Context(), s.approvalWorkflow, id, func(db *gorm.DB) *gorm.DB {
return db.Preload("ActionUser")
return s.withRelations(db)
})
if err != nil {
s.Log.Warnf("Unable to load approvals for projectflock %d: %+v", id, err)
@@ -184,7 +188,7 @@ func (s projectflockService) getOneEntityOnly(c *fiber.Ctx, id uint) (*entity.Pr
return projectflock, nil
}
func (s projectflockService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectFlock, *flockDTO.FlockBaseDTO, error) {
func (s projectflockService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectFlock, *flockDTO.FlockRelationDTO, error) {
projectflock, err := s.Repository.GetByID(c.Context(), id, s.Repository.WithDefaultRelations())
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil, fiber.NewError(fiber.StatusNotFound, "Projectflock not found")
@@ -196,7 +200,7 @@ func (s projectflockService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectFlock
if s.ApprovalSvc != nil {
approvals, err := s.ApprovalSvc.ListByTarget(c.Context(), s.approvalWorkflow, id, func(db *gorm.DB) *gorm.DB {
return db.Preload("ActionUser")
return s.withRelations(db)
})
if err != nil {
s.Log.Warnf("Unable to load approvals for projectflock %d: %+v", id, err)
@@ -211,7 +215,7 @@ func (s projectflockService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectFlock
}
// Fetch Flock master data for this ProjectFlock
var flockResult *flockDTO.FlockBaseDTO
var flockResult *flockDTO.FlockRelationDTO
if projectflock.FlockName != "" {
baseName := pfutils.DeriveBaseName(projectflock.FlockName)
if baseName != "" {
@@ -219,7 +223,7 @@ func (s projectflockService) GetOne(c *fiber.Ctx, id uint) (*entity.ProjectFlock
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
s.Log.Warnf("Failed to fetch flock %q: %+v", baseName, err)
} else if flock != nil {
flockResult = &flockDTO.FlockBaseDTO{
flockResult = &flockDTO.FlockRelationDTO{
Id: flock.Id,
Name: flock.Name,
}
@@ -282,6 +286,11 @@ func (s *projectflockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*
if len(kandangs) != len(kandangIDs) {
return nil, fiber.NewError(fiber.StatusNotFound, "Some kandangs not found")
}
for _, kandang := range kandangs {
if kandang.LocationId != req.LocationId {
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Kandang %d tidak berada pada lokasi yang sama dengan project flock", kandang.Id))
}
}
// larang kalau ada yg sudah terikat ke project lain
if linked, err := s.pivotRepo().HasKandangsLinkedToOtherProject(c.Context(), kandangIDs, nil); err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate kandangs linkage")
@@ -300,22 +309,24 @@ func (s *projectflockService) CreateOne(c *fiber.Ctx, req *validation.Create) (*
err = s.Repository.DB().WithContext(c.Context()).Transaction(func(dbTransaction *gorm.DB) error {
projectRepo := repository.NewProjectflockRepository(dbTransaction)
nextSeq, err := projectRepo.GetNextSequenceForBase(c.Context(), canonicalBase)
if err != nil {
return err
}
generatedName, seq, err := s.generateSequentialFlockName(c.Context(), projectRepo, canonicalBase, nextSeq, nil)
// Generate unique flock name (sequential per base name, starting from 1)
generatedName, _, err := s.generateSequentialFlockName(c.Context(), projectRepo, canonicalBase, 1, nil)
if err != nil {
return err
}
createBody.FlockName = generatedName
createBody.Period = seq
if err := projectRepo.CreateOne(c.Context(), createBody, nil); err != nil {
return err
}
if err := s.attachKandangs(c.Context(), dbTransaction, createBody.Id, kandangIDs); err != nil {
// Compute period based on location history (max period in that location + 1),
// and store it on project_flock_kandangs only.
nextPeriod, err := s.nextLocationPeriod(c.Context(), dbTransaction, req.LocationId)
if err != nil {
return err
}
if err := s.attachKandangs(c.Context(), dbTransaction, createBody.Id, kandangIDs, nextPeriod); err != nil {
return err
}
@@ -451,6 +462,15 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
if len(kandangs) != len(newKandangIDs) {
return nil, fiber.NewError(fiber.StatusNotFound, "Some kandangs not found")
}
targetLocationID := existing.LocationId
if req.LocationId != nil && *req.LocationId > 0 {
targetLocationID = *req.LocationId
}
for _, kandang := range kandangs {
if kandang.LocationId != targetLocationID {
return nil, fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("Kandang %d tidak berada pada lokasi yang sama dengan project flock", kandang.Id))
}
}
if linked, err := s.pivotRepo().HasKandangsLinkedToOtherProject(c.Context(), newKandangIDs, &id); err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate kandangs linkage")
} else if linked {
@@ -476,18 +496,11 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
}
if needFlockNameRegenerate {
nextSeq, err := projectRepo.GetNextSequenceForBase(c.Context(), baseForGeneration)
if err != nil {
return err
}
newName, seq, err := s.generateSequentialFlockName(c.Context(), projectRepo, baseForGeneration, nextSeq, &id)
newName, _, err := s.generateSequentialFlockName(c.Context(), projectRepo, baseForGeneration, 1, &id)
if err != nil {
return err
}
updateBody["flock_name"] = newName
if seq != existing.Period {
updateBody["period"] = seq
}
}
if len(updateBody) > 0 {
@@ -531,7 +544,19 @@ func (s projectflockService) UpdateOne(c *fiber.Ctx, req *validation.Update, id
}
if len(toAttach) > 0 {
if err := s.attachKandangs(c.Context(), dbTransaction, id, toAttach); err != nil {
var currentPeriod int
if err := dbTransaction.WithContext(c.Context()).
Table("project_flock_kandangs").
Where("project_flock_id = ?", id).
Select("COALESCE(MAX(period), 0)").
Scan(&currentPeriod).Error; err != nil {
return err
}
if currentPeriod <= 0 {
currentPeriod = 1
}
if err := s.attachKandangs(c.Context(), dbTransaction, id, toAttach, currentPeriod); err != nil {
return err
}
}
@@ -807,57 +832,90 @@ func (s projectflockService) GetAvailableDocQuantity(ctx *fiber.Ctx, kandangID u
return total, nil
}
func (s projectflockService) GetFlockPeriodSummary(c *fiber.Ctx, projectFlockKandangID uint) (*FlockPeriodSummary, error) {
if projectFlockKandangID == 0 {
return nil, fiber.NewError(fiber.StatusBadRequest, "project_flock_kandang_id is required")
// nextLocationPeriod computes the next period number for a given location
// based on the maximum period that has ever been used by any kandang in that location.
func (s projectflockService) nextLocationPeriod(ctx context.Context, tx *gorm.DB, locationID uint) (int, error) {
if locationID == 0 {
return 0, fiber.NewError(fiber.StatusBadRequest, "location_id is required to compute period")
}
pivot, err := s.pivotRepo().GetByID(c.Context(), projectFlockKandangID)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, "Project flock kandang not found")
db := s.Repository.DB()
if tx != nil {
db = tx
}
var maxPeriod int
if err := db.WithContext(ctx).
Table("project_flock_kandangs pfk").
Joins("JOIN kandangs k ON k.id = pfk.kandang_id").
Where("k.location_id = ?", locationID).
Select("COALESCE(MAX(pfk.period), 0)").
Scan(&maxPeriod).Error; err != nil {
s.Log.Errorf("Failed to compute max period for location %d: %+v", locationID, err)
return 0, fiber.NewError(fiber.StatusInternalServerError, "Failed to compute period for location")
}
return maxPeriod + 1, nil
}
func (s projectflockService) GetProjectPeriods(c *fiber.Ctx, projectIDs []uint) (map[uint]int, error) {
if len(projectIDs) == 0 {
return map[uint]int{}, nil
}
return s.pivotRepo().ProjectPeriodsByProjectIDs(c.Context(), projectIDs)
}
func (s projectflockService) GetFlockPeriodSummary(c *fiber.Ctx, locationID uint) ([]KandangPeriodSummary, error) {
if locationID == 0 {
return nil, fiber.NewError(fiber.StatusBadRequest, "location_id is required")
}
exists, err := s.Repository.LocationExists(c.Context(), locationID)
if err != nil {
s.Log.Errorf("Failed to fetch project_flock_kandang %d: %+v", projectFlockKandangID, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch project flock kandang")
s.Log.Errorf("Failed to validate location %d: %+v", locationID, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to validate location")
}
if !exists {
return nil, fiber.NewError(fiber.StatusNotFound, "Location not found")
}
var baseName string
var referenceFlock *entity.Flock
if pivot.ProjectFlock.Id != 0 {
baseName = pfutils.DeriveBaseName(pivot.ProjectFlock.FlockName)
type kandangPeriodRow struct {
Id uint
Name string
LatestPeriod int
}
if strings.TrimSpace(baseName) != "" {
referenceFlock, err = s.FlockRepo.GetByName(c.Context(), baseName)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
s.Log.Errorf("Failed to fetch flock %q: %+v", baseName, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch flock")
}
var rows []kandangPeriodRow
db := s.Repository.DB().WithContext(c.Context())
if err := db.
Table("kandangs AS k").
Select("k.id, k.name, COALESCE(MAX(pfk.period), 0) AS latest_period").
Joins("LEFT JOIN project_flock_kandangs AS pfk ON pfk.kandang_id = k.id").
Where("k.location_id = ?", locationID).
Where("k.deleted_at IS NULL").
Group("k.id, k.name").
Order("k.id ASC").
Scan(&rows).Error; err != nil {
s.Log.Errorf("Failed to fetch kandang period summary for location %d: %+v", locationID, err)
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to fetch kandang period summary")
}
if referenceFlock == nil {
referenceFlock = &entity.Flock{Name: pivot.ProjectFlock.FlockName}
}
maxPeriod := pivot.ProjectFlock.Period
if strings.TrimSpace(baseName) != "" {
if headerMax, err := s.Repository.GetMaxPeriodByBaseName(c.Context(), baseName); err != nil {
s.Log.Warnf("Unable to compute header period for base %q: %+v", baseName, err)
} else if headerMax > maxPeriod {
maxPeriod = headerMax
summaries := make([]KandangPeriodSummary, 0, len(rows))
for _, row := range rows {
nextPeriod := 0
if row.LatestPeriod > 0 {
nextPeriod = row.LatestPeriod + 1
}
if pivotMax, err := s.pivotRepo().MaxPeriodByBaseName(c.Context(), baseName); err != nil {
s.Log.Warnf("Unable to compute pivot period for base %q: %+v", baseName, err)
} else if pivotMax > maxPeriod {
maxPeriod = pivotMax
}
summaries = append(summaries, KandangPeriodSummary{
Id: row.Id,
Name: row.Name,
Period: nextPeriod,
})
}
return &FlockPeriodSummary{
Flock: *referenceFlock,
NextPeriod: maxPeriod + 1,
}, nil
return summaries, nil
}
func uniqueUintSlice(values []uint) []uint {
@@ -933,7 +991,7 @@ func (s projectflockService) ensureFlockByName(ctx context.Context, actorID uint
return newFlock, nil
}
func (s projectflockService) attachKandangs(ctx context.Context, dbTransaction *gorm.DB, projectFlockID uint, kandangIDs []uint) error {
func (s projectflockService) attachKandangs(ctx context.Context, dbTransaction *gorm.DB, projectFlockID uint, kandangIDs []uint, period int) error {
if len(kandangIDs) == 0 {
return nil
}
@@ -971,6 +1029,7 @@ func (s projectflockService) attachKandangs(ctx context.Context, dbTransaction *
records = append(records, &entity.ProjectFlockKandang{
ProjectFlockId: projectFlockID,
KandangId: id,
Period: period,
})
}
if err := s.pivotRepoWithTx(dbTransaction).CreateMany(ctx, records); err != nil {
@@ -1040,10 +1099,11 @@ func (s projectflockService) kandangRepoWithTx(tx *gorm.DB) kandangRepository.Ka
return kandangRepository.NewKandangRepository(s.Repository.DB())
}
func actorIDFromContext(c *fiber.Ctx) (uint, error) {
func actorIDFromContext(_ *fiber.Ctx) (uint, error) {
// user, ok := authmiddleware.AuthenticatedUser(c)
// if !ok || user == nil || user.Id == 0 {
// return 0, fiber.NewError(fiber.StatusUnauthorized, "Please authenticate")
// }
// return user.Id, nil
return 1, nil
}
@@ -15,30 +15,30 @@ import (
// === DTO Structs ===
type RecordingBaseDTO struct {
Id uint `json:"id"`
ProjectFlockKandangId uint `json:"project_flock_kandang_id"`
RecordDatetime time.Time `json:"record_datetime"`
Day int `json:"day"`
ProjectFlockCategory string `json:"project_flock_category"`
TotalDepletionQty float64 `json:"total_depletion_qty"`
CumDepletionRate float64 `json:"cum_depletion_rate"`
DailyGain float64 `json:"daily_gain"`
AvgDailyGain float64 `json:"avg_daily_gain"`
CumIntake int `json:"cum_intake"`
FcrValue float64 `json:"fcr_value"`
TotalChickQty float64 `json:"total_chick_qty"`
Approval approvalDTO.ApprovalBaseDTO `json:"approval"`
EggGradingStatus *string `json:"egg_grading_status"`
EggGradingPendingQty *int `json:"egg_grading_pending_qty"`
EggGradingCompletedQty *int `json:"egg_grading_completed_qty"`
type RecordingRelationDTO struct {
Id uint `json:"id"`
ProjectFlockKandangId uint `json:"project_flock_kandang_id"`
RecordDatetime time.Time `json:"record_datetime"`
Day int `json:"day"`
ProjectFlockCategory string `json:"project_flock_category"`
TotalDepletionQty float64 `json:"total_depletion_qty"`
CumDepletionRate float64 `json:"cum_depletion_rate"`
DailyGain float64 `json:"daily_gain"`
AvgDailyGain float64 `json:"avg_daily_gain"`
CumIntake int `json:"cum_intake"`
FcrValue float64 `json:"fcr_value"`
TotalChickQty float64 `json:"total_chick_qty"`
Approval approvalDTO.ApprovalRelationDTO `json:"approval"`
EggGradingStatus *string `json:"egg_grading_status"`
EggGradingPendingQty *int `json:"egg_grading_pending_qty"`
EggGradingCompletedQty *int `json:"egg_grading_completed_qty"`
}
type RecordingListDTO struct {
RecordingBaseDTO
CreatedUser *userDTO.UserBaseDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
RecordingRelationDTO
CreatedUser *userDTO.UserRelationDTO `json:"created_user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type RecordingDetailDTO struct {
@@ -91,7 +91,7 @@ type RecordingEggGradingDTO struct {
// === Mapper Functions ===
func ToRecordingBaseDTO(e entity.Recording) RecordingBaseDTO {
func ToRecordingRelationDTO(e entity.Recording) RecordingRelationDTO {
var (
projectFlockCategory string
day int
@@ -142,7 +142,7 @@ func ToRecordingBaseDTO(e entity.Recording) RecordingBaseDTO {
gradingStatus, gradingPending, gradingCompleted := computeEggGradingStatus(e)
return RecordingBaseDTO{
return RecordingRelationDTO{
Id: e.Id,
ProjectFlockKandangId: e.ProjectFlockKandangId,
RecordDatetime: e.RecordDatetime,
@@ -163,17 +163,17 @@ func ToRecordingBaseDTO(e entity.Recording) RecordingBaseDTO {
}
func ToRecordingListDTO(e entity.Recording) RecordingListDTO {
var createdUser *userDTO.UserBaseDTO
var createdUser *userDTO.UserRelationDTO
if e.CreatedUser != nil && e.CreatedUser.Id != 0 {
mapped := userDTO.ToUserBaseDTO(*e.CreatedUser)
mapped := userDTO.ToUserRelationDTO(*e.CreatedUser)
createdUser = &mapped
}
return RecordingListDTO{
RecordingBaseDTO: ToRecordingBaseDTO(e),
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
CreatedUser: createdUser,
RecordingRelationDTO: ToRecordingRelationDTO(e),
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
CreatedUser: createdUser,
}
}
@@ -344,8 +344,8 @@ func filterGoodEggs(eggs []entity.RecordingEgg) []entity.RecordingEgg {
return result
}
func defaultRecordingLatestApproval(e entity.Recording) approvalDTO.ApprovalBaseDTO {
result := approvalDTO.ApprovalBaseDTO{}
func defaultRecordingLatestApproval(e entity.Recording) approvalDTO.ApprovalRelationDTO {
result := approvalDTO.ApprovalRelationDTO{}
step := utils.RecordingStepPengajuan
result.StepNumber = uint16(step)
@@ -356,9 +356,9 @@ func defaultRecordingLatestApproval(e entity.Recording) approvalDTO.ApprovalBase
}
if e.CreatedUser != nil && e.CreatedUser.Id != 0 {
result.ActionBy = userDTO.ToUserBaseDTO(*e.CreatedUser)
result.ActionBy = userDTO.ToUserRelationDTO(*e.CreatedUser)
} else if e.CreatedBy != 0 {
result.ActionBy = userDTO.UserBaseDTO{
result.ActionBy = userDTO.UserRelationDTO{
Id: e.CreatedBy,
IdUser: int64(e.CreatedBy),
}
@@ -10,7 +10,7 @@ import (
// === DTO Structs ===
type TransferLayingBaseDTO struct {
type TransferLayingRelationDTO struct {
Id uint `json:"id"`
TransferNumber string `json:"transfer_number"`
TransferDate time.Time `json:"transfer_date"`
@@ -64,22 +64,22 @@ type LayingTransferTargetDTO struct {
}
type TransferLayingListDTO struct {
TransferLayingBaseDTO
FromProjectFlock *ProjectFlockSummaryDTO `json:"from_project_flock,omitempty"`
ToProjectFlock *ProjectFlockSummaryDTO `json:"to_project_flock,omitempty"`
PendingUsageQty *float64 `json:"pending_usage_qty"`
UsageQty *float64 `json:"usage_qty"`
CreatedBy uint `json:"created_by"`
CreatedUser *userDTO.UserBaseDTO `json:"created_user,omitempty"`
CreatedAt time.Time `json:"created_at"`
Approval *approvalDTO.ApprovalBaseDTO `json:"approval,omitempty"`
TransferLayingRelationDTO
FromProjectFlock *ProjectFlockSummaryDTO `json:"from_project_flock,omitempty"`
ToProjectFlock *ProjectFlockSummaryDTO `json:"to_project_flock,omitempty"`
PendingUsageQty *float64 `json:"pending_usage_qty"`
UsageQty *float64 `json:"usage_qty"`
CreatedBy uint `json:"created_by"`
CreatedUser *userDTO.UserRelationDTO `json:"created_user,omitempty"`
CreatedAt time.Time `json:"created_at"`
Approval *approvalDTO.ApprovalRelationDTO `json:"approval,omitempty"`
}
type TransferLayingDetailDTO struct {
TransferLayingListDTO
Sources []LayingTransferSourceDTO `json:"sources,omitempty"`
Targets []LayingTransferTargetDTO `json:"targets,omitempty"`
Approval *approvalDTO.ApprovalBaseDTO `json:"approval,omitempty"`
Sources []LayingTransferSourceDTO `json:"sources,omitempty"`
Targets []LayingTransferTargetDTO `json:"targets,omitempty"`
Approval *approvalDTO.ApprovalRelationDTO `json:"approval,omitempty"`
}
// === Available Quantity DTOs ===
@@ -203,8 +203,8 @@ func ToLayingTransferTargetDTOs(targets []entity.LayingTransferTarget) []LayingT
return result
}
func ToTransferLayingBaseDTO(e entity.LayingTransfer) TransferLayingBaseDTO {
return TransferLayingBaseDTO{
func ToTransferLayingRelationDTO(e entity.LayingTransfer) TransferLayingRelationDTO {
return TransferLayingRelationDTO{
Id: e.Id,
TransferNumber: e.TransferNumber,
TransferDate: e.TransferDate,
@@ -213,26 +213,26 @@ func ToTransferLayingBaseDTO(e entity.LayingTransfer) TransferLayingBaseDTO {
}
func ToTransferLayingListDTO(e entity.LayingTransfer) TransferLayingListDTO {
var createdUser *userDTO.UserBaseDTO
var createdUser *userDTO.UserRelationDTO
if e.CreatedUser != nil && e.CreatedUser.Id != 0 {
mapped := userDTO.ToUserBaseDTO(*e.CreatedUser)
mapped := userDTO.ToUserRelationDTO(*e.CreatedUser)
createdUser = &mapped
}
return TransferLayingListDTO{
TransferLayingBaseDTO: ToTransferLayingBaseDTO(e),
FromProjectFlock: ToProjectFlockSummaryDTO(e.FromProjectFlock),
ToProjectFlock: ToProjectFlockSummaryDTO(e.ToProjectFlock),
PendingUsageQty: e.PendingUsageQty,
UsageQty: e.UsageQty,
CreatedBy: e.CreatedBy,
CreatedUser: createdUser,
CreatedAt: e.CreatedAt,
TransferLayingRelationDTO: ToTransferLayingRelationDTO(e),
FromProjectFlock: ToProjectFlockSummaryDTO(e.FromProjectFlock),
ToProjectFlock: ToProjectFlockSummaryDTO(e.ToProjectFlock),
PendingUsageQty: e.PendingUsageQty,
UsageQty: e.UsageQty,
CreatedBy: e.CreatedBy,
CreatedUser: createdUser,
CreatedAt: e.CreatedAt,
}
}
func ToTransferLayingDetailDTO(e entity.LayingTransfer, approvals []entity.Approval) TransferLayingDetailDTO {
var latestApproval *approvalDTO.ApprovalBaseDTO
var latestApproval *approvalDTO.ApprovalRelationDTO
if e.LatestApproval != nil {
mapped := approvalDTO.ToApprovalDTO(*e.LatestApproval)
@@ -252,7 +252,7 @@ func ToTransferLayingDetailDTO(e entity.LayingTransfer, approvals []entity.Appro
}
func ToTransferLayingDetailDTOWithSingleApproval(e entity.LayingTransfer, approval *entity.Approval) TransferLayingDetailDTO {
var mappedApproval *approvalDTO.ApprovalBaseDTO
var mappedApproval *approvalDTO.ApprovalRelationDTO
// Prefer LatestApproval from entity
if e.LatestApproval != nil && e.LatestApproval.Id != 0 {