mirror of
https://gitlab.com/mbugroup/lti-api.git
synced 2026-05-20 13:31:56 +00:00
feat(BE-47,48,49,50): implement inventory adjustment system
- Extend DB schema with product_warehouses and stock_logs tables - Implement stock adjustment API (increase/decrease operations) - Add comprehensive validation for all adjustment operations - Implement audit log system for each adjustment with history tracking - Include transaction handling, DTOs, seeders, and proper error handling - Add adjustment history API with pagination and filtering TODO: Integration testing pending
This commit is contained in:
@@ -2,128 +2,184 @@ package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
|
||||
repository "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/adjustments/repositories"
|
||||
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"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type AdjustmentService interface {
|
||||
GetAll(ctx *fiber.Ctx, params *validation.Query) ([]entity.Adjustment, int64, error)
|
||||
GetOne(ctx *fiber.Ctx, id uint) (*entity.Adjustment, error)
|
||||
CreateOne(ctx *fiber.Ctx, req *validation.Create) (*entity.Adjustment, error)
|
||||
UpdateOne(ctx *fiber.Ctx, req *validation.Update, id uint) (*entity.Adjustment, error)
|
||||
DeleteOne(ctx *fiber.Ctx, id uint) error
|
||||
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
|
||||
Repository repository.AdjustmentRepository
|
||||
Log *logrus.Logger
|
||||
Validate *validator.Validate
|
||||
StockLogsRepository stockLogsRepo.StockLogRepository
|
||||
WarehouseRepo warehouseRepo.WarehouseRepository
|
||||
ProductWarehouseRepo ProductWarehouse.ProductWarehouseRepository
|
||||
}
|
||||
|
||||
func NewAdjustmentService(repo repository.AdjustmentRepository, validate *validator.Validate) AdjustmentService {
|
||||
func NewAdjustmentService(stockLogsRepo stockLogsRepo.StockLogRepository, warehouseRepo warehouseRepo.WarehouseRepository, productWarehouseRepo ProductWarehouse.ProductWarehouseRepository, validate *validator.Validate) AdjustmentService {
|
||||
return &adjustmentService{
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
Repository: repo,
|
||||
Log: utils.Log,
|
||||
Validate: validate,
|
||||
StockLogsRepository: stockLogsRepo,
|
||||
WarehouseRepo: warehouseRepo,
|
||||
ProductWarehouseRepo: productWarehouseRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s adjustmentService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.Preload("CreatedUser")
|
||||
func (s *adjustmentService) withRelations(db *gorm.DB) *gorm.DB {
|
||||
return db.
|
||||
Preload("ProductWarehouse").
|
||||
Preload("ProductWarehouse.Product").
|
||||
Preload("ProductWarehouse.Warehouse").
|
||||
Preload("CreatedUser")
|
||||
}
|
||||
|
||||
func (s adjustmentService) GetAll(c *fiber.Ctx, params *validation.Query) ([]entity.Adjustment, int64, error) {
|
||||
if err := s.Validate.Struct(params); err != nil {
|
||||
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 := (params.Page - 1) * params.Limit
|
||||
offset := (query.Page - 1) * query.Limit
|
||||
|
||||
stockLogs, total, err := s.StockLogsRepository.GetAll(c.Context(), offset, query.Limit, func(db *gorm.DB) *gorm.DB {
|
||||
|
||||
adjustments, 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+"%")
|
||||
|
||||
db = db.Where("log_type = ?", entity.LogTypeAdjustment)
|
||||
|
||||
if query.Search != "" {
|
||||
db = db.Where("note ILIKE ?", "%"+query.Search+"%")
|
||||
}
|
||||
return db.Order("created_at DESC").Order("updated_at DESC")
|
||||
|
||||
if query.TransactionType != "" {
|
||||
db = db.Where("transaction_type = ?", strings.ToUpper(query.TransactionType))
|
||||
}
|
||||
|
||||
return db.Order("created_at DESC")
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed to get adjustments: %+v", err)
|
||||
return nil, 0, err
|
||||
return nil, 0, fiber.NewError(fiber.StatusInternalServerError, "Failed to get adjustment history")
|
||||
}
|
||||
return adjustments, total, nil
|
||||
}
|
||||
|
||||
func (s adjustmentService) GetOne(c *fiber.Ctx, id uint) (*entity.Adjustment, error) {
|
||||
adjustment, err := s.Repository.GetByID(c.Context(), id, s.withRelations)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fiber.NewError(fiber.StatusNotFound, "Adjustment not found")
|
||||
}
|
||||
if err != nil {
|
||||
s.Log.Errorf("Failed get adjustment by id: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
return adjustment, nil
|
||||
}
|
||||
|
||||
func (s *adjustmentService) CreateOne(c *fiber.Ctx, req *validation.Create) (*entity.Adjustment, error) {
|
||||
if err := s.Validate.Struct(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
createBody := &entity.Adjustment{
|
||||
Name: req.Name,
|
||||
}
|
||||
|
||||
if err := s.Repository.CreateOne(c.Context(), createBody, nil); err != nil {
|
||||
s.Log.Errorf("Failed to create adjustment: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, createBody.Id)
|
||||
}
|
||||
|
||||
func (s adjustmentService) UpdateOne(c *fiber.Ctx, req *validation.Update, id uint) (*entity.Adjustment, 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, "Adjustment not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to update adjustment: %+v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.GetOne(c, id)
|
||||
}
|
||||
|
||||
func (s adjustmentService) 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, "Adjustment not found")
|
||||
}
|
||||
s.Log.Errorf("Failed to delete adjustment: %+v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
|
||||
// Convert to pointer slice
|
||||
result := make([]*entity.StockLog, len(stockLogs))
|
||||
for i, v := range stockLogs {
|
||||
result[i] = &v
|
||||
}
|
||||
|
||||
return result, total, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user