Private
Public Access
92 lines
2.2 KiB
Go
92 lines
2.2 KiB
Go
package stock
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
|
|
"repuestera_back/models"
|
|
models_logs "repuestera_back/models/logs"
|
|
"repuestera_back/repositorios"
|
|
"repuestera_back/utils"
|
|
)
|
|
|
|
func LiberarReserva(c *gin.Context) {
|
|
id, err := parseUintParam(c, "id")
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
resultado, err := liberarReserva(
|
|
repositorios.BaseDeDatos(),
|
|
repositorios.ObtenerRepositorios(c),
|
|
utils.EmpresaID(c),
|
|
c.GetUint("userID"),
|
|
uint(id),
|
|
)
|
|
if err != nil {
|
|
responderError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, resultado)
|
|
}
|
|
|
|
// liberarReserva devuelve el disponible de una reserva activa.
|
|
func liberarReserva(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, reservaID uint) (*models.Reserva, error) {
|
|
var reserva *models.Reserva
|
|
|
|
err := db.Transaction(func(tx *gorm.DB) error {
|
|
actual, err := repo.Reserva.ObtenerPorID(reservaID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return ErrReservaInexistente
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if actual.Estado != models.ReservaActiva {
|
|
return ErrReservaYaLiberada
|
|
}
|
|
|
|
stock, err := repo.Stock.BloquearPorRepuestoAlmacen(tx, uint64(actual.RepuestoID), actual.AlmacenID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return ErrStockNoEncontrado
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
liberada, err := repo.Reserva.Liberar(tx, reservaID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !liberada {
|
|
return ErrReservaYaLiberada
|
|
}
|
|
|
|
saldoAnterior := stock.CantidadReservada
|
|
stock.CantidadReservada = redondearCantidad(math.Max(0, stock.CantidadReservada-actual.Cantidad))
|
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
|
return err
|
|
}
|
|
if err := registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoLiberacion, -actual.Cantidad, saldoAnterior, stock.CantidadReservada, "RESERVA", uint64(actual.ID), "Liberación de reserva"); err != nil {
|
|
return err
|
|
}
|
|
|
|
reserva = actual
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
registrarLog(repo, empresaID, usuarioID, "LIBERAR_RESERVA", []models_logs.LogDetalle{
|
|
{Columna: "reservaId", ValorNuevo: fmt.Sprintf("%d", reserva.ID)},
|
|
{Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", reserva.Cantidad)},
|
|
})
|
|
return reserva, nil
|
|
}
|