feat(BE-229,234,235,230,231,232,233): purchase request and purchase order and fix master data dto

This commit is contained in:
ragilap
2025-11-17 09:39:30 +07:00
parent 8f74391f1e
commit 11f2389ec5
22 changed files with 2184 additions and 437 deletions
@@ -2,6 +2,7 @@ package repository
import (
"context"
"errors"
"fmt"
"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
@@ -24,6 +25,8 @@ type ProductWarehouseRepository interface {
ApplyFlagsFilter(db *gorm.DB, flags []string) *gorm.DB
AdjustQuantities(ctx context.Context, deltas map[uint]float64, modifier func(*gorm.DB) *gorm.DB) error
GetDetailByID(ctx context.Context, id uint) (*entity.ProductWarehouse, error)
CleanupEmpty(ctx context.Context, affected map[uint]struct{}) error
EnsureProductWarehouse(ctx context.Context, productID, warehouseID uint, createdBy uint64) (uint, error)
}
type ProductWarehouseRepositoryImpl struct {
@@ -150,6 +153,73 @@ func (r *ProductWarehouseRepositoryImpl) AdjustQuantities(ctx context.Context, d
return nil
}
func (r *ProductWarehouseRepositoryImpl) CleanupEmpty(ctx context.Context, affected map[uint]struct{}) error {
if len(affected) == 0 {
return nil
}
ids := make([]uint, 0, len(affected))
for id := range affected {
ids = append(ids, id)
}
var emptyIDs []uint
if err := r.DB().WithContext(ctx).
Model(&entity.ProductWarehouse{}).
Where("id IN ? AND COALESCE(quantity,0) <= 0", ids).
Pluck("id", &emptyIDs).Error; err != nil {
return err
}
if len(emptyIDs) == 0 {
return nil
}
if err := r.DB().WithContext(ctx).
Model(&entity.PurchaseItem{}).
Where("product_warehouse_id IN ?", emptyIDs).
Update("product_warehouse_id", nil).Error; err != nil {
return err
}
if err := r.DB().WithContext(ctx).
Where("id IN ?", emptyIDs).
Delete(&entity.ProductWarehouse{}).Error; err != nil {
return err
}
return nil
}
func (r *ProductWarehouseRepositoryImpl) EnsureProductWarehouse(
ctx context.Context,
productID uint,
warehouseID uint,
createdBy uint64,
) (uint, error) {
record, err := r.GetProductWarehouseByProductAndWarehouseID(ctx, productID, warehouseID)
if err == nil {
return record.Id, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return 0, err
}
entity := &entity.ProductWarehouse{
ProductId: productID,
WarehouseId: warehouseID,
Quantity: 0,
CreatedBy: uint(createdBy),
}
if entity.CreatedBy == 0 {
entity.CreatedBy = 1
}
if err := r.CreateOne(ctx, entity, nil); err != nil {
return 0, err
}
return entity.Id, nil
}
func (r *ProductWarehouseRepositoryImpl) GetDetailByID(ctx context.Context, id uint) (*entity.ProductWarehouse, error) {
var productWarehouse entity.ProductWarehouse
err := r.DB().WithContext(ctx).