Private
Public Access
997 lines
31 KiB
Go
997 lines
31 KiB
Go
// Package stock centraliza las reglas de negocio del módulo Stock.
|
|
// Todos los casos de uso (traslado, ajuste, ingreso, reservas, devoluciones y
|
|
// comentarios) pasan por este servicio para que las validaciones sean únicas.
|
|
package stock
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
applog "log"
|
|
"math"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
dto_builders "repuestera_back/dto/Builders"
|
|
"repuestera_back/models"
|
|
"repuestera_back/models/contabilidad"
|
|
models_logs "repuestera_back/models/logs"
|
|
"repuestera_back/repositorios"
|
|
"repuestera_back/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// Errores de negocio del módulo. Los controllers los traducen a códigos HTTP.
|
|
var (
|
|
ErrCantidadInvalida = errors.New("la cantidad debe ser mayor a cero")
|
|
ErrStockInsuficiente = errors.New("stock insuficiente")
|
|
ErrMismoAlmacen = errors.New("el almacén de origen y destino deben ser distintos")
|
|
ErrStockNoEncontrado = errors.New("stock no encontrado")
|
|
ErrReservaInexistente = errors.New("reserva inexistente")
|
|
ErrReservaYaLiberada = errors.New("la reserva ya no está activa")
|
|
ErrComentarioLargo = errors.New("el comentario no puede superar los 60 caracteres")
|
|
ErrComentarioVacio = errors.New("el comentario no puede estar vacío")
|
|
ErrFacturaAnulada = errors.New("la factura está anulada")
|
|
ErrDevolucionExcedeVendido = errors.New("la devolución excede lo vendido")
|
|
ErrMotivoRequerido = errors.New("el motivo es obligatorio")
|
|
ErrItemDuplicado = errors.New("el repuesto está repetido en la operación")
|
|
ErrItemNoEncontrado = errors.New("el repuesto no pertenece a la factura")
|
|
ErrAlmacenInvalido = errors.New("el almacén no existe o no pertenece a la empresa")
|
|
ErrProveedorNoEncontrado = errors.New("el proveedor no existe o no pertenece a la empresa")
|
|
ErrRepuestoNoEncontrado = errors.New("el repuesto no existe o no pertenece a la empresa")
|
|
ErrRemitoDuplicado = errors.New("ya existe un remito con ese número para el proveedor")
|
|
ErrFechaVencimiento = errors.New("la fecha de vencimiento debe ser futura")
|
|
ErrAjusteBajoReserva = errors.New("el stock no puede quedar por debajo de lo reservado")
|
|
ErrSinAlmacen = errors.New("no hay almacenes cargados en la empresa")
|
|
)
|
|
|
|
// Estado clasifica un ítem según su cantidad física y su mínimo.
|
|
type Estado string
|
|
|
|
const (
|
|
EstadoAgotado Estado = "AGOTADO"
|
|
EstadoBajoMinimo Estado = "BAJO_MINIMO"
|
|
EstadoNormal Estado = "NORMAL"
|
|
)
|
|
|
|
// Disponible es la cantidad que puede usarse sin afectar reservas.
|
|
func Disponible(stock *models.Stock) float64 {
|
|
if stock == nil {
|
|
return 0
|
|
}
|
|
return redondearCantidad(stock.Cantidad - stock.CantidadReservada)
|
|
}
|
|
|
|
// EstadoStock devuelve AGOTADO, BAJO_MINIMO o NORMAL.
|
|
func EstadoStock(stock *models.Stock, repuesto *models.Repuesto) Estado {
|
|
if stock == nil {
|
|
return EstadoAgotado
|
|
}
|
|
if stock.Cantidad <= 0 {
|
|
return EstadoAgotado
|
|
}
|
|
if repuesto != nil && stock.Cantidad < float64(repuesto.StockMinimo) {
|
|
return EstadoBajoMinimo
|
|
}
|
|
return EstadoNormal
|
|
}
|
|
|
|
// ValidarCantidad acepta solo cantidades positivas y finitas.
|
|
func ValidarCantidad(cantidad float64) error {
|
|
if math.IsNaN(cantidad) || math.IsInf(cantidad, 0) || cantidad <= 0 {
|
|
return ErrCantidadInvalida
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ValidarObservacion limita el texto a 60 caracteres (runas, no bytes).
|
|
func ValidarObservacion(texto string) error {
|
|
if utf8.RuneCountInString(texto) > 60 {
|
|
return ErrComentarioLargo
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func redondearCantidad(valor float64) float64 {
|
|
return math.Round(valor*1000) / 1000
|
|
}
|
|
|
|
// Servicio expone las operaciones de escritura del módulo Stock.
|
|
type Servicio struct {
|
|
db *gorm.DB
|
|
repo *repositorios.Repositorios
|
|
empresaID uint
|
|
usuarioID uint
|
|
contabilidad bool
|
|
}
|
|
|
|
// Nuevo arma el servicio a partir del contexto autenticado.
|
|
func Nuevo(c *gin.Context) *Servicio {
|
|
return &Servicio{
|
|
db: repositorios.BaseDeDatos(),
|
|
repo: repositorios.ObtenerRepositorios(c),
|
|
empresaID: utils.EmpresaID(c),
|
|
usuarioID: c.GetUint("userID"),
|
|
contabilidad: true,
|
|
}
|
|
}
|
|
|
|
// NuevoConDB permite inyectar la conexión y el usuario (tests / jobs).
|
|
func NuevoConDB(db *gorm.DB, empresaID, usuarioID uint) *Servicio {
|
|
return &Servicio{
|
|
db: db,
|
|
repo: repositorios.NuevoContenedor(db, empresaID),
|
|
empresaID: empresaID,
|
|
usuarioID: usuarioID,
|
|
contabilidad: true,
|
|
}
|
|
}
|
|
|
|
// SinContabilidad desactiva los asientos para pruebas o empresas que aún no
|
|
// tienen cuentas contables definidas.
|
|
func (s *Servicio) SinContabilidad() *Servicio {
|
|
s.contabilidad = false
|
|
return s
|
|
}
|
|
|
|
// EntradaTraslado mueve mercadería entre dos almacenes de la empresa.
|
|
type EntradaTraslado struct {
|
|
RepuestoID uint64
|
|
AlmacenOrigenID uint
|
|
AlmacenDestinoID uint
|
|
Cantidad float64
|
|
Observacion string
|
|
}
|
|
|
|
type ResultadoTraslado struct {
|
|
Origen *models.Stock
|
|
Destino *models.Stock
|
|
}
|
|
|
|
// Trasladar descuenta el origen y suma el destino en una sola transacción.
|
|
func (s *Servicio) Trasladar(entrada EntradaTraslado) (*ResultadoTraslado, error) {
|
|
if err := ValidarCantidad(entrada.Cantidad); err != nil {
|
|
return nil, err
|
|
}
|
|
if entrada.RepuestoID == 0 || entrada.AlmacenOrigenID == 0 || entrada.AlmacenDestinoID == 0 {
|
|
return nil, ErrStockNoEncontrado
|
|
}
|
|
if entrada.AlmacenOrigenID == entrada.AlmacenDestinoID {
|
|
return nil, ErrMismoAlmacen
|
|
}
|
|
if err := ValidarObservacion(entrada.Observacion); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
cantidad := redondearCantidad(entrada.Cantidad)
|
|
var resultado ResultadoTraslado
|
|
|
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
|
origen, err := s.buscarStockTx(tx, entrada.RepuestoID, entrada.AlmacenOrigenID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return ErrStockNoEncontrado
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
destino, errDestino := s.buscarStockTx(tx, entrada.RepuestoID, entrada.AlmacenDestinoID)
|
|
existeDestino := errDestino == nil
|
|
if errDestino != nil && !errors.Is(errDestino, gorm.ErrRecordNotFound) {
|
|
return errDestino
|
|
}
|
|
|
|
// Bloquear siempre en orden ascendente de ID para evitar deadlocks
|
|
// cuando dos traslados cruzan el mismo par de filas.
|
|
if existeDestino && destino.ID < origen.ID {
|
|
destino, err = s.repo.Stock.BloquearPorID(tx, destino.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
origen, err = s.repo.Stock.BloquearPorID(tx, origen.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
origen, err = s.repo.Stock.BloquearPorID(tx, origen.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if existeDestino {
|
|
destino, err = s.repo.Stock.BloquearPorID(tx, destino.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
destino = &models.Stock{
|
|
RepuestoID: entrada.RepuestoID,
|
|
AlmacenID: entrada.AlmacenDestinoID,
|
|
}
|
|
if s.empresaID > 0 {
|
|
destino.EmpresaID = uint64(s.empresaID)
|
|
}
|
|
if err := tx.Create(destino).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
if Disponible(origen) < cantidad {
|
|
return fmt.Errorf("%w: disponible %.3f, solicitado %.3f", ErrStockInsuficiente, Disponible(origen), cantidad)
|
|
}
|
|
|
|
saldoOrigen := origen.Cantidad
|
|
saldoDestino := destino.Cantidad
|
|
|
|
origen.Cantidad = redondearCantidad(origen.Cantidad - cantidad)
|
|
destino.Cantidad = redondearCantidad(destino.Cantidad + cantidad)
|
|
if err := s.repo.Stock.ActualizarCantidades(tx, origen); err != nil {
|
|
return err
|
|
}
|
|
if err := s.repo.Stock.ActualizarCantidades(tx, destino); err != nil {
|
|
return err
|
|
}
|
|
|
|
referencia := fmt.Sprintf("Traslado %d → %d", entrada.AlmacenOrigenID, entrada.AlmacenDestinoID)
|
|
if err := s.registrarMovimiento(tx, origen, models.MovimientoTrasladoSalida, -cantidad, saldoOrigen, origen.Cantidad, "TRASLADO", entrada.RepuestoID, referencia); err != nil {
|
|
return err
|
|
}
|
|
if err := s.registrarMovimiento(tx, destino, models.MovimientoTrasladoEntrada, cantidad, saldoDestino, destino.Cantidad, "TRASLADO", entrada.RepuestoID, referencia); err != nil {
|
|
return err
|
|
}
|
|
|
|
resultado = ResultadoTraslado{Origen: origen, Destino: destino}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s.registrarLog("TRASLADO_STOCK", []models_logs.LogDetalle{
|
|
{Columna: "repuestoId", ValorNuevo: fmt.Sprintf("%d", entrada.RepuestoID)},
|
|
{Columna: "origenId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenOrigenID)},
|
|
{Columna: "destinoId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenDestinoID)},
|
|
{Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", cantidad)},
|
|
})
|
|
return &resultado, nil
|
|
}
|
|
|
|
// EntradaAjuste corrige la cantidad real de un ítem.
|
|
type EntradaAjuste struct {
|
|
StockID uint64
|
|
CantidadReal float64
|
|
Motivo string
|
|
Observacion string
|
|
}
|
|
|
|
// Ajustar deja el stock en la cantidad real indicada y registra la diferencia.
|
|
func (s *Servicio) Ajustar(entrada EntradaAjuste) (*models.Stock, error) {
|
|
if entrada.CantidadReal < 0 || math.IsNaN(entrada.CantidadReal) || math.IsInf(entrada.CantidadReal, 0) {
|
|
return nil, ErrCantidadInvalida
|
|
}
|
|
if strings.TrimSpace(entrada.Motivo) == "" {
|
|
return nil, ErrMotivoRequerido
|
|
}
|
|
if err := ValidarObservacion(entrada.Observacion); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
cantidadReal := redondearCantidad(entrada.CantidadReal)
|
|
var resultado *models.Stock
|
|
|
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
|
stock, err := s.repo.Stock.BloquearPorID(tx, entrada.StockID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return ErrStockNoEncontrado
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if cantidadReal < stock.CantidadReservada {
|
|
return fmt.Errorf("%w: reservado %.3f", ErrAjusteBajoReserva, stock.CantidadReservada)
|
|
}
|
|
|
|
saldoAnterior := stock.Cantidad
|
|
diferencia := redondearCantidad(cantidadReal - saldoAnterior)
|
|
stock.Cantidad = cantidadReal
|
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
|
return err
|
|
}
|
|
|
|
observacion := strings.TrimSpace(strings.Join([]string{entrada.Motivo, entrada.Observacion}, " - "))
|
|
if err := s.registrarMovimiento(tx, stock, models.MovimientoAjuste, diferencia, saldoAnterior, stock.Cantidad, "AJUSTE", stock.ID, observacion); err != nil {
|
|
return err
|
|
}
|
|
|
|
if diferencia != 0 {
|
|
if err := s.asientoAjuste(tx, stock, diferencia); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
resultado = stock
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s.registrarLog("AJUSTE_STOCK", []models_logs.LogDetalle{
|
|
{Columna: "stockId", ValorNuevo: fmt.Sprintf("%d", entrada.StockID)},
|
|
{Columna: "cantidadReal", ValorNuevo: fmt.Sprintf("%.3f", cantidadReal)},
|
|
{Columna: "motivo", ValorNuevo: entrada.Motivo},
|
|
})
|
|
return resultado, nil
|
|
}
|
|
|
|
// ItemIngreso es un renglón del remito de compra.
|
|
type ItemIngreso struct {
|
|
RepuestoID uint64
|
|
CantidadEsperada float64
|
|
CantidadRecibida float64
|
|
UnidadMedida string
|
|
Observacion string
|
|
}
|
|
|
|
// EntradaIngreso registra el ingreso de mercadería con remito.
|
|
type EntradaIngreso struct {
|
|
ProveedorID uint
|
|
Numero string
|
|
FechaEmision time.Time
|
|
AlmacenDestinoID uint
|
|
Observacion string
|
|
Items []ItemIngreso
|
|
}
|
|
|
|
type ResultadoIngreso struct {
|
|
Remito *models.Remito
|
|
Diferencias []models.DiferenciaRemito
|
|
Stocks []*models.Stock
|
|
}
|
|
|
|
// Ingresar crea el remito, actualiza stock, registra diferencias y asiento.
|
|
func (s *Servicio) Ingresar(entrada EntradaIngreso) (*ResultadoIngreso, error) {
|
|
if entrada.ProveedorID == 0 {
|
|
return nil, ErrProveedorNoEncontrado
|
|
}
|
|
if entrada.AlmacenDestinoID == 0 {
|
|
return nil, ErrAlmacenInvalido
|
|
}
|
|
if entrada.FechaEmision.IsZero() {
|
|
return nil, fmt.Errorf("%w: fecha de emisión obligatoria", ErrMotivoRequerido)
|
|
}
|
|
if len(entrada.Items) == 0 {
|
|
return nil, fmt.Errorf("%w: el remito debe tener al menos un ítem", ErrCantidadInvalida)
|
|
}
|
|
if err := ValidarObservacion(entrada.Observacion); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if _, err := s.repo.Proveedor.ObtenerPorID(entrada.ProveedorID); err != nil {
|
|
return nil, ErrProveedorNoEncontrado
|
|
}
|
|
if _, err := s.repo.Almacen.ObtenerPorID(entrada.AlmacenDestinoID); err != nil {
|
|
return nil, ErrAlmacenInvalido
|
|
}
|
|
|
|
items := append([]ItemIngreso(nil), entrada.Items...)
|
|
// Ordenar por repuesto para bloquear filas siempre en el mismo orden.
|
|
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
|
|
|
repuestos := make(map[uint64]*models.Repuesto, len(items))
|
|
vistos := make(map[uint64]bool, len(items))
|
|
for _, item := range items {
|
|
if item.RepuestoID == 0 {
|
|
return nil, ErrRepuestoNoEncontrado
|
|
}
|
|
if vistos[item.RepuestoID] {
|
|
return nil, fmt.Errorf("%w: %d", ErrItemDuplicado, item.RepuestoID)
|
|
}
|
|
vistos[item.RepuestoID] = true
|
|
if math.IsNaN(item.CantidadEsperada) || item.CantidadEsperada < 0 || math.IsNaN(item.CantidadRecibida) || item.CantidadRecibida < 0 {
|
|
return nil, ErrCantidadInvalida
|
|
}
|
|
if item.CantidadEsperada == 0 && item.CantidadRecibida == 0 {
|
|
return nil, ErrCantidadInvalida
|
|
}
|
|
if err := ValidarObservacion(item.Observacion); err != nil {
|
|
return nil, err
|
|
}
|
|
repuestoPtr, err := s.repo.Repuesto.ObtenerPorID(uint(item.RepuestoID))
|
|
if err != nil || repuestoPtr == nil || *repuestoPtr == nil {
|
|
return nil, fmt.Errorf("%w: %d", ErrRepuestoNoEncontrado, item.RepuestoID)
|
|
}
|
|
repuestos[item.RepuestoID] = *repuestoPtr
|
|
}
|
|
|
|
var resultado ResultadoIngreso
|
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
|
var existentes int64
|
|
query := tx.Model(&models.Remito{}).
|
|
Where("numero = ? AND proveedor_id = ?", entrada.Numero, entrada.ProveedorID)
|
|
if s.empresaID > 0 {
|
|
query = query.Where("empresa_id = ?", s.empresaID)
|
|
}
|
|
if err := query.Count(&existentes).Error; err != nil {
|
|
return err
|
|
}
|
|
if existentes > 0 {
|
|
return ErrRemitoDuplicado
|
|
}
|
|
|
|
remito := &models.Remito{
|
|
Numero: entrada.Numero,
|
|
FechaEmision: entrada.FechaEmision,
|
|
TipoOperacion: models.OperacionCompra,
|
|
EmisorID: entrada.ProveedorID,
|
|
ReceptorID: s.empresaID,
|
|
ProveedorID: &entrada.ProveedorID,
|
|
AlmacenDestinoID: &entrada.AlmacenDestinoID,
|
|
Observacion: entrada.Observacion,
|
|
}
|
|
remito.Estado = "confirmado"
|
|
remito.ResponsableID = s.usuarioID
|
|
|
|
var total float64
|
|
for _, item := range items {
|
|
repuesto := repuestos[item.RepuestoID]
|
|
recibida := redondearCantidad(item.CantidadRecibida)
|
|
total += redondearCantidad(recibida * repuesto.Precio)
|
|
remito.Detalles = append(remito.Detalles, models.RemitoDetalle{
|
|
ProductoID: uint(item.RepuestoID),
|
|
CantidadEsperada: redondearCantidad(item.CantidadEsperada),
|
|
CantidadRecibida: recibida,
|
|
UnidadMedida: item.UnidadMedida,
|
|
Observacion: item.Observacion,
|
|
})
|
|
}
|
|
total = redondearCantidad(total)
|
|
remito.Total = total
|
|
|
|
if err := s.repo.Remito.CrearConDetalles(tx, remito); err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, item := range items {
|
|
recibida := redondearCantidad(item.CantidadRecibida)
|
|
if recibida > 0 {
|
|
stock, err := s.bloquearOCrearStock(tx, item.RepuestoID, entrada.AlmacenDestinoID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
saldoAnterior := stock.Cantidad
|
|
stock.Cantidad = redondearCantidad(stock.Cantidad + recibida)
|
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
|
return err
|
|
}
|
|
if err := s.registrarMovimiento(tx, stock, models.MovimientoIngreso, recibida, saldoAnterior, stock.Cantidad, "REMITO", uint64(remito.ID), remito.Numero); err != nil {
|
|
return err
|
|
}
|
|
resultado.Stocks = append(resultado.Stocks, stock)
|
|
}
|
|
|
|
esperada := redondearCantidad(item.CantidadEsperada)
|
|
if esperada != recibida {
|
|
diferencia := &models.DiferenciaRemito{
|
|
RemitoID: remito.ID,
|
|
RepuestoID: item.RepuestoID,
|
|
CantidadEsperada: esperada,
|
|
CantidadRecibida: recibida,
|
|
Diferencia: redondearCantidad(recibida - esperada),
|
|
UsuarioID: s.usuarioID,
|
|
Observacion: item.Observacion,
|
|
}
|
|
if err := s.repo.DiferenciaRemito.Registrar(tx, diferencia); err != nil {
|
|
return err
|
|
}
|
|
resultado.Diferencias = append(resultado.Diferencias, *diferencia)
|
|
}
|
|
}
|
|
|
|
if total > 0 {
|
|
if err := s.registrarAsiento(tx, "REMITO", remito.ID, []lineaAsiento{
|
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: total, descripcion: "Ingreso de mercadería"},
|
|
{cuenta: cuentaProveedores, tipo: tipoPasivo, haber: total, descripcion: "Compra con remito"},
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
resultado.Remito = remito
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s.registrarLog("INGRESO_STOCK", []models_logs.LogDetalle{
|
|
{Columna: "remitoId", ValorNuevo: fmt.Sprintf("%d", resultado.Remito.ID)},
|
|
{Columna: "numero", ValorNuevo: entrada.Numero},
|
|
{Columna: "items", ValorNuevo: fmt.Sprintf("%d", len(items))},
|
|
{Columna: "diferencias", ValorNuevo: fmt.Sprintf("%d", len(resultado.Diferencias))},
|
|
})
|
|
return &resultado, nil
|
|
}
|
|
|
|
// EntradaReserva descuenta disponible sin mover la cantidad física.
|
|
type EntradaReserva struct {
|
|
RepuestoID uint64
|
|
AlmacenID uint
|
|
Cantidad float64
|
|
ClienteID *uint
|
|
FechaVencimiento *time.Time
|
|
Observacion string
|
|
}
|
|
|
|
// Reservar bloquea stock, incrementa lo reservado y crea la reserva activa.
|
|
func (s *Servicio) Reservar(entrada EntradaReserva) (*models.Reserva, error) {
|
|
if err := ValidarCantidad(entrada.Cantidad); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := ValidarObservacion(entrada.Observacion); err != nil {
|
|
return nil, err
|
|
}
|
|
if entrada.FechaVencimiento != nil && !entrada.FechaVencimiento.After(time.Now()) {
|
|
return nil, ErrFechaVencimiento
|
|
}
|
|
if entrada.ClienteID != nil {
|
|
if _, err := s.repo.Cliente.ObtenerPorID(*entrada.ClienteID); err != nil {
|
|
return nil, fmt.Errorf("%w: cliente %d", ErrItemNoEncontrado, *entrada.ClienteID)
|
|
}
|
|
}
|
|
|
|
cantidad := redondearCantidad(entrada.Cantidad)
|
|
var reserva *models.Reserva
|
|
|
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
|
stock, err := s.repo.Stock.BloquearPorRepuestoAlmacen(tx, entrada.RepuestoID, entrada.AlmacenID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return ErrStockNoEncontrado
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if Disponible(stock) < cantidad {
|
|
return fmt.Errorf("%w: disponible %.3f, solicitado %.3f", ErrStockInsuficiente, Disponible(stock), cantidad)
|
|
}
|
|
|
|
saldoReservado := stock.CantidadReservada
|
|
stock.CantidadReservada = redondearCantidad(stock.CantidadReservada + cantidad)
|
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
|
return err
|
|
}
|
|
|
|
reserva = &models.Reserva{
|
|
RepuestoID: uint(entrada.RepuestoID),
|
|
AlmacenID: entrada.AlmacenID,
|
|
Cantidad: cantidad,
|
|
Estado: models.ReservaActiva,
|
|
ClienteID: entrada.ClienteID,
|
|
CreadoPorID: s.usuarioID,
|
|
Observacion: entrada.Observacion,
|
|
}
|
|
if entrada.FechaVencimiento != nil {
|
|
reserva.FechaVencimiento = *entrada.FechaVencimiento
|
|
}
|
|
if s.empresaID > 0 {
|
|
reserva.EmpresaID = s.empresaID
|
|
}
|
|
if reserva.Estado == "" {
|
|
reserva.Estado = models.ReservaActiva
|
|
}
|
|
if err := tx.Create(reserva).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
return s.registrarMovimiento(tx, stock, models.MovimientoReserva, cantidad, saldoReservado, stock.CantidadReservada, "RESERVA", uint64(reserva.ID), entrada.Observacion)
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s.registrarLog("RESERVAR_STOCK", []models_logs.LogDetalle{
|
|
{Columna: "reservaId", ValorNuevo: fmt.Sprintf("%d", reserva.ID)},
|
|
{Columna: "repuestoId", ValorNuevo: fmt.Sprintf("%d", entrada.RepuestoID)},
|
|
{Columna: "almacenId", ValorNuevo: fmt.Sprintf("%d", entrada.AlmacenID)},
|
|
{Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", cantidad)},
|
|
})
|
|
return reserva, nil
|
|
}
|
|
|
|
// Liberar devuelve el disponible de una reserva activa.
|
|
func (s *Servicio) Liberar(reservaID uint) (*models.Reserva, error) {
|
|
var reserva *models.Reserva
|
|
|
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
|
actual, err := s.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 := s.repo.Stock.BloquearPorRepuestoAlmacen(tx, uint64(actual.RepuestoID), actual.AlmacenID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return ErrStockNoEncontrado
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
liberada, err := s.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 := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
|
return err
|
|
}
|
|
if err := s.registrarMovimiento(tx, 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
|
|
}
|
|
|
|
s.registrarLog("LIBERAR_RESERVA", []models_logs.LogDetalle{
|
|
{Columna: "reservaId", ValorNuevo: fmt.Sprintf("%d", reserva.ID)},
|
|
{Columna: "cantidad", ValorNuevo: fmt.Sprintf("%.3f", reserva.Cantidad)},
|
|
})
|
|
return reserva, nil
|
|
}
|
|
|
|
// ItemDevolucion es un renglón devuelto de una factura.
|
|
type ItemDevolucion struct {
|
|
RepuestoID uint64
|
|
Cantidad float64
|
|
PrecioUnitario float64
|
|
}
|
|
|
|
// EntradaDevolucion registra una devolución sobre una factura.
|
|
type EntradaDevolucion struct {
|
|
FacturaID uint
|
|
AlmacenID uint
|
|
Motivo string
|
|
Items []ItemDevolucion
|
|
}
|
|
|
|
type ResultadoDevolucion struct {
|
|
Devolucion *models.Devolucion
|
|
Stocks []*models.Stock
|
|
}
|
|
|
|
// Devolver valida contra lo vendido, repone stock y registra el comprobante.
|
|
func (s *Servicio) Devolver(entrada EntradaDevolucion) (*ResultadoDevolucion, error) {
|
|
if strings.TrimSpace(entrada.Motivo) == "" {
|
|
return nil, ErrMotivoRequerido
|
|
}
|
|
if len(entrada.Items) == 0 {
|
|
return nil, fmt.Errorf("%w: la devolución debe tener al menos un ítem", ErrCantidadInvalida)
|
|
}
|
|
|
|
factura, err := s.repo.Factura.ObtenerPorID(entrada.FacturaID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%w: factura %d", ErrItemNoEncontrado, entrada.FacturaID)
|
|
}
|
|
if strings.EqualFold(strings.TrimSpace(factura.Estado), "anulada") {
|
|
return nil, ErrFacturaAnulada
|
|
}
|
|
|
|
almacenID := entrada.AlmacenID
|
|
if almacenID == 0 {
|
|
almacenes, err := s.repo.Almacen.Listar()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(almacenes) == 0 {
|
|
return nil, ErrSinAlmacen
|
|
}
|
|
almacenID = almacenes[0].ID
|
|
} else if _, err := s.repo.Almacen.ObtenerPorID(almacenID); err != nil {
|
|
return nil, ErrAlmacenInvalido
|
|
}
|
|
|
|
items := append([]ItemDevolucion(nil), entrada.Items...)
|
|
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
|
|
|
vendidos := make(map[uint64]float64)
|
|
precios := make(map[uint64]float64)
|
|
for _, detalle := range factura.Detalles {
|
|
vendidos[detalle.RepuestoID] += float64(detalle.Cantidad)
|
|
precios[detalle.RepuestoID] = detalle.PrecioUnitario
|
|
}
|
|
|
|
anteriores, err := s.repo.Devolucion.ListarPorFactura(factura.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var resultado ResultadoDevolucion
|
|
err = s.db.Transaction(func(tx *gorm.DB) error {
|
|
devueltos := make(map[uint64]float64)
|
|
for _, devolucion := range anteriores {
|
|
for _, detalle := range devolucion.Detalles {
|
|
devueltos[detalle.RepuestoID] += detalle.Cantidad
|
|
}
|
|
}
|
|
|
|
devolucion := &models.Devolucion{
|
|
Motivo: entrada.Motivo,
|
|
FacturaOrigenID: factura.ID,
|
|
}
|
|
devolucion.Estado = "confirmada"
|
|
devolucion.ResponsableID = s.usuarioID
|
|
|
|
detalles := make([]models.DevolucionDetalle, 0, len(items))
|
|
for _, item := range items {
|
|
if err := ValidarCantidad(item.Cantidad); err != nil {
|
|
return err
|
|
}
|
|
vendido, ok := vendidos[item.RepuestoID]
|
|
if !ok {
|
|
return fmt.Errorf("%w: %d", ErrItemNoEncontrado, item.RepuestoID)
|
|
}
|
|
cantidad := redondearCantidad(item.Cantidad)
|
|
if cantidad > redondearCantidad(vendido-devueltos[item.RepuestoID]) {
|
|
return fmt.Errorf("%w: repuesto %d, vendido %.3f, ya devuelto %.3f", ErrDevolucionExcedeVendido, item.RepuestoID, vendido, devueltos[item.RepuestoID])
|
|
}
|
|
|
|
precio := item.PrecioUnitario
|
|
if precio <= 0 {
|
|
precio = precios[item.RepuestoID]
|
|
}
|
|
detalles = append(detalles, models.DevolucionDetalle{
|
|
RepuestoID: item.RepuestoID,
|
|
Cantidad: cantidad,
|
|
PrecioUnitario: precio,
|
|
Subtotal: redondearCantidad(cantidad * precio),
|
|
})
|
|
devolucion.Total = redondearCantidad(devolucion.Total + cantidad*precio)
|
|
}
|
|
devolucion.Detalles = detalles
|
|
|
|
if err := s.repo.Devolucion.CrearConDetalles(tx, devolucion); err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, detalle := range detalles {
|
|
stock, err := s.bloquearOCrearStock(tx, detalle.RepuestoID, almacenID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
saldoAnterior := stock.Cantidad
|
|
stock.Cantidad = redondearCantidad(stock.Cantidad + detalle.Cantidad)
|
|
if err := s.repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
|
return err
|
|
}
|
|
if err := s.registrarMovimiento(tx, stock, models.MovimientoDevolucion, detalle.Cantidad, saldoAnterior, stock.Cantidad, "DEVOLUCION", uint64(devolucion.ID), entrada.Motivo); err != nil {
|
|
return err
|
|
}
|
|
resultado.Stocks = append(resultado.Stocks, stock)
|
|
}
|
|
|
|
if devolucion.Total > 0 {
|
|
if err := s.registrarAsiento(tx, "DEVOLUCION", devolucion.ID, []lineaAsiento{
|
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: devolucion.Total, descripcion: "Devolución de mercadería"},
|
|
{cuenta: cuentaDevoluciones, tipo: tipoResultado, haber: devolucion.Total, descripcion: "Devoluciones sobre ventas"},
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
resultado.Devolucion = devolucion
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s.registrarLog("DEVOLUCION_STOCK", []models_logs.LogDetalle{
|
|
{Columna: "devolucionId", ValorNuevo: fmt.Sprintf("%d", resultado.Devolucion.ID)},
|
|
{Columna: "facturaId", ValorNuevo: fmt.Sprintf("%d", factura.ID)},
|
|
{Columna: "total", ValorNuevo: fmt.Sprintf("%.2f", resultado.Devolucion.Total)},
|
|
})
|
|
return &resultado, nil
|
|
}
|
|
|
|
// Comentar guarda el último comentario visible y su historial.
|
|
func (s *Servicio) Comentar(stockID uint64, texto string) (*models.Stock, error) {
|
|
texto = strings.TrimSpace(texto)
|
|
if texto == "" {
|
|
return nil, ErrComentarioVacio
|
|
}
|
|
if err := ValidarObservacion(texto); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var stock *models.Stock
|
|
err := s.db.Transaction(func(tx *gorm.DB) error {
|
|
actual, err := s.repo.Stock.BloquearPorID(tx, stockID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return ErrStockNoEncontrado
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := s.repo.Stock.ActualizarObservacion(tx, stockID, texto); err != nil {
|
|
return err
|
|
}
|
|
actual.Observacion = texto
|
|
stock = actual
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s.registrarLog("COMENTAR_STOCK", []models_logs.LogDetalle{
|
|
{Columna: "stockId", ValorNuevo: fmt.Sprintf("%d", stockID)},
|
|
{Columna: "observacion", ValorNuevo: texto},
|
|
})
|
|
return stock, nil
|
|
}
|
|
|
|
// buscarStockTx busca sin bloquear; el bloqueo se hace después en orden de ID.
|
|
func (s *Servicio) buscarStockTx(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error) {
|
|
var stock models.Stock
|
|
query := tx.Where("repuesto_id = ? AND almacen_id = ?", repuestoID, almacenID)
|
|
if s.empresaID > 0 {
|
|
query = query.Where("empresa_id = ?", s.empresaID)
|
|
}
|
|
if err := query.First(&stock).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &stock, nil
|
|
}
|
|
|
|
// bloquearOCrearStock obtiene la fila con FOR UPDATE o la crea en cero.
|
|
func (s *Servicio) bloquearOCrearStock(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error) {
|
|
stock, err := s.repo.Stock.BloquearPorRepuestoAlmacen(tx, repuestoID, almacenID)
|
|
if err == nil {
|
|
return stock, nil
|
|
}
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, err
|
|
}
|
|
|
|
nuevo := &models.Stock{RepuestoID: repuestoID, AlmacenID: almacenID}
|
|
if s.empresaID > 0 {
|
|
nuevo.EmpresaID = uint64(s.empresaID)
|
|
}
|
|
if err := tx.Create(nuevo).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return nuevo, nil
|
|
}
|
|
|
|
func (s *Servicio) registrarMovimiento(
|
|
tx *gorm.DB,
|
|
stock *models.Stock,
|
|
tipo models.TipoMovimientoStock,
|
|
cantidad float64,
|
|
saldoAnterior float64,
|
|
saldoPosterior float64,
|
|
referenciaTipo string,
|
|
referenciaID uint64,
|
|
observacion string,
|
|
) error {
|
|
movimiento := &models.MovimientoStock{
|
|
StockID: stock.ID,
|
|
RepuestoID: stock.RepuestoID,
|
|
AlmacenID: stock.AlmacenID,
|
|
Tipo: tipo,
|
|
Cantidad: redondearCantidad(cantidad),
|
|
SaldoAnterior: redondearCantidad(saldoAnterior),
|
|
SaldoPosterior: redondearCantidad(saldoPosterior),
|
|
ReferenciaTipo: referenciaTipo,
|
|
ReferenciaID: referenciaID,
|
|
UsuarioID: s.usuarioID,
|
|
Observacion: observacion,
|
|
Fecha: time.Now(),
|
|
}
|
|
return s.repo.MovimientoStock.Registrar(tx, movimiento)
|
|
}
|
|
|
|
const (
|
|
cuentaInventario = "Inventario"
|
|
cuentaProveedores = "Proveedores"
|
|
cuentaPerdida = "Pérdida por ajuste"
|
|
cuentaDevoluciones = "Devoluciones sobre ventas"
|
|
|
|
tipoActivo = "activo"
|
|
tipoPasivo = "pasivo"
|
|
tipoResultado = "resultado"
|
|
)
|
|
|
|
type lineaAsiento struct {
|
|
cuenta string
|
|
tipo string
|
|
debe float64
|
|
haber float64
|
|
descripcion string
|
|
}
|
|
|
|
// asientoAjuste registra la pérdida o recuperación de valor de un ajuste.
|
|
func (s *Servicio) asientoAjuste(tx *gorm.DB, stock *models.Stock, diferencia float64) error {
|
|
repuestoPtr, err := s.repo.Repuesto.ObtenerPorID(uint(stock.RepuestoID))
|
|
if err != nil || repuestoPtr == nil || *repuestoPtr == nil {
|
|
return fmt.Errorf("%w: %d", ErrRepuestoNoEncontrado, stock.RepuestoID)
|
|
}
|
|
monto := redondearCantidad(math.Abs(diferencia) * (*repuestoPtr).Precio)
|
|
if monto == 0 {
|
|
return nil
|
|
}
|
|
|
|
if diferencia < 0 {
|
|
return s.registrarAsiento(tx, "AJUSTE", uint(stock.ID), []lineaAsiento{
|
|
{cuenta: cuentaPerdida, tipo: tipoResultado, debe: monto, descripcion: "Faltante de inventario"},
|
|
{cuenta: cuentaInventario, tipo: tipoActivo, haber: monto, descripcion: "Ajuste negativo de stock"},
|
|
})
|
|
}
|
|
return s.registrarAsiento(tx, "AJUSTE", uint(stock.ID), []lineaAsiento{
|
|
{cuenta: cuentaInventario, tipo: tipoActivo, debe: monto, descripcion: "Ajuste positivo de stock"},
|
|
{cuenta: cuentaPerdida, tipo: tipoResultado, haber: monto, descripcion: "Sobrante de inventario"},
|
|
})
|
|
}
|
|
|
|
// registrarAsiento crea las cuentas si faltan y persiste el asiento completo.
|
|
func (s *Servicio) registrarAsiento(tx *gorm.DB, comprobanteTipo string, comprobanteID uint, lineas []lineaAsiento) error {
|
|
if !s.contabilidad || len(lineas) == 0 {
|
|
return nil
|
|
}
|
|
|
|
asiento := &contabilidad.AsientoContable{
|
|
ComprobanteTipo: comprobanteTipo,
|
|
ComprobanteID: comprobanteID,
|
|
}
|
|
for _, linea := range lineas {
|
|
if linea.debe == 0 && linea.haber == 0 {
|
|
continue
|
|
}
|
|
cuenta := &contabilidad.CuentaContable{Nombre: linea.cuenta, Tipo: linea.tipo}
|
|
if err := s.repo.Contabilidad.GuardarCuenta(tx, cuenta); err != nil {
|
|
return err
|
|
}
|
|
asiento.Movimientos = append(asiento.Movimientos, contabilidad.MovimientoContable{
|
|
CuentaID: cuenta.ID,
|
|
Debe: redondearCantidad(linea.debe),
|
|
Haber: redondearCantidad(linea.haber),
|
|
Descripcion: linea.descripcion,
|
|
})
|
|
}
|
|
if len(asiento.Movimientos) == 0 {
|
|
return nil
|
|
}
|
|
return s.repo.Contabilidad.CrearAsientoConMovimientos(tx, asiento)
|
|
}
|
|
|
|
// registrarLog guarda la auditoría fuera de la transacción: si falla, la
|
|
// operación de negocio ya confirmada no se revierte.
|
|
func (s *Servicio) registrarLog(accion string, detalles []models_logs.LogDetalle) {
|
|
log, err := dto_builders.NewLogDirector().Custom(s.usuarioID, accion, detalles)
|
|
if err != nil {
|
|
applog.Printf("stock: no se pudo construir el log de %s: %v", accion, err)
|
|
return
|
|
}
|
|
log.EmpresaID = s.empresaID
|
|
if err := s.repo.Logs.Crear(log, s.usuarioID); err != nil {
|
|
applog.Printf("stock: no se pudo registrar el log de %s: %v", accion, err)
|
|
}
|
|
}
|