Files
backend_fiesta/services/stockrequestService.go
2026-09-16 17:09:04 +05:30

76 lines
2.4 KiB
Go

package services
import (
"errors"
"nearle/models"
"nearle/repositories"
"time"
)
type StockRequestService interface {
CreateStockRequest(req *models.StockRequest) error
GetStockRequests(tenantID int, locationID int, status string, date string, pageNo int, pageSize int) ([]models.StockRequest, error)
UpdateStockRequest(requestID int, status string) error
}
type stockRequestService struct {
repo repositories.StockRequestRepository
productService ProductService
}
func NewStockRequestService(repo repositories.StockRequestRepository, productService ProductService) StockRequestService {
return &stockRequestService{repo: repo, productService: productService}
}
func (s *stockRequestService) CreateStockRequest(req *models.StockRequest) error {
// A request for nothing is not a request.
//
// Nothing downstream rejected it, so a branch could raise a request for
// zero units and it sat in the admin's queue looking exactly like a real
// one — and approving it moved no stock, which reads as the ledger being
// broken rather than the request being empty. A negative would move stock
// the wrong way on receipt, since UpdateStockRequest writes Qty straight
// into the ledger as an 'in'.
//
// Returned as an ordinary error: the controller already reports per-item
// reasons, so one bad row in a batch is named and the rest still land.
if req.Qty <= 0 {
return errors.New("quantity must be more than zero")
}
return s.repo.CreateStockRequest(req)
}
func (s *stockRequestService) GetStockRequests(tenantID int, locationID int, status string, date string, pageNo int, pageSize int) ([]models.StockRequest, error) {
return s.repo.GetStockRequests(tenantID, locationID, status, date, pageNo, pageSize)
}
func (s *stockRequestService) UpdateStockRequest(requestID int, status string) error {
// If the request is being marked as Received, we need to update the actual store inventory
if status == "Received" {
req, err := s.repo.GetStockRequestByID(requestID)
if err != nil {
return err
}
if req.Status != "Received" { // prevent double receiving
stk := models.Productstock{
Tenantid: req.Tenantid,
Locationid: req.Locationid,
Productid: req.Productid,
Quantity: req.Qty,
Stocktype: "in",
Stockdate: time.Now(),
}
err = s.productService.CreateProductStock([]models.Productstock{stk})
if err != nil {
return err
}
}
}
return s.repo.UpdateStockRequest(requestID, status)
}