mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
81cbb230f3
- Add search parameter to adjustment history API - Fix JOIN query logic to avoid duplicate JOINs - Use EXISTS subquery for cleaner product/warehouse filtering - Fix pointer conversion issue in slice iteration - Improve query performance and code readability
196 lines
6.7 KiB
Go
196 lines
6.7 KiB
Go
package service
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
|
|
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
|
validation "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/adjustments/validations"
|
|
ProductWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
|
|
warehouseRepo "gitlab.com/mbugroup/lti-api.git/internal/modules/master/warehouses/repositories"
|
|
stockLogsRepo "gitlab.com/mbugroup/lti-api.git/internal/modules/shared/stock-logs/repositories"
|
|
"gitlab.com/mbugroup/lti-api.git/internal/utils"
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
type AdjustmentService interface {
|
|
Adjustment(ctx *fiber.Ctx, req *validation.Create) (*entity.StockLog, error)
|
|
GetOne(ctx *fiber.Ctx, id uint) (*entity.StockLog, error)
|
|
AdjustmentHistory(ctx *fiber.Ctx, query *validation.Query) ([]*entity.StockLog, int64, error)
|
|
}
|
|
|
|
type adjustmentService struct {
|
|
Log *logrus.Logger
|
|
Validate *validator.Validate
|
|
StockLogsRepository stockLogsRepo.StockLogRepository
|
|
WarehouseRepo warehouseRepo.WarehouseRepository
|
|
ProductWarehouseRepo ProductWarehouse.ProductWarehouseRepository
|
|
}
|
|
|
|
func NewAdjustmentService(stockLogsRepo stockLogsRepo.StockLogRepository, warehouseRepo warehouseRepo.WarehouseRepository, productWarehouseRepo ProductWarehouse.ProductWarehouseRepository, validate *validator.Validate) AdjustmentService {
|
|
return &adjustmentService{
|
|
Log: utils.Log,
|
|
Validate: validate,
|
|
StockLogsRepository: stockLogsRepo,
|
|
WarehouseRepo: warehouseRepo,
|
|
ProductWarehouseRepo: productWarehouseRepo,
|
|
}
|
|
}
|
|
|
|
func (s *adjustmentService) withRelations(db *gorm.DB) *gorm.DB {
|
|
return db.
|
|
Preload("ProductWarehouse").
|
|
Preload("ProductWarehouse.Product").
|
|
Preload("ProductWarehouse.Warehouse").
|
|
Preload("CreatedUser")
|
|
}
|
|
|
|
func (s *adjustmentService) GetOne(c *fiber.Ctx, id uint) (*entity.StockLog, error) {
|
|
stockLog, err := s.StockLogsRepository.GetByID(c.Context(), id, s.withRelations)
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, fiber.NewError(fiber.StatusNotFound, "Adjustment not found")
|
|
}
|
|
s.Log.Errorf("Failed to get adjustment by id: %+v", err)
|
|
return nil, err
|
|
}
|
|
|
|
if stockLog.LogType != entity.LogTypeAdjustment {
|
|
return nil, fiber.NewError(fiber.StatusNotFound, "Adjustment not found")
|
|
}
|
|
|
|
return stockLog, nil
|
|
}
|
|
|
|
func (s *adjustmentService) Adjustment(c *fiber.Ctx, req *validation.Create) (*entity.StockLog, error) {
|
|
if err := s.Validate.Struct(req); err != nil {
|
|
return nil, err
|
|
}
|
|
ctx := c.Context()
|
|
|
|
productWarehouseExists, err := s.ProductWarehouseRepo.ProductWarehouseExists(ctx, uint(req.ProductID), uint(req.WarehouseID), nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !productWarehouseExists {
|
|
return nil, fiber.NewError(fiber.StatusBadRequest, "Product warehouse not found")
|
|
}
|
|
|
|
transactionType := strings.ToUpper(req.TransactionType)
|
|
if transactionType != entity.TransactionTypeIncrease && transactionType != entity.TransactionTypeDecrease {
|
|
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid transaction type")
|
|
}
|
|
|
|
var createdLogId uint
|
|
|
|
err = s.StockLogsRepository.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
// Get product warehouse by product id and warehouse id (read operation, no transaction needed)
|
|
productWarehouse, err := s.ProductWarehouseRepo.GetProductWarehouseByProductAndWarehouseID(ctx, uint(req.ProductID), uint(req.WarehouseID))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if productWarehouse == nil {
|
|
return fiber.NewError(fiber.StatusBadRequest, "Product warehouse not found")
|
|
}
|
|
s.Log.Infof("Product Warehouse found: %+v", productWarehouse.Id)
|
|
|
|
afterQuantity := productWarehouse.Quantity
|
|
if transactionType == entity.TransactionTypeIncrease {
|
|
afterQuantity += req.Quantity
|
|
} else {
|
|
if productWarehouse.Quantity < req.Quantity {
|
|
return fiber.NewError(fiber.StatusBadRequest, "Insufficient stock for adjustment")
|
|
}
|
|
afterQuantity -= req.Quantity
|
|
}
|
|
|
|
newLog := &entity.StockLog{
|
|
TransactionType: transactionType,
|
|
Quantity: req.Quantity,
|
|
BeforeQuantity: productWarehouse.Quantity,
|
|
AfterQuantity: afterQuantity,
|
|
LogType: entity.LogTypeAdjustment,
|
|
LogId: 0,
|
|
Note: req.Note,
|
|
ProductWarehouseId: productWarehouse.Id,
|
|
CreatedBy: 1, // TODO: should Get from auth middleware
|
|
}
|
|
|
|
if err := s.StockLogsRepository.WithTx(tx).CreateOne(ctx, newLog, nil); err != nil {
|
|
s.Log.Errorf("Failed to create stock log: %+v", err)
|
|
return err
|
|
}
|
|
s.Log.Infof("Stock log created: %+v", newLog.Id)
|
|
|
|
productWarehouse.Quantity = afterQuantity
|
|
if err := s.ProductWarehouseRepo.WithTx(tx).UpdateOne(ctx, productWarehouse.Id, productWarehouse, nil); err != nil {
|
|
s.Log.Errorf("Failed to update product warehouse quantity: %+v", err)
|
|
return err
|
|
}
|
|
s.Log.Infof("Product warehouse quantity updated: %+v", productWarehouse.Id)
|
|
|
|
// Set createdLogId to get the log with relations after transaction
|
|
createdLogId = newLog.Id
|
|
return nil
|
|
})
|
|
|
|
if err != nil {
|
|
s.Log.Errorf("Transaction failed in CreateOne: %+v", err)
|
|
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to process adjustment transaction")
|
|
}
|
|
|
|
return s.GetOne(c, createdLogId)
|
|
}
|
|
|
|
func (s *adjustmentService) AdjustmentHistory(c *fiber.Ctx, query *validation.Query) ([]*entity.StockLog, int64, error) {
|
|
if err := s.Validate.Struct(query); err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
offset := (query.Page - 1) * query.Limit
|
|
|
|
stockLogs, total, err := s.StockLogsRepository.GetAll(c.Context(), offset, query.Limit, func(db *gorm.DB) *gorm.DB {
|
|
|
|
db = s.withRelations(db)
|
|
|
|
db = db.Where("log_type = ?", entity.LogTypeAdjustment)
|
|
|
|
if query.TransactionType != "" {
|
|
db = db.Where("transaction_type = ?", strings.ToUpper(query.TransactionType))
|
|
}
|
|
if query.ProductID > 0 {
|
|
db = db.Joins("JOIN product_warehouses ON product_warehouses.id = stock_logs.product_warehouse_id").
|
|
Where("product_warehouses.product_id = ?", query.ProductID)
|
|
}
|
|
|
|
if query.WarehouseID > 0 {
|
|
if query.ProductID > 0 {
|
|
|
|
db = db.Where("product_warehouses.warehouse_id = ?", query.WarehouseID)
|
|
} else {
|
|
|
|
db = db.Joins("JOIN product_warehouses ON product_warehouses.id = stock_logs.product_warehouse_id").
|
|
Where("product_warehouses.warehouse_id = ?", query.WarehouseID)
|
|
}
|
|
}
|
|
|
|
return db.Order("created_at DESC")
|
|
})
|
|
|
|
if err != nil {
|
|
s.Log.Errorf("Failed to get adjustments: %+v", err)
|
|
return nil, 0, fiber.NewError(fiber.StatusInternalServerError, "Failed to get adjustment history")
|
|
}
|
|
|
|
result := make([]*entity.StockLog, len(stockLogs))
|
|
for i, v := range stockLogs {
|
|
result[i] = &v
|
|
}
|
|
|
|
return result, total, nil
|
|
}
|