Private
Public Access
falta testeo
This commit is contained in:
1 parent
9205fea8d8
commit
61ca620c8e
50 files changed
+3061
-1112
No files matched your search
@@ -1,11 +1,18 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
func ActualizarObservacion(c *gin.Context) {
|
||||
@@ -13,16 +20,33 @@ func ActualizarObservacion(c *gin.Context) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.ObservacionDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := nuevoServicio(c).Comentar(id, data.Observacion)
|
||||
texto := strings.TrimSpace(data.Observacion)
|
||||
if err := validarObservacion(texto); err != nil {
|
||||
responderError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
repos := repositorios.ObtenerRepositorios(c)
|
||||
resultado, err := repos.Stock.ActualizarObservacion(id, texto)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
responderError(c, ErrStockNoEncontrado)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
responderError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
registrarLog(repos, utils.EmpresaID(c), c.GetUint("userID"), "COMENTAR_STOCK", []models_logs.LogDetalle{
|
||||
{Columna: "stockId", ValorNuevo: fmt.Sprintf("%d", id)},
|
||||
{Columna: "observacion", ValorNuevo: texto},
|
||||
})
|
||||
c.JSON(http.StatusOK, resultado)
|
||||
}
|
||||
@@ -1,12 +1,20 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
stocksvc "repuestera_back/services/stock"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
func AjustarStock(c *gin.Context) {
|
||||
@@ -15,15 +23,77 @@ func AjustarStock(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
resultado, err := nuevoServicio(c).Ajustar(stocksvc.EntradaAjuste{
|
||||
StockID: data.StockID,
|
||||
CantidadReal: data.CantidadReal,
|
||||
Motivo: data.Motivo,
|
||||
Observacion: data.Observacion,
|
||||
})
|
||||
|
||||
resultado, err := ajustarStock(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
responderError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, resultado)
|
||||
}
|
||||
|
||||
// ajustarStock deja el stock en la cantidad real indicada y registra la diferencia.
|
||||
func ajustarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.AjusteDto) (*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 := db.Transaction(func(tx *gorm.DB) error {
|
||||
stock, err := 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 := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
observacion := strings.TrimSpace(strings.Join([]string{entrada.Motivo, entrada.Observacion}, " - "))
|
||||
if err := registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoAjuste, diferencia, saldoAnterior, stock.Cantidad, "AJUSTE", stock.ID, observacion); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if diferencia != 0 {
|
||||
if err := asientoAjuste(tx, repo, stock, diferencia); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
resultado = stock
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
registrarLog(repo, empresaID, usuarioID, "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
|
||||
}
|
||||
@@ -1,41 +1,207 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"sort"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
stocksvc "repuestera_back/services/stock"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
type resultadoIngreso struct {
|
||||
Remito *models.Remito
|
||||
Diferencias []models.DiferenciaRemito
|
||||
Stocks []*models.Stock
|
||||
}
|
||||
|
||||
func IngresarStock(c *gin.Context) {
|
||||
var data dto.IngresoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
items := make([]stocksvc.ItemIngreso, 0, len(data.Items))
|
||||
for _, it := range data.Items {
|
||||
items = append(items, stocksvc.ItemIngreso{
|
||||
RepuestoID: it.RepuestoID,
|
||||
CantidadEsperada: it.CantidadEsperada,
|
||||
CantidadRecibida: it.CantidadRecibida,
|
||||
UnidadMedida: it.UnidadMedida,
|
||||
Observacion: it.Observacion,
|
||||
})
|
||||
}
|
||||
resultado, err := nuevoServicio(c).Ingresar(stocksvc.EntradaIngreso{
|
||||
ProveedorID: data.ProveedorID,
|
||||
Numero: data.Numero,
|
||||
FechaEmision: data.FechaEmision,
|
||||
AlmacenDestinoID: data.AlmacenDestinoID,
|
||||
Observacion: data.Observacion,
|
||||
Items: items,
|
||||
})
|
||||
|
||||
resultado, err := ingresarStock(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
responderError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
|
||||
// ingresarStock crea el remito, actualiza stock, registra diferencias y asiento.
|
||||
func ingresarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.IngresoDto) (*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
|
||||
}
|
||||
|
||||
proveedor, err := repo.Proveedor.ObtenerPorID(entrada.ProveedorID)
|
||||
if err != nil || proveedor == nil {
|
||||
return nil, ErrProveedorNoEncontrado
|
||||
}
|
||||
if _, err := repo.Almacen.ObtenerPorID(entrada.AlmacenDestinoID); err != nil {
|
||||
return nil, ErrAlmacenInvalido
|
||||
}
|
||||
|
||||
items := append([]dto.ItemIngresoDto(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 := 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 := db.Transaction(func(tx *gorm.DB) error {
|
||||
existe, err := repo.Remito.ExisteNumeroProveedor(tx, entrada.Numero, entrada.ProveedorID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existe {
|
||||
return ErrRemitoDuplicado
|
||||
}
|
||||
|
||||
remito := &models.Remito{
|
||||
Numero: entrada.Numero,
|
||||
FechaEmision: entrada.FechaEmision,
|
||||
TipoOperacion: models.OperacionCompra,
|
||||
EmisorID: entrada.ProveedorID,
|
||||
ReceptorID: empresaID,
|
||||
ProveedorID: &entrada.ProveedorID,
|
||||
AlmacenDestinoID: &entrada.AlmacenDestinoID,
|
||||
Observacion: entrada.Observacion,
|
||||
}
|
||||
remito.Estado = "confirmado"
|
||||
remito.ResponsableID = 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 := repo.Remito.CrearConDetalles(tx, remito); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, item := range items {
|
||||
recibida := redondearCantidad(item.CantidadRecibida)
|
||||
if recibida > 0 {
|
||||
stock, err := repo.Stock.BloquearOCrearPorRepuestoAlmacen(tx, item.RepuestoID, entrada.AlmacenDestinoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
saldoAnterior := stock.Cantidad
|
||||
stock.Cantidad = redondearCantidad(stock.Cantidad + recibida)
|
||||
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := registrarMovimiento(tx, repo, usuarioID, 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: usuarioID,
|
||||
Observacion: item.Observacion,
|
||||
}
|
||||
if err := repo.DiferenciaRemito.Registrar(tx, diferencia); err != nil {
|
||||
return err
|
||||
}
|
||||
resultado.Diferencias = append(resultado.Diferencias, *diferencia)
|
||||
}
|
||||
}
|
||||
|
||||
if total > 0 {
|
||||
if err := registrarAsiento(tx, repo, "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
|
||||
}
|
||||
|
||||
registrarLog(repo, empresaID, usuarioID, "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))},
|
||||
})
|
||||
if len(resultado.Diferencias) > 0 {
|
||||
notificarDiferencias(repo, empresaID, usuarioID, resultado.Remito, proveedor.Nombre, resultado.Diferencias, repuestos)
|
||||
}
|
||||
return &resultado, nil
|
||||
}
|
||||
@@ -1,8 +1,18 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"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) {
|
||||
@@ -10,10 +20,72 @@ func LiberarReserva(c *gin.Context) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
resultado, err := nuevoServicio(c).Liberar(uint(id))
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
applog "log"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
)
|
||||
|
||||
// notificarDiferencias avisa por email las diferencias detectadas en un
|
||||
// ingreso y deja una entrada de auditoría. Nunca revierte el ingreso: si el
|
||||
// envío falla, las diferencias quedan sin NotificadaAt.
|
||||
func notificarDiferencias(
|
||||
repo *repositorios.Repositorios,
|
||||
empresaID, usuarioID uint,
|
||||
remito *models.Remito,
|
||||
proveedor string,
|
||||
diferencias []models.DiferenciaRemito,
|
||||
repuestos map[uint64]*models.Repuesto,
|
||||
) {
|
||||
if remito == nil || len(diferencias) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]string, 0, len(diferencias))
|
||||
detalles := make([]models_logs.LogDetalle, 0, len(diferencias)+5)
|
||||
for _, diferencia := range diferencias {
|
||||
nombre := fmt.Sprintf("Repuesto %d", diferencia.RepuestoID)
|
||||
if repuesto, ok := repuestos[diferencia.RepuestoID]; ok && repuesto != nil {
|
||||
nombre = repuesto.Nombre
|
||||
}
|
||||
|
||||
items = append(items, fmt.Sprintf(
|
||||
"%s | Esperado: %.3f | Recibido: %.3f | Diferencia: %.3f",
|
||||
nombre, diferencia.CantidadEsperada, diferencia.CantidadRecibida, diferencia.Diferencia,
|
||||
))
|
||||
detalles = append(detalles, models_logs.LogDetalle{
|
||||
Columna: fmt.Sprintf("repuesto_%d", diferencia.RepuestoID),
|
||||
ValorNuevo: fmt.Sprintf(
|
||||
"esperado %.3f, recibido %.3f, diferencia %.3f",
|
||||
diferencia.CantidadEsperada, diferencia.CantidadRecibida, diferencia.Diferencia,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
destinatarios := destinatariosDiferencias(repo, empresaID, usuarioID)
|
||||
enviado := false
|
||||
if len(destinatarios) > 0 {
|
||||
enviado = services.EnviarEmail(services.MensajeEmail{
|
||||
Titulo: fmt.Sprintf("Diferencia en remito %s", remito.Numero),
|
||||
Descripcion: fmt.Sprintf(
|
||||
"<p>Se detectaron <strong>%d</strong> diferencias al ingresar el remito "+
|
||||
"<strong>%s</strong> del proveedor <strong>%s</strong>.</p>"+
|
||||
"<p>Fecha de emisión: %s</p>"+
|
||||
"<p>Usuario responsable: %d</p>",
|
||||
len(diferencias), remito.Numero, proveedor,
|
||||
remito.FechaEmision.Format("02/01/2006"), usuarioID,
|
||||
),
|
||||
Items: items,
|
||||
Destinatarios: destinatarios,
|
||||
}, usuarioID)
|
||||
}
|
||||
|
||||
if enviado {
|
||||
ids := make([]uint64, 0, len(diferencias))
|
||||
for _, diferencia := range diferencias {
|
||||
ids = append(ids, diferencia.ID)
|
||||
}
|
||||
if err := repo.DiferenciaRemito.MarcarNotificadas(ids, time.Now()); err != nil {
|
||||
applog.Printf("stock: no se pudieron marcar las diferencias del remito %s como notificadas: %v", remito.Numero, err)
|
||||
}
|
||||
} else {
|
||||
applog.Printf("stock: no se pudo enviar el aviso de diferencias del remito %s", remito.Numero)
|
||||
}
|
||||
|
||||
detalles = append([]models_logs.LogDetalle{
|
||||
{Columna: "remitoId", ValorNuevo: fmt.Sprintf("%d", remito.ID)},
|
||||
{Columna: "numero", ValorNuevo: remito.Numero},
|
||||
{Columna: "proveedor", ValorNuevo: proveedor},
|
||||
{Columna: "emailEnviado", ValorNuevo: fmt.Sprintf("%t", enviado)},
|
||||
{Columna: "destinatarios", ValorNuevo: strings.Join(destinatarios, ", ")},
|
||||
}, detalles...)
|
||||
|
||||
registrarLog(repo, empresaID, usuarioID, "DIFERENCIA_REMITO", detalles)
|
||||
}
|
||||
|
||||
// destinatariosDiferencias usa STOCK_ALERT_EMAILS si está configurado. Si no,
|
||||
// avisa a los owners/admins activos de la empresa y, como último recurso, al
|
||||
// usuario que registró el ingreso.
|
||||
func destinatariosDiferencias(repo *repositorios.Repositorios, empresaID, usuarioID uint) []string {
|
||||
if raw := strings.TrimSpace(os.Getenv("STOCK_ALERT_EMAILS")); raw != "" {
|
||||
return limpiarDestinatarios(strings.Split(raw, ","))
|
||||
}
|
||||
|
||||
var destinatarios []string
|
||||
if empresaID > 0 {
|
||||
miembros, _, err := repo.Empresa.ListarMiembros(empresaID, 0, 100)
|
||||
if err == nil {
|
||||
for _, miembro := range miembros {
|
||||
if !miembro.Activo || !miembro.Rol.EsAdministrador() {
|
||||
continue
|
||||
}
|
||||
destinatarios = append(destinatarios, miembro.Usuario.Email)
|
||||
}
|
||||
}
|
||||
}
|
||||
destinatarios = limpiarDestinatarios(destinatarios)
|
||||
if len(destinatarios) > 0 {
|
||||
return destinatarios
|
||||
}
|
||||
|
||||
usuario, err := repo.Usuario.ObtenerPorID(usuarioID)
|
||||
if err == nil && usuario != nil {
|
||||
return limpiarDestinatarios([]string{usuario.Email})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func limpiarDestinatarios(destinatarios []string) []string {
|
||||
vistos := make(map[string]bool, len(destinatarios))
|
||||
limpios := make([]string, 0, len(destinatarios))
|
||||
for _, destinatario := range destinatarios {
|
||||
destinatario = strings.TrimSpace(destinatario)
|
||||
if destinatario == "" || vistos[destinatario] {
|
||||
continue
|
||||
}
|
||||
vistos[destinatario] = true
|
||||
limpios = append(limpios, destinatario)
|
||||
}
|
||||
return limpios
|
||||
}
|
||||
@@ -7,9 +7,8 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
r "repuestera_back/repositorios"
|
||||
"repuestera_back/models"
|
||||
stocksvc "repuestera_back/services/stock"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerStock(c *gin.Context) {
|
||||
@@ -36,7 +35,7 @@ func ObtenerStock(c *gin.Context) {
|
||||
if q.Estado != "" {
|
||||
filtrado := make([]models.Stock, 0, len(stocks))
|
||||
for i := range stocks {
|
||||
estado := string(stocksvc.EstadoStock(&stocks[i], &stocks[i].Repuesto))
|
||||
estado := string(estadoDe(&stocks[i], &stocks[i].Repuesto))
|
||||
if strings.EqualFold(estado, q.Estado) {
|
||||
filtrado = append(filtrado, stocks[i])
|
||||
}
|
||||
|
||||
@@ -1,37 +1,177 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
stocksvc "repuestera_back/services/stock"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
type resultadoDevolucion struct {
|
||||
Devolucion *models.Devolucion
|
||||
Stocks []*models.Stock
|
||||
}
|
||||
|
||||
func RegistrarDevolucion(c *gin.Context) {
|
||||
var data dto.DevolucionDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
items := make([]stocksvc.ItemDevolucion, 0, len(data.Items))
|
||||
for _, it := range data.Items {
|
||||
items = append(items, stocksvc.ItemDevolucion{
|
||||
RepuestoID: it.RepuestoID,
|
||||
Cantidad: it.Cantidad,
|
||||
PrecioUnitario: it.PrecioUnitario,
|
||||
})
|
||||
}
|
||||
resultado, err := nuevoServicio(c).Devolver(stocksvc.EntradaDevolucion{
|
||||
FacturaID: data.FacturaID,
|
||||
AlmacenID: data.AlmacenID,
|
||||
Motivo: data.Motivo,
|
||||
Items: items,
|
||||
})
|
||||
|
||||
resultado, err := registrarDevolucion(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
responderError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
|
||||
// registrarDevolucion valida contra lo vendido, repone stock y registra el comprobante.
|
||||
func registrarDevolucion(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.DevolucionDto) (*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 := 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 := repo.Almacen.Listar()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(almacenes) == 0 {
|
||||
return nil, ErrSinAlmacen
|
||||
}
|
||||
almacenID = almacenes[0].ID
|
||||
} else if _, err := repo.Almacen.ObtenerPorID(almacenID); err != nil {
|
||||
return nil, ErrAlmacenInvalido
|
||||
}
|
||||
|
||||
items := append([]dto.ItemDevolucionDto(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 := repo.Devolucion.ListarPorFactura(factura.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resultado resultadoDevolucion
|
||||
err = 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 = 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 := repo.Devolucion.CrearConDetalles(tx, devolucion); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, detalle := range detalles {
|
||||
stock, err := repo.Stock.BloquearOCrearPorRepuestoAlmacen(tx, detalle.RepuestoID, almacenID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
saldoAnterior := stock.Cantidad
|
||||
stock.Cantidad = redondearCantidad(stock.Cantidad + detalle.Cantidad)
|
||||
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := registrarMovimiento(tx, repo, usuarioID, 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 := registrarAsiento(tx, repo, "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
|
||||
}
|
||||
|
||||
registrarLog(repo, empresaID, usuarioID, "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
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
stocksvc "repuestera_back/services/stock"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
func ReservarStock(c *gin.Context) {
|
||||
@@ -15,14 +22,14 @@ func ReservarStock(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
resultado, err := nuevoServicio(c).Reservar(stocksvc.EntradaReserva{
|
||||
RepuestoID: data.RepuestoID,
|
||||
AlmacenID: data.AlmacenID,
|
||||
Cantidad: data.Cantidad,
|
||||
ClienteID: data.ClienteID,
|
||||
FechaVencimiento: data.FechaVencimiento,
|
||||
Observacion: data.Observacion,
|
||||
})
|
||||
|
||||
resultado, err := reservarStock(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
responderError(c, err)
|
||||
return
|
||||
@@ -30,3 +37,68 @@ func ReservarStock(c *gin.Context) {
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
|
||||
// reservarStock bloquea stock, incrementa lo reservado y crea la reserva activa.
|
||||
func reservarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.ReservaDto) (*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 _, err := repo.Cliente.ObtenerPorID(entrada.ClienteID); err != nil {
|
||||
return nil, fmt.Errorf("%w: cliente %d", ErrClienteNoEncontrado, entrada.ClienteID)
|
||||
}
|
||||
|
||||
cantidad := redondearCantidad(entrada.Cantidad)
|
||||
var reserva *models.Reserva
|
||||
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
stock, err := 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 := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
clienteID := entrada.ClienteID
|
||||
reserva = &models.Reserva{
|
||||
RepuestoID: uint(entrada.RepuestoID),
|
||||
AlmacenID: entrada.AlmacenID,
|
||||
Cantidad: cantidad,
|
||||
Estado: models.ReservaActiva,
|
||||
ClienteID: &clienteID,
|
||||
FechaVencimiento: entrada.FechaVencimiento,
|
||||
CreadoPorID: usuarioID,
|
||||
Observacion: entrada.Observacion,
|
||||
}
|
||||
if err := repo.Reserva.CrearTx(tx, reserva); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return registrarMovimiento(tx, repo, usuarioID, stock, models.MovimientoReserva, cantidad, saldoReservado, stock.CantidadReservada, "RESERVA", uint64(reserva.ID), entrada.Observacion)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
registrarLog(repo, empresaID, usuarioID, "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
|
||||
}
|
||||
@@ -1,30 +1,144 @@
|
||||
package stock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
dto "repuestera_back/dto/Stock"
|
||||
stocksvc "repuestera_back/services/stock"
|
||||
"repuestera_back/models"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
type resultadoTraslado struct {
|
||||
Origen *models.Stock
|
||||
Destino *models.Stock
|
||||
}
|
||||
|
||||
func TrasladarStock(c *gin.Context) {
|
||||
var data dto.TrasladoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
resultado, err := nuevoServicio(c).Trasladar(stocksvc.EntradaTraslado{
|
||||
RepuestoID: data.RepuestoID,
|
||||
AlmacenOrigenID: data.AlmacenOrigenID,
|
||||
AlmacenDestinoID: data.AlmacenDestinoID,
|
||||
Cantidad: data.Cantidad,
|
||||
Observacion: data.Observacion,
|
||||
})
|
||||
|
||||
resultado, err := trasladarStock(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
responderError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, resultado)
|
||||
}
|
||||
|
||||
// trasladarStock descuenta el origen y suma el destino en una sola transacción.
|
||||
func trasladarStock(db *gorm.DB, repo *repositorios.Repositorios, empresaID, usuarioID uint, entrada dto.TrasladoDto) (*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 := db.Transaction(func(tx *gorm.DB) error {
|
||||
origen, err := repo.Stock.BuscarPorRepuestoAlmacen(tx, entrada.RepuestoID, entrada.AlmacenOrigenID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrStockNoEncontrado
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
destino, errDestino := repo.Stock.BuscarPorRepuestoAlmacen(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 = repo.Stock.BloquearPorID(tx, destino.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
origen, err = repo.Stock.BloquearPorID(tx, origen.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
origen, err = repo.Stock.BloquearPorID(tx, origen.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existeDestino {
|
||||
destino, err = repo.Stock.BloquearPorID(tx, destino.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
destino, err = repo.Stock.BloquearOCrearPorRepuestoAlmacen(tx, entrada.RepuestoID, entrada.AlmacenDestinoID)
|
||||
if 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 := repo.Stock.ActualizarCantidades(tx, origen); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := repo.Stock.ActualizarCantidades(tx, destino); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
referencia := fmt.Sprintf("Traslado %d → %d", entrada.AlmacenOrigenID, entrada.AlmacenDestinoID)
|
||||
if err := registrarMovimiento(tx, repo, usuarioID, origen, models.MovimientoTrasladoSalida, -cantidad, saldoOrigen, origen.Cantidad, "TRASLADO", entrada.RepuestoID, referencia); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := registrarMovimiento(tx, repo, usuarioID, 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
|
||||
}
|
||||
|
||||
registrarLog(repo, empresaID, usuarioID, "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
|
||||
}
|
||||
@@ -2,42 +2,84 @@ package stock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
applog "log"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"repuestera_back/services/stock"
|
||||
dto_builders "repuestera_back/dto/Builders"
|
||||
"repuestera_back/models"
|
||||
"repuestera_back/models/contabilidad"
|
||||
models_logs "repuestera_back/models/logs"
|
||||
"repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
// 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")
|
||||
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")
|
||||
ErrClienteNoEncontrado = errors.New("el cliente 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")
|
||||
)
|
||||
|
||||
// estadoStock clasifica un ítem según su cantidad física y su mínimo.
|
||||
type estadoStock string
|
||||
|
||||
const (
|
||||
estadoAgotado estadoStock = "AGOTADO"
|
||||
estadoBajoMinimo estadoStock = "BAJO_MINIMO"
|
||||
estadoNormal estadoStock = "NORMAL"
|
||||
)
|
||||
|
||||
func codigoHTTP(err error) int {
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
return http.StatusNotFound
|
||||
case errors.Is(err, stock.ErrStockNoEncontrado),
|
||||
errors.Is(err, stock.ErrReservaInexistente),
|
||||
errors.Is(err, stock.ErrItemNoEncontrado),
|
||||
errors.Is(err, stock.ErrAlmacenInvalido),
|
||||
errors.Is(err, stock.ErrProveedorNoEncontrado),
|
||||
errors.Is(err, stock.ErrRepuestoNoEncontrado),
|
||||
errors.Is(err, stock.ErrSinAlmacen):
|
||||
case errors.Is(err, ErrStockNoEncontrado),
|
||||
errors.Is(err, ErrReservaInexistente),
|
||||
errors.Is(err, ErrItemNoEncontrado),
|
||||
errors.Is(err, ErrAlmacenInvalido),
|
||||
errors.Is(err, ErrProveedorNoEncontrado),
|
||||
errors.Is(err, ErrClienteNoEncontrado),
|
||||
errors.Is(err, ErrRepuestoNoEncontrado),
|
||||
errors.Is(err, ErrSinAlmacen):
|
||||
return http.StatusNotFound
|
||||
case errors.Is(err, stock.ErrReservaYaLiberada),
|
||||
errors.Is(err, stock.ErrFacturaAnulada),
|
||||
errors.Is(err, stock.ErrItemDuplicado),
|
||||
errors.Is(err, stock.ErrRemitoDuplicado):
|
||||
case errors.Is(err, ErrReservaYaLiberada),
|
||||
errors.Is(err, ErrFacturaAnulada),
|
||||
errors.Is(err, ErrItemDuplicado),
|
||||
errors.Is(err, ErrRemitoDuplicado):
|
||||
return http.StatusConflict
|
||||
case errors.Is(err, stock.ErrComentarioLargo),
|
||||
errors.Is(err, stock.ErrComentarioVacio),
|
||||
errors.Is(err, stock.ErrMotivoRequerido),
|
||||
errors.Is(err, stock.ErrCantidadInvalida),
|
||||
errors.Is(err, stock.ErrFechaVencimiento),
|
||||
errors.Is(err, stock.ErrAjusteBajoReserva):
|
||||
case errors.Is(err, ErrComentarioLargo),
|
||||
errors.Is(err, ErrMotivoRequerido),
|
||||
errors.Is(err, ErrCantidadInvalida),
|
||||
errors.Is(err, ErrFechaVencimiento),
|
||||
errors.Is(err, ErrAjusteBajoReserva):
|
||||
return http.StatusBadRequest
|
||||
case errors.Is(err, stock.ErrStockInsuficiente),
|
||||
errors.Is(err, stock.ErrMismoAlmacen),
|
||||
errors.Is(err, stock.ErrDevolucionExcedeVendido):
|
||||
case errors.Is(err, ErrStockInsuficiente),
|
||||
errors.Is(err, ErrMismoAlmacen),
|
||||
errors.Is(err, ErrDevolucionExcedeVendido):
|
||||
return http.StatusUnprocessableEntity
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
@@ -57,6 +99,161 @@ func parseUintParam(c *gin.Context, name string) (uint64, error) {
|
||||
return uid, nil
|
||||
}
|
||||
|
||||
func nuevoServicio(c *gin.Context) *stock.Servicio {
|
||||
return stock.Nuevo(c)
|
||||
// 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)
|
||||
}
|
||||
|
||||
// estadoDe devuelve AGOTADO, BAJO_MINIMO o NORMAL.
|
||||
func estadoDe(stock *models.Stock, repuesto *models.Repuesto) estadoStock {
|
||||
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
|
||||
}
|
||||
|
||||
func registrarMovimiento(
|
||||
tx *gorm.DB,
|
||||
repo *repositorios.Repositorios,
|
||||
usuarioID uint,
|
||||
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: usuarioID,
|
||||
Observacion: observacion,
|
||||
Fecha: time.Now(),
|
||||
}
|
||||
return 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 asientoAjuste(tx *gorm.DB, repo *repositorios.Repositorios, stock *models.Stock, diferencia float64) error {
|
||||
repuestoPtr, err := 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 registrarAsiento(tx, repo, "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 registrarAsiento(tx, repo, "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 registrarAsiento(tx *gorm.DB, repo *repositorios.Repositorios, comprobanteTipo string, comprobanteID uint, lineas []lineaAsiento) error {
|
||||
if 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 := 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 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 registrarLog(repo *repositorios.Repositorios, empresaID, usuarioID uint, accion string, detalles []models_logs.LogDetalle) {
|
||||
log, err := dto_builders.NewLogDirector().Custom(usuarioID, accion, detalles)
|
||||
if err != nil {
|
||||
applog.Printf("stock: no se pudo construir el log de %s: %v", accion, err)
|
||||
return
|
||||
}
|
||||
log.EmpresaID = empresaID
|
||||
if err := repo.Logs.Crear(log, usuarioID); err != nil {
|
||||
applog.Printf("stock: no se pudo registrar el log de %s: %v", accion, err)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package dto
|
||||
|
||||
type AjusteDto struct {
|
||||
StockID uint64 `json:"stockId" binding:"required"`
|
||||
CantidadReal float64 `json:"cantidadReal" binding:"required"`
|
||||
CantidadReal float64 `json:"cantidadReal" binding:"gte=0"`
|
||||
Motivo string `json:"motivo" binding:"required"`
|
||||
Observacion string `json:"observacion"`
|
||||
}
|
||||
@@ -2,8 +2,8 @@ package dto
|
||||
|
||||
type ItemIngresoDto struct {
|
||||
RepuestoID uint64 `json:"repuestoId" binding:"required"`
|
||||
CantidadEsperada float64 `json:"cantidadEsperada" binding:"required"`
|
||||
CantidadRecibida float64 `json:"cantidadRecibida" binding:"required"`
|
||||
CantidadEsperada float64 `json:"cantidadEsperada" binding:"gte=0"`
|
||||
CantidadRecibida float64 `json:"cantidadRecibida" binding:"gte=0"`
|
||||
UnidadMedida string `json:"unidadMedida"`
|
||||
Observacion string `json:"observacion"`
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
package dto
|
||||
|
||||
type ObservacionDto struct {
|
||||
Observacion string `json:"observacion" binding:"required"`
|
||||
Observacion string `json:"observacion"`
|
||||
}
|
||||
@@ -6,7 +6,7 @@ type ReservaDto struct {
|
||||
RepuestoID uint64 `json:"repuestoId" binding:"required"`
|
||||
AlmacenID uint `json:"almacenId" binding:"required"`
|
||||
Cantidad float64 `json:"cantidad" binding:"required"`
|
||||
ClienteID *uint `json:"clienteId"`
|
||||
ClienteID uint `json:"clienteId" binding:"required"`
|
||||
FechaVencimiento *time.Time `json:"fechaVencimiento"`
|
||||
Observacion string `json:"observacion"`
|
||||
}
|
||||
@@ -8,7 +8,7 @@ type Factura struct {
|
||||
ProveedorID *uint `json:"proveedorId,omitempty"`
|
||||
Proveedor *Proveedor `gorm:"foreignKey:ProveedorID" json:"proveedor,omitempty"`
|
||||
SeAviso bool `gorm:"" json:"seAviso"`
|
||||
Detalles []FacturaDetalle `gorm:"type:json" json:"detalles,omitempty"`
|
||||
Detalles []FacturaDetalle `gorm:"serializer:json;type:json" json:"detalles,omitempty"`
|
||||
}
|
||||
|
||||
func (Factura) TableName() string {
|
||||
|
||||
@@ -18,7 +18,7 @@ type Reserva struct {
|
||||
Estado EstadoReserva `gorm:"type:varchar(20);not null;default:'activa';index;index:idx_reserva_empresa_estado_vencimiento,priority:2" json:"estado"`
|
||||
ClienteID *uint `json:"cliente_id,omitempty"`
|
||||
Cliente *Cliente `gorm:"foreignKey:ClienteID" json:"cliente,omitempty"`
|
||||
FechaVencimiento time.Time `gorm:"index;index:idx_reserva_empresa_estado_vencimiento,priority:3" json:"fecha_vencimiento,omitempty"`
|
||||
FechaVencimiento *time.Time `gorm:"index;index:idx_reserva_empresa_estado_vencimiento,priority:3" json:"fecha_vencimiento,omitempty"`
|
||||
CreadoPorID uint `gorm:"index" json:"creadoPorId,omitempty"`
|
||||
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package repositorios
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"repuestera_back/models"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -10,6 +12,7 @@ type RepositorioDiferenciaRemito interface {
|
||||
IRepositorio[models.DiferenciaRemito]
|
||||
Registrar(tx *gorm.DB, diferencia *models.DiferenciaRemito) error
|
||||
ListarPorRemito(remitoID uint) ([]models.DiferenciaRemito, error)
|
||||
MarcarNotificadas(ids []uint64, fecha time.Time) error
|
||||
}
|
||||
|
||||
type repositorioDiferenciaRemito struct {
|
||||
@@ -36,6 +39,19 @@ func (r *repositorioDiferenciaRemito) Registrar(tx *gorm.DB, diferencia *models.
|
||||
return tx.Create(diferencia).Error
|
||||
}
|
||||
|
||||
// MarcarNotificadas registra el momento en que se envió el aviso de las
|
||||
// diferencias. Si el envío falla, las filas quedan pendientes.
|
||||
func (r *repositorioDiferenciaRemito) MarcarNotificadas(ids []uint64, fecha time.Time) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query := r.db.Model(&models.DiferenciaRemito{}).Where("id IN ?", ids)
|
||||
if r.empresaID > 0 {
|
||||
query = query.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
return query.Update("notificada_at", fecha).Error
|
||||
}
|
||||
|
||||
func (r *repositorioDiferenciaRemito) ListarPorRemito(remitoID uint) ([]models.DiferenciaRemito, error) {
|
||||
var diferencias []models.DiferenciaRemito
|
||||
if err := r.db.
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
type RepositorioRemito interface {
|
||||
IRepositorio[models.Remito]
|
||||
CrearConDetalles(tx *gorm.DB, remito *models.Remito) error
|
||||
ExisteNumeroProveedor(tx *gorm.DB, numero string, proveedorID uint) (bool, error)
|
||||
ObtenerConDetalles(id uint) (*models.Remito, error)
|
||||
}
|
||||
|
||||
@@ -37,6 +38,21 @@ func (r *repositorioRemito) CrearConDetalles(tx *gorm.DB, remito *models.Remito)
|
||||
return tx.Create(remito).Error
|
||||
}
|
||||
|
||||
// ExisteNumeroProveedor indica si ya hay un remito con ese numero para el proveedor.
|
||||
func (r *repositorioRemito) ExisteNumeroProveedor(tx *gorm.DB, numero string, proveedorID uint) (bool, error) {
|
||||
query := tx.Model(&models.Remito{}).
|
||||
Where("numero = ? AND proveedor_id = ?", numero, proveedorID)
|
||||
if r.empresaID > 0 {
|
||||
query = query.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return total > 0, nil
|
||||
}
|
||||
|
||||
func (r *repositorioRemito) ObtenerConDetalles(id uint) (*models.Remito, error) {
|
||||
var remito models.Remito
|
||||
if err := r.db.
|
||||
|
||||
@@ -22,6 +22,7 @@ type FiltrosReserva struct {
|
||||
type RepositorioReserva interface {
|
||||
IRepositorio[models.Reserva]
|
||||
ListarActivas(filtros FiltrosReserva) ([]models.Reserva, error)
|
||||
CrearTx(tx *gorm.DB, reserva *models.Reserva) error
|
||||
Liberar(tx *gorm.DB, id uint) (bool, error)
|
||||
MarcarVencidas(ahora time.Time) (int64, error)
|
||||
}
|
||||
@@ -77,6 +78,17 @@ func (r *repositorioReserva) ListarActivas(filtros FiltrosReserva) ([]models.Res
|
||||
return reservas, nil
|
||||
}
|
||||
|
||||
// CrearTx persiste una reserva dentro de una transaccion y le asigna la empresa activa.
|
||||
func (r *repositorioReserva) CrearTx(tx *gorm.DB, reserva *models.Reserva) error {
|
||||
if reserva == nil {
|
||||
return gorm.ErrInvalidValue
|
||||
}
|
||||
if r.empresaID > 0 {
|
||||
reserva.EmpresaID = r.empresaID
|
||||
}
|
||||
return tx.Create(reserva).Error
|
||||
}
|
||||
|
||||
// Liberar marca la reserva como liberada si seguia activa.
|
||||
// Devuelve false cuando la reserva ya no estaba activa.
|
||||
func (r *repositorioReserva) Liberar(tx *gorm.DB, id uint) (bool, error) {
|
||||
|
||||
@@ -24,11 +24,13 @@ type RepositorioStock interface {
|
||||
IRepositorio[models.Stock]
|
||||
Listar(filtros FiltrosStock) ([]models.Stock, error)
|
||||
ObtenerPorRepuestoAlmacen(repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||
BuscarPorRepuestoAlmacen(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||
BloquearOCrearPorRepuestoAlmacen(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||
CrearSiNoExiste(stock *models.Stock) error
|
||||
BloquearPorID(tx *gorm.DB, id uint64) (*models.Stock, error)
|
||||
BloquearPorRepuestoAlmacen(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error)
|
||||
ActualizarCantidades(tx *gorm.DB, stock *models.Stock) error
|
||||
ActualizarObservacion(tx *gorm.DB, id uint64, texto string) error
|
||||
ActualizarObservacion(id uint64, texto string) (*models.Stock, error)
|
||||
}
|
||||
|
||||
type repositorioStock struct {
|
||||
@@ -95,6 +97,40 @@ func (r *repositorioStock) ObtenerPorRepuestoAlmacen(repuestoID uint64, almacenI
|
||||
return &stock, nil
|
||||
}
|
||||
|
||||
// BuscarPorRepuestoAlmacen busca una fila dentro de una transaccion sin bloquearla.
|
||||
func (r *repositorioStock) BuscarPorRepuestoAlmacen(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 r.empresaID > 0 {
|
||||
query = query.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
if err := query.First(&stock).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &stock, nil
|
||||
}
|
||||
|
||||
// BloquearOCrearPorRepuestoAlmacen obtiene la fila con FOR UPDATE o la crea
|
||||
// en cero para la empresa activa.
|
||||
func (r *repositorioStock) BloquearOCrearPorRepuestoAlmacen(tx *gorm.DB, repuestoID uint64, almacenID uint) (*models.Stock, error) {
|
||||
stock, err := r.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 r.empresaID > 0 {
|
||||
nuevo.EmpresaID = uint64(r.empresaID)
|
||||
}
|
||||
if err := tx.Create(nuevo).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nuevo, nil
|
||||
}
|
||||
|
||||
func (r *repositorioStock) CrearSiNoExiste(stock *models.Stock) error {
|
||||
if stock == nil {
|
||||
return errors.New("stock nil")
|
||||
@@ -155,12 +191,29 @@ func (r *repositorioStock) BloquearPorRepuestoAlmacen(tx *gorm.DB, repuestoID ui
|
||||
}
|
||||
|
||||
// ActualizarObservacion guarda el ultimo comentario visible del item.
|
||||
func (r *repositorioStock) ActualizarObservacion(tx *gorm.DB, id uint64, texto string) error {
|
||||
query := tx.Model(&models.Stock{}).Where("id = ?", id)
|
||||
if r.empresaID > 0 {
|
||||
query = query.Where("empresa_id = ?", r.empresaID)
|
||||
// Un texto vacio elimina la observacion actual.
|
||||
func (r *repositorioStock) ActualizarObservacion(id uint64, texto string) (*models.Stock, error) {
|
||||
var stock *models.Stock
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
actual, err := r.BloquearPorID(tx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
query := tx.Model(&models.Stock{}).Where("id = ?", id)
|
||||
if r.empresaID > 0 {
|
||||
query = query.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
if err := query.Update("observacion", texto).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
actual.Observacion = texto
|
||||
stock = actual
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return query.Update("observacion", texto).Error
|
||||
return stock, nil
|
||||
}
|
||||
|
||||
func normalizarPagina(pagina, porPagina int) (int, int) {
|
||||
|
||||
+57
-14
@@ -12,10 +12,22 @@ import (
|
||||
"repuestera_back/jwtutils"
|
||||
)
|
||||
|
||||
// EnviarEmailInvitacion intenta notificar la invitación usando el servicio
|
||||
// comms. Un fallo de email no invalida la invitación: el link se devuelve al
|
||||
// administrador para que pueda compartirlo.
|
||||
func EnviarEmailInvitacion(destino, empresa, rol, link string, creadorID uint) bool {
|
||||
// MensajeEmail es el contrato que espera el servicio comms en POST /email.
|
||||
type MensajeEmail struct {
|
||||
Titulo string
|
||||
Descripcion string
|
||||
Items []string
|
||||
Destinatarios []string
|
||||
}
|
||||
|
||||
// EnviarEmail publica un mensaje en el servicio comms. Devuelve false si no
|
||||
// hay destinatarios, si comms no responde o si rechaza el envío.
|
||||
func EnviarEmail(mensaje MensajeEmail, creadorID uint) bool {
|
||||
destinatarios := normalizarDestinatarios(mensaje.Destinatarios)
|
||||
if len(destinatarios) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
base := strings.TrimRight(os.Getenv("COMMS_URL"), "/")
|
||||
if base == "" {
|
||||
base = "http://comms:8088"
|
||||
@@ -28,18 +40,16 @@ func EnviarEmailInvitacion(destino, empresa, rol, link string, creadorID uint) b
|
||||
return false
|
||||
}
|
||||
|
||||
descripcion := fmt.Sprintf(
|
||||
"<p>Fuiste invitado a <strong>%s</strong> con el rol <strong>%s</strong>.</p>"+
|
||||
"<p><a href=\"%s\">Aceptar invitación</a></p>"+
|
||||
"<p>Si el enlace no funciona, copiá esta dirección: %s</p>",
|
||||
empresa, rol, link, link,
|
||||
)
|
||||
items := mensaje.Items
|
||||
if items == nil {
|
||||
items = []string{}
|
||||
}
|
||||
|
||||
cuerpo, _ := json.Marshal(map[string]any{
|
||||
"titulo": "Invitación a " + empresa,
|
||||
"descripcion": descripcion,
|
||||
"items": []string{},
|
||||
"to": []string{destino},
|
||||
"titulo": mensaje.Titulo,
|
||||
"descripcion": mensaje.Descripcion,
|
||||
"items": items,
|
||||
"to": destinatarios,
|
||||
})
|
||||
|
||||
cliente := &http.Client{Timeout: 5 * time.Second}
|
||||
@@ -57,3 +67,36 @@ func EnviarEmailInvitacion(destino, empresa, rol, link string, creadorID uint) b
|
||||
defer resp.Body.Close()
|
||||
return resp.StatusCode >= 200 && resp.StatusCode < 300
|
||||
}
|
||||
|
||||
func normalizarDestinatarios(destinatarios []string) []string {
|
||||
vistos := make(map[string]bool, len(destinatarios))
|
||||
limpios := make([]string, 0, len(destinatarios))
|
||||
for _, destinatario := range destinatarios {
|
||||
destinatario = strings.TrimSpace(destinatario)
|
||||
if destinatario == "" || vistos[destinatario] {
|
||||
continue
|
||||
}
|
||||
vistos[destinatario] = true
|
||||
limpios = append(limpios, destinatario)
|
||||
}
|
||||
return limpios
|
||||
}
|
||||
|
||||
// EnviarEmailInvitacion intenta notificar la invitación usando el servicio
|
||||
// comms. Un fallo de email no invalida la invitación: el link se devuelve al
|
||||
// administrador para que pueda compartirlo.
|
||||
func EnviarEmailInvitacion(destino, empresa, rol, link string, creadorID uint) bool {
|
||||
descripcion := fmt.Sprintf(
|
||||
"<p>Fuiste invitado a <strong>%s</strong> con el rol <strong>%s</strong>.</p>"+
|
||||
"<p><a href=\"%s\">Aceptar invitación</a></p>"+
|
||||
"<p>Si el enlace no funciona, copiá esta dirección: %s</p>",
|
||||
empresa, rol, link, link,
|
||||
)
|
||||
|
||||
return EnviarEmail(MensajeEmail{
|
||||
Titulo: "Invitación a " + empresa,
|
||||
Descripcion: descripcion,
|
||||
Items: []string{},
|
||||
Destinatarios: []string{destino},
|
||||
}, creadorID)
|
||||
}
|
||||
@@ -1,996 +0,0 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerAlmacenes(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/almacenes/`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerClientes(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/clientes/`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerFacturas(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/facturas/`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerProveedores(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/proveedores/`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function ajustarStock(body: any) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/stock/ajustes`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function comentarStock(id: number, observacion: string) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/stock/${id}/observacion`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify({ observacion })
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function ingresarStock(body: any) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/stock/ingresos`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function liberarReserva(id: number) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/stock/reservas/${id}/liberar`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerReservas(fetch2?: Function) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/stock/reservas`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerStock(
|
||||
fetch2?: Function,
|
||||
filtros?: { q?: string; almacenId?: number; estado?: string }
|
||||
) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (filtros?.q) params.set('q', filtros.q);
|
||||
if (filtros?.almacenId) params.set('almacenId', String(filtros.almacenId));
|
||||
if (filtros?.estado) params.set('estado', filtros.estado);
|
||||
const path = `${API_URL}/stock/?${params.toString()}`;
|
||||
const req = await fetchfn(path, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${getToken()}`
|
||||
}
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error;
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function registrarDevolucion(body: {
|
||||
facturaId: number;
|
||||
almacenId?: number;
|
||||
motivo: string;
|
||||
items: Array<{ repuestoId: number; cantidad: number; precioUnitario?: number }>;
|
||||
}) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/stock/devoluciones`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function reservarStock(body: any) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/stock/reservas`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function trasladarStock(body: any) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/stock/traslados`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -9,3 +9,14 @@
|
||||
font-size: 1.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* En los temas oscuros el icono nativo del calendario es negro y se pierde.
|
||||
Le damos un fondo claro para que quede visible. */
|
||||
[theme='g80'] input[type='date']::-webkit-calendar-picker-indicator,
|
||||
[theme='g90'] input[type='date']::-webkit-calendar-picker-indicator,
|
||||
[theme='g100'] input[type='date']::-webkit-calendar-picker-indicator {
|
||||
background-color: #fff;
|
||||
border-radius: 2px;
|
||||
cursor: pointer;
|
||||
opacity: 1;
|
||||
}
|
||||
@@ -61,8 +61,8 @@
|
||||
datePickerType="range"
|
||||
on:change={(e) => {
|
||||
const dates = e.detail as { selectedDates: Date[] };
|
||||
filtros.fechaInicio = dates.selectedDates[0] ?? '';
|
||||
filtros.fechaFin = dates.selectedDates[1] ?? '';
|
||||
filtros.fechaInicio = dates.selectedDates[0]?.toISOString().slice(0, 10) ?? '';
|
||||
filtros.fechaFin = dates.selectedDates[1]?.toISOString().slice(0, 10) ?? '';
|
||||
}}
|
||||
>
|
||||
<DatePickerInput labelText="Fecha inicio" placeholder="mm/dd/yyyy" />
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
<script lang="ts">
|
||||
import Header from '$lib/components/Header.svelte';
|
||||
import {
|
||||
Button,
|
||||
DataTableSkeleton,
|
||||
InlineNotification,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
} from 'carbon-components-svelte';
|
||||
import { InventoryManagement, Play, Return } from 'carbon-icons-svelte';
|
||||
import { goto, invalidate } from '$app/navigation';
|
||||
import ModalStructured from '$lib/components/ModalStructured.svelte';
|
||||
import FiltrosStock from './FiltrosStock.svelte';
|
||||
import TablaStock from './TablaStock.svelte';
|
||||
import TrasladarStockForm from './TrasladarStockForm.svelte';
|
||||
import AjustarStockForm from './AjustarStockForm.svelte';
|
||||
import ReservarStockForm from './ReservarStockForm.svelte';
|
||||
import ComentarStockForm from './ComentarStockForm.svelte';
|
||||
import IngresarStockForm from './IngresarStockForm.svelte';
|
||||
import DevolucionStockForm from './DevolucionStockForm.svelte';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import { liberarReserva } from '$lib/hooks/stock/liberarReserva';
|
||||
import type { Almacen, Cliente, ReservaStock, StockItem } from '../../types';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
let error = $state('');
|
||||
|
||||
$effect(() => {
|
||||
if (data.error) error = data.error;
|
||||
});
|
||||
|
||||
let stock = $derived<StockItem[]>(Array.isArray(data.stock) ? data.stock : []);
|
||||
let almacenes = $derived<Almacen[]>(Array.isArray(data.almacenes) ? data.almacenes : []);
|
||||
let clientes = $derived<Cliente[]>(Array.isArray(data.clientes) ? data.clientes : []);
|
||||
let reservas = $derived<ReservaStock[]>(Array.isArray(data.reservas) ? data.reservas : []);
|
||||
let filtros = $derived(data.filtros ?? { q: '', almacenId: 0, estado: '' });
|
||||
let cargando = $derived(data.stock === undefined || data.stock === null);
|
||||
|
||||
const headers = [
|
||||
{ key: 'repuesto', value: 'Repuesto' },
|
||||
{ key: 'descripcion', value: 'Descripción' },
|
||||
{ key: 'almacen', value: 'Almacén' },
|
||||
{ key: 'cantidad', value: 'Cantidad' },
|
||||
{ key: 'reservada', value: 'Reservado' },
|
||||
{ key: 'disponible', value: 'Disponible' },
|
||||
{ key: 'observacion', value: 'Observación' },
|
||||
{ key: 'estado', value: 'Estado' }
|
||||
];
|
||||
|
||||
let openIngreso = $state(false);
|
||||
let openDevolucion = $state(false);
|
||||
let openInfo = $state(false);
|
||||
let openTraslado = $state(false);
|
||||
let openAjuste = $state(false);
|
||||
let openReserva = $state(false);
|
||||
let openComentario = $state(false);
|
||||
|
||||
let stockTraslado = $state<StockItem | null>(null);
|
||||
let stockAjuste = $state<StockItem | null>(null);
|
||||
let stockReserva = $state<StockItem | null>(null);
|
||||
let stockComentario = $state<StockItem | null>(null);
|
||||
let stockInfo = $state<Record<string, unknown> | null>(null);
|
||||
|
||||
function buscar(f: { q: string; almacenId: number; estado: string }) {
|
||||
const params = new URLSearchParams();
|
||||
if (f.q) params.set('q', f.q);
|
||||
if (f.almacenId) params.set('almacenId', String(f.almacenId));
|
||||
if (f.estado) params.set('estado', f.estado);
|
||||
const query = params.toString();
|
||||
void goto(`/stock${query ? `?${query}` : ''}`, { keepFocus: true, noScroll: true });
|
||||
}
|
||||
|
||||
function limpiarFiltros() {
|
||||
void goto('/stock', { keepFocus: true, noScroll: true });
|
||||
}
|
||||
|
||||
function verRegistro(s: StockItem) {
|
||||
stockInfo = {
|
||||
Repuesto: s.repuesto?.nombre ?? s.repuestoId,
|
||||
Descripción: s.repuesto?.descripcion || '-',
|
||||
Almacén: s.almacen?.codigo ?? s.almacenId,
|
||||
Cantidad: formatearCantidad(s.cantidad),
|
||||
Reservado: formatearCantidad(s.cantidadReservada),
|
||||
Disponible: formatearCantidad(s.cantidad - s.cantidadReservada),
|
||||
Observación: s.observacion || '-'
|
||||
};
|
||||
openInfo = true;
|
||||
}
|
||||
|
||||
async function liberar(r: ReservaStock) {
|
||||
const res = await liberarReserva(r.ID);
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
return;
|
||||
}
|
||||
await invalidate('stock:load');
|
||||
}
|
||||
|
||||
function fecha(v?: string) {
|
||||
if (!v) return '-';
|
||||
const d = new Date(v);
|
||||
return Number.isNaN(d.getTime()) ? '-' : d.toLocaleDateString();
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header />
|
||||
|
||||
<div class="page-container">
|
||||
<div class="flex justify-between">
|
||||
<h1 class="page-title">Gestión de Stock</h1>
|
||||
<div class="flex flex-wrap justify-end gap-2">
|
||||
<Button icon={InventoryManagement} onclick={() => (openIngreso = true)}>
|
||||
Registrar Ingreso
|
||||
</Button>
|
||||
<Button kind="tertiary" icon={Return} onclick={() => (openDevolucion = true)}>
|
||||
Registrar Devolución
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FiltrosStock {almacenes} valores={filtros} onBuscar={buscar} onLimpiar={limpiarFiltros} />
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
{/if}
|
||||
|
||||
{#if cargando}
|
||||
<DataTableSkeleton {headers} rows={5} size="compact" showHeader={false} showToolbar={false} />
|
||||
{:else}
|
||||
<TablaStock
|
||||
{stock}
|
||||
onTrasladar={(s) => {
|
||||
stockTraslado = s;
|
||||
openTraslado = true;
|
||||
}}
|
||||
onAjustar={(s) => {
|
||||
stockAjuste = s;
|
||||
openAjuste = true;
|
||||
}}
|
||||
onReservar={(s) => {
|
||||
stockReserva = s;
|
||||
openReserva = true;
|
||||
}}
|
||||
onComentar={(s) => {
|
||||
stockComentario = s;
|
||||
openComentario = true;
|
||||
}}
|
||||
onVer={verRegistro}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if data.reservasError}
|
||||
<InlineNotification
|
||||
kind="error"
|
||||
title="Reservas"
|
||||
subtitle={data.reservasError}
|
||||
hideCloseButton
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if !cargando}
|
||||
<TableContainer title="Reservas activas">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Repuesto</TableHeader>
|
||||
<TableHeader>Almacén</TableHeader>
|
||||
<TableHeader>Cantidad</TableHeader>
|
||||
<TableHeader>Cliente</TableHeader>
|
||||
<TableHeader>Vencimiento</TableHeader>
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if reservas.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={6}>No hay reservas activas.</TableCell>
|
||||
</TableRow>
|
||||
{:else}
|
||||
{#each reservas as r (r.ID)}
|
||||
<TableRow>
|
||||
<TableCell>{r.repuesto?.nombre ?? r.repuesto_id}</TableCell>
|
||||
<TableCell>{r.almacen?.codigo ?? r.almacen_id}</TableCell>
|
||||
<TableCell>{formatearCantidad(r.cantidad)}</TableCell>
|
||||
<TableCell>{r.cliente?.nombre ?? '-'}</TableCell>
|
||||
<TableCell>{fecha(r.fecha_vencimiento)}</TableCell>
|
||||
<TableCell class="acciones-cell">
|
||||
<Button kind="ghost" size="small" icon={Play} onclick={() => liberar(r)}>
|
||||
Liberar
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
{/if}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<IngresarStockForm bind:open={openIngreso} {almacenes} onClose={() => (openIngreso = false)} />
|
||||
|
||||
<DevolucionStockForm
|
||||
bind:open={openDevolucion}
|
||||
{almacenes}
|
||||
onClose={() => (openDevolucion = false)}
|
||||
/>
|
||||
|
||||
<TrasladarStockForm
|
||||
bind:open={openTraslado}
|
||||
stock={stockTraslado}
|
||||
{almacenes}
|
||||
onClose={() => {
|
||||
openTraslado = false;
|
||||
stockTraslado = null;
|
||||
}}
|
||||
/>
|
||||
|
||||
<AjustarStockForm
|
||||
bind:open={openAjuste}
|
||||
stock={stockAjuste}
|
||||
onClose={() => {
|
||||
openAjuste = false;
|
||||
stockAjuste = null;
|
||||
}}
|
||||
/>
|
||||
|
||||
<ReservarStockForm
|
||||
bind:open={openReserva}
|
||||
stock={stockReserva}
|
||||
{clientes}
|
||||
onClose={() => {
|
||||
openReserva = false;
|
||||
stockReserva = null;
|
||||
}}
|
||||
/>
|
||||
|
||||
<ComentarStockForm
|
||||
bind:open={openComentario}
|
||||
stock={stockComentario}
|
||||
onClose={() => {
|
||||
openComentario = false;
|
||||
stockComentario = null;
|
||||
}}
|
||||
/>
|
||||
|
||||
<ModalStructured objeto={stockInfo} bind:open={openInfo} />
|
||||
@@ -0,0 +1,34 @@
|
||||
import { obtenerStock } from '$lib/hooks/stock/obtenerStock';
|
||||
import { obtenerAlmacenes } from '$lib/hooks/almacenes/obtenerAlmacenes';
|
||||
import { obtenerClientes } from '$lib/hooks/clientes/obtenerClientes';
|
||||
import { obtenerReservas } from '$lib/hooks/stock/obtenerReservas';
|
||||
|
||||
export let ssr = false;
|
||||
|
||||
export async function load({ fetch, depends, url }) {
|
||||
depends('stock:load');
|
||||
|
||||
const almacenParam = url.searchParams.get('almacenId');
|
||||
const filtros = {
|
||||
q: url.searchParams.get('q') ?? '',
|
||||
almacenId: almacenParam ? Number(almacenParam) || undefined : undefined,
|
||||
estado: url.searchParams.get('estado') ?? ''
|
||||
};
|
||||
|
||||
const [stock, almacenes, clientes, reservas] = await Promise.all([
|
||||
obtenerStock(fetch, filtros),
|
||||
obtenerAlmacenes(fetch),
|
||||
obtenerClientes(fetch),
|
||||
obtenerReservas(fetch)
|
||||
]);
|
||||
|
||||
return {
|
||||
stock,
|
||||
almacenes: Array.isArray(almacenes) ? almacenes : [],
|
||||
clientes: Array.isArray(clientes) ? clientes : [],
|
||||
reservas: Array.isArray(reservas) ? reservas : [],
|
||||
reservasError: typeof reservas === 'string' ? reservas : '',
|
||||
error: typeof stock === 'string' ? stock : '',
|
||||
filtros
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<script lang="ts">
|
||||
import { Modal, NumberInput, TextInput, InlineNotification } from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { ajustarStock } from '$lib/hooks/stock/ajustarStock';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import type { StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
stock = null
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
stock?: StockItem | null;
|
||||
} = $props();
|
||||
|
||||
let cantidadReal = $state(0);
|
||||
let motivo = $state('');
|
||||
let observacion = $state('');
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
const actual = $derived(stock?.cantidad ?? 0);
|
||||
const reservada = $derived(stock?.cantidadReservada ?? 0);
|
||||
const diferencia = $derived(cantidadReal - actual);
|
||||
const bajoMinimo = $derived(
|
||||
cantidadReal < (stock?.repuesto?.stockMinimo ?? 0) && (stock?.repuesto?.stockMinimo ?? 0) > 0
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
cantidadReal = stock?.cantidad ?? 0;
|
||||
motivo = '';
|
||||
observacion = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !stock) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
if (cantidadReal < 0) {
|
||||
error = 'La cantidad real no puede ser negativa.';
|
||||
} else if (!motivo.trim()) {
|
||||
error = 'Ingresá el motivo del ajuste.';
|
||||
} else if (cantidadReal < reservada) {
|
||||
error = `La cantidad no puede quedar por debajo de lo reservado (${formatearCantidad(reservada)}).`;
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await ajustarStock({
|
||||
stockId: stock.id,
|
||||
cantidadReal,
|
||||
motivo,
|
||||
observacion
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="ajustarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="ajustarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Ajustar stock"
|
||||
primaryButtonText="Guardar ajuste"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Repuesto</p>
|
||||
<p class="font-semibold">{stock?.repuesto?.nombre ?? stock?.repuestoId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Almacén</p>
|
||||
<p class="font-semibold">{stock?.almacen?.codigo ?? stock?.almacenId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Stock actual</p>
|
||||
<p class="font-semibold">{formatearCantidad(actual)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Reservado</p>
|
||||
<p class="font-semibold">{formatearCantidad(reservada)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NumberInput
|
||||
labelText="Nuevo stock (cantidad real)"
|
||||
bind:value={cantidadReal}
|
||||
min={0}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
|
||||
<p class="mt-2 text-sm text-gray-400">
|
||||
Diferencia: <span class="font-semibold"
|
||||
>{diferencia > 0 ? '+' : ''}{formatearCantidad(diferencia)}</span
|
||||
>
|
||||
</p>
|
||||
|
||||
{#if bajoMinimo}
|
||||
<div class="mt-4">
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Stock bajo mínimo"
|
||||
subtitle="El nuevo stock queda por debajo del mínimo configurado para el repuesto."
|
||||
hideCloseButton
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Motivo" bind:value={motivo} maxlength={60} required />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Observación (opcional)" bind:value={observacion} maxlength={60} />
|
||||
<div class="mt-1 text-sm text-gray-500">{observacion.length}/60</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,93 @@
|
||||
<script lang="ts">
|
||||
import { InlineNotification, Modal, TextInput } from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { comentarStock } from '$lib/hooks/stock/comentarStock';
|
||||
import type { StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
stock = null
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
stock?: StockItem | null;
|
||||
} = $props();
|
||||
|
||||
let observacion = $state('');
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
observacion = stock?.observacion ?? '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !stock) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
const texto = observacion.trim();
|
||||
if (texto.length > 60) {
|
||||
error = 'La observación no puede superar los 60 caracteres.';
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await comentarStock(stock.id, texto);
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="comentarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="comentarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Registrar observación"
|
||||
primaryButtonText="Guardar"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4">
|
||||
<p class="text-sm text-gray-400">Repuesto</p>
|
||||
<p class="font-semibold">{stock?.repuesto?.nombre ?? stock?.repuestoId ?? '-'}</p>
|
||||
</div>
|
||||
|
||||
<TextInput
|
||||
labelText="Observación"
|
||||
bind:value={observacion}
|
||||
maxlength={60}
|
||||
placeholder="Máximo 60 caracteres"
|
||||
helperText="Dejá el campo vacío para quitar la observación."
|
||||
/>
|
||||
<div class="mt-1 text-sm text-gray-500">{observacion.length}/60</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,211 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, TrashCan } from 'carbon-icons-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { registrarDevolucion } from '$lib/hooks/stock/registrarDevolucion';
|
||||
import { obtenerFacturas } from '$lib/hooks/facturas/obtenerFacturas';
|
||||
import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import type { Almacen, FacturaResumen, Repuesto } from '../../types';
|
||||
|
||||
interface ItemDevolucion {
|
||||
repuestoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
almacenes = []
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
almacenes?: Almacen[];
|
||||
} = $props();
|
||||
|
||||
let facturas = $state<FacturaResumen[]>([]);
|
||||
let repuestos = $state<Repuesto[]>([]);
|
||||
let cargandoCatalogos = $state(false);
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
let facturaId = $state<number>(0);
|
||||
let almacenId = $state<number>(0);
|
||||
let motivo = $state('');
|
||||
let items = $state<ItemDevolucion[]>([]);
|
||||
|
||||
function itemVacio(): ItemDevolucion {
|
||||
return { repuestoId: 0, cantidad: 0, precioUnitario: 0 };
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
|
||||
facturaId = 0;
|
||||
almacenId = almacenes[0]?.id ?? 0;
|
||||
motivo = '';
|
||||
items = [itemVacio()];
|
||||
error = '';
|
||||
enviando = false;
|
||||
|
||||
let cancelado = false;
|
||||
cargandoCatalogos = true;
|
||||
(async () => {
|
||||
const [f, r] = await Promise.all([obtenerFacturas(), obtenerRepuestos()]);
|
||||
if (cancelado) return;
|
||||
facturas = Array.isArray(f) ? f : [];
|
||||
repuestos = Array.isArray(r) ? r : [];
|
||||
cargandoCatalogos = false;
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelado = true;
|
||||
};
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
const itemsValidos = items.filter((i) => i.repuestoId > 0 && i.cantidad > 0);
|
||||
|
||||
if (!facturaId) {
|
||||
error = 'Seleccioná la factura de origen.';
|
||||
} else if (!motivo.trim()) {
|
||||
error = 'Ingresá el motivo de la devolución.';
|
||||
} else if (itemsValidos.length === 0) {
|
||||
error = 'Agregá al menos un ítem con repuesto y cantidad.';
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await registrarDevolucion({
|
||||
facturaId,
|
||||
almacenId: almacenId || undefined,
|
||||
motivo: motivo.trim(),
|
||||
items: itemsValidos.map((i) => ({
|
||||
repuestoId: i.repuestoId,
|
||||
cantidad: i.cantidad,
|
||||
precioUnitario: i.precioUnitario
|
||||
}))
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="devolucionStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="devolucionStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Registrar devolución"
|
||||
primaryButtonText="Confirmar devolución"
|
||||
primaryButtonDisabled={enviando || cargandoCatalogos}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<Select labelText="Factura" bind:selected={facturaId}>
|
||||
<SelectItem value={0} text="Seleccioná una factura" />
|
||||
{#each facturas as f (f.ID)}
|
||||
<SelectItem
|
||||
value={f.ID}
|
||||
text={`${f.numero ? `#${f.numero}` : `Factura ${f.ID}`}${f.cliente?.nombre ? ` · ${f.cliente.nombre}` : ''}`}
|
||||
/>
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<Select labelText="Almacén de destino" bind:selected={almacenId}>
|
||||
<SelectItem value={0} text="Seleccioná un almacén" />
|
||||
{#each almacenes as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Motivo" bind:value={motivo} maxlength={60} />
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex items-center justify-between">
|
||||
<p class="text-base font-semibold">Ítems devueltos</p>
|
||||
<Button kind="ghost" size="small" icon={Add} onclick={() => (items = [...items, itemVacio()])}
|
||||
>Agregar ítem</Button
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-col gap-4">
|
||||
{#each items as item, i (i)}
|
||||
<div class="rounded border border-gray-700 p-3">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<p class="text-sm font-semibold">Ítem {i + 1}</p>
|
||||
{#if items.length > 1}
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={TrashCan}
|
||||
onclick={() => (items = items.filter((_, idx) => idx !== i))}>Quitar</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-2 grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<Select labelText="Repuesto" bind:selected={item.repuestoId}>
|
||||
<SelectItem value={0} text="Seleccioná un repuesto" />
|
||||
{#each repuestos as r (r.ID)}
|
||||
<SelectItem value={r.ID} text={r.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<NumberInput
|
||||
labelText="Cantidad"
|
||||
bind:value={item.cantidad}
|
||||
min={0}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
labelText="Precio unitario"
|
||||
bind:value={item.precioUnitario}
|
||||
min={0}
|
||||
step={0.01}
|
||||
allowEmpty
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { Tag } from 'carbon-components-svelte';
|
||||
|
||||
let { cantidad = 0, reservada = 0, minimo = 0 } = $props();
|
||||
|
||||
const estado = $derived(
|
||||
cantidad <= 0 ? 'AGOTADO' : minimo > 0 && cantidad < minimo ? 'BAJO' : 'OK'
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if estado === 'AGOTADO'}
|
||||
<Tag type="red">Agotado</Tag>
|
||||
{:else if estado === 'BAJO'}
|
||||
<Tag type="magenta">Bajo mínimo</Tag>
|
||||
{:else}
|
||||
<Tag type="green">OK</Tag>
|
||||
{/if}
|
||||
@@ -0,0 +1,62 @@
|
||||
<script lang="ts">
|
||||
import { Button, Select, SelectItem, TextInput } from 'carbon-components-svelte';
|
||||
import { Close, Search } from 'carbon-icons-svelte';
|
||||
import type { Almacen } from '../../types';
|
||||
|
||||
let {
|
||||
almacenes = [],
|
||||
valores = { q: '', almacenId: 0, estado: '' },
|
||||
onBuscar,
|
||||
onLimpiar
|
||||
}: {
|
||||
almacenes?: Almacen[];
|
||||
valores?: { q?: string; almacenId?: number; estado?: string };
|
||||
onBuscar?: (filtros: { q: string; almacenId: number; estado: string }) => void;
|
||||
onLimpiar?: () => void;
|
||||
} = $props();
|
||||
|
||||
let q = $state('');
|
||||
let almacenId = $state<number>(0);
|
||||
let estado = $state('');
|
||||
|
||||
$effect(() => {
|
||||
q = valores.q ?? '';
|
||||
almacenId = valores.almacenId ?? 0;
|
||||
estado = valores.estado ?? '';
|
||||
});
|
||||
</script>
|
||||
|
||||
<form
|
||||
class="mb-6 flex flex-wrap items-end gap-4"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onBuscar?.({ q, almacenId: Number(almacenId) || 0, estado });
|
||||
}}
|
||||
>
|
||||
<div class="min-w-60 flex-1">
|
||||
<TextInput
|
||||
labelText="Buscar repuesto"
|
||||
placeholder="Nombre, descripción o código"
|
||||
bind:value={q}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Select labelText="Almacén" bind:selected={almacenId}>
|
||||
<SelectItem value={0} text="Todos los almacenes" />
|
||||
{#each almacenes as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<Select labelText="Estado" bind:selected={estado}>
|
||||
<SelectItem value="" text="Todos" />
|
||||
<SelectItem value="NORMAL" text="OK" />
|
||||
<SelectItem value="BAJO_MINIMO" text="Bajo mínimo" />
|
||||
<SelectItem value="AGOTADO" text="Agotado" />
|
||||
</Select>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<Button type="submit" icon={Search}>Buscar</Button>
|
||||
<Button kind="ghost" icon={Close} onclick={() => onLimpiar?.()}>Limpiar</Button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,250 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, TrashCan } from 'carbon-icons-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { ingresarStock } from '$lib/hooks/stock/ingresarStock';
|
||||
import { obtenerProveedores } from '$lib/hooks/proveedores/obtenerProveedores';
|
||||
import { obtenerRepuestos } from '$lib/hooks/repuestos/obtenerRepuestos';
|
||||
import type { Almacen, Proveedor, Repuesto } from '../../types';
|
||||
|
||||
interface ItemIngreso {
|
||||
repuestoId: number;
|
||||
cantidadEsperada: number;
|
||||
cantidadRecibida: number;
|
||||
unidadMedida: string;
|
||||
observacion: string;
|
||||
}
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
almacenes = []
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
almacenes?: Almacen[];
|
||||
} = $props();
|
||||
|
||||
let proveedores = $state<Proveedor[]>([]);
|
||||
let repuestos = $state<Repuesto[]>([]);
|
||||
let cargandoCatalogos = $state(false);
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
let proveedorId = $state<number>(0);
|
||||
let numero = $state('');
|
||||
let fechaEmision = $state(new Date().toISOString().slice(0, 10));
|
||||
let almacenDestinoId = $state<number>(0);
|
||||
let observacion = $state('');
|
||||
let items = $state<ItemIngreso[]>([]);
|
||||
|
||||
function itemVacio(): ItemIngreso {
|
||||
return {
|
||||
repuestoId: 0,
|
||||
cantidadEsperada: 0,
|
||||
cantidadRecibida: 0,
|
||||
unidadMedida: 'Unidad',
|
||||
observacion: ''
|
||||
};
|
||||
}
|
||||
|
||||
const diferencias = $derived(
|
||||
items.filter((i) => i.cantidadEsperada !== i.cantidadRecibida).length
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
|
||||
// Reiniciar formulario al abrir.
|
||||
proveedorId = 0;
|
||||
numero = '';
|
||||
fechaEmision = new Date().toISOString().slice(0, 10);
|
||||
almacenDestinoId = almacenes[0]?.id ?? 0;
|
||||
observacion = '';
|
||||
items = [itemVacio()];
|
||||
error = '';
|
||||
enviando = false;
|
||||
|
||||
let cancelado = false;
|
||||
cargandoCatalogos = true;
|
||||
(async () => {
|
||||
const [p, r] = await Promise.all([obtenerProveedores(), obtenerRepuestos()]);
|
||||
if (cancelado) return;
|
||||
proveedores = Array.isArray(p) ? p : [];
|
||||
repuestos = Array.isArray(r) ? r : [];
|
||||
cargandoCatalogos = false;
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelado = true;
|
||||
};
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
const itemsValidos = items.filter((i) => i.repuestoId > 0 && i.cantidadRecibida > 0);
|
||||
|
||||
if (!proveedorId) {
|
||||
error = 'Seleccioná un proveedor.';
|
||||
} else if (!numero.trim()) {
|
||||
error = 'Ingresá el número de remito.';
|
||||
} else if (!fechaEmision) {
|
||||
error = 'Ingresá la fecha de emisión.';
|
||||
} else if (!almacenDestinoId) {
|
||||
error = 'Seleccioná el almacén destino.';
|
||||
} else if (itemsValidos.length === 0) {
|
||||
error = 'Agregá al menos un ítem con repuesto y cantidad recibida.';
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await ingresarStock({
|
||||
proveedorId,
|
||||
numero: numero.trim(),
|
||||
fechaEmision: `${fechaEmision}T00:00:00Z`,
|
||||
almacenDestinoId,
|
||||
observacion,
|
||||
items: itemsValidos.map((i) => ({
|
||||
repuestoId: i.repuestoId,
|
||||
cantidadEsperada: i.cantidadEsperada,
|
||||
cantidadRecibida: i.cantidadRecibida,
|
||||
unidadMedida: i.unidadMedida || 'Unidad',
|
||||
observacion: i.observacion
|
||||
}))
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="ingresarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="ingresarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Registrar ingreso de stock"
|
||||
primaryButtonText="Confirmar ingreso"
|
||||
primaryButtonDisabled={enviando || cargandoCatalogos}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<Select labelText="Proveedor" bind:selected={proveedorId}>
|
||||
<SelectItem value={0} text="Seleccioná un proveedor" />
|
||||
{#each proveedores as p (p.ID)}
|
||||
<SelectItem value={p.ID} text={p.cuit ? `${p.nombre} · ${p.cuit}` : p.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<Select labelText="Almacén destino" bind:selected={almacenDestinoId}>
|
||||
<SelectItem value={0} text="Seleccioná un almacén" />
|
||||
{#each almacenes as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<TextInput labelText="N° de remito" bind:value={numero} maxlength={30} />
|
||||
|
||||
<TextInput labelText="Fecha de emisión" type="date" bind:value={fechaEmision} />
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Observación (opcional)" bind:value={observacion} maxlength={60} />
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex items-center justify-between">
|
||||
<p class="text-base font-semibold">Ítems del remito</p>
|
||||
<Button kind="ghost" size="small" icon={Add} onclick={() => (items = [...items, itemVacio()])}
|
||||
>Agregar ítem</Button
|
||||
>
|
||||
</div>
|
||||
|
||||
{#if diferencias > 0}
|
||||
<div class="mt-3">
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Hay diferencias"
|
||||
subtitle={`${diferencias} ítem(s) con cantidad recibida distinta de la esperada.`}
|
||||
hideCloseButton
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-3 flex flex-col gap-4">
|
||||
{#each items as item, i (i)}
|
||||
<div class="rounded border border-gray-700 p-3">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<p class="text-sm font-semibold">Ítem {i + 1}</p>
|
||||
{#if items.length > 1}
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={TrashCan}
|
||||
onclick={() => (items = items.filter((_, idx) => idx !== i))}>Quitar</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-2 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<Select labelText="Repuesto" bind:selected={item.repuestoId}>
|
||||
<SelectItem value={0} text="Seleccioná un repuesto" />
|
||||
{#each repuestos as r (r.ID)}
|
||||
<SelectItem value={r.ID} text={r.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<TextInput labelText="Unidad de medida" bind:value={item.unidadMedida} maxlength={20} />
|
||||
|
||||
<NumberInput
|
||||
labelText="Cantidad esperada"
|
||||
bind:value={item.cantidadEsperada}
|
||||
min={0}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
labelText="Cantidad recibida"
|
||||
bind:value={item.cantidadRecibida}
|
||||
min={0}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,158 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { reservarStock } from '$lib/hooks/stock/reservarStock';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import type { Cliente, StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
stock = null,
|
||||
clientes = []
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
stock?: StockItem | null;
|
||||
clientes?: Cliente[];
|
||||
} = $props();
|
||||
|
||||
let cantidad = $state(0);
|
||||
let clienteId = $state('');
|
||||
let fechaVencimiento = $state('');
|
||||
let observacion = $state('');
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
const disponible = $derived(stock ? stock.cantidad - stock.cantidadReservada : 0);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
cantidad = 0;
|
||||
clienteId = '';
|
||||
fechaVencimiento = '';
|
||||
observacion = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !stock) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
if (!clienteId) {
|
||||
error = 'Seleccioná un cliente.';
|
||||
} else if (clientes.length === 0) {
|
||||
error = 'No hay clientes cargados.';
|
||||
} else if (cantidad <= 0) {
|
||||
error = 'La cantidad debe ser mayor a cero.';
|
||||
} else if (cantidad > disponible) {
|
||||
error = `La cantidad supera el disponible (${formatearCantidad(disponible)}).`;
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await reservarStock({
|
||||
repuestoId: stock.repuestoId,
|
||||
almacenId: stock.almacenId,
|
||||
cantidad,
|
||||
clienteId: Number(clienteId),
|
||||
fechaVencimiento: fechaVencimiento ? `${fechaVencimiento}T00:00:00Z` : null,
|
||||
observacion
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="reservarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="reservarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Reservar stock"
|
||||
primaryButtonText="Reservar"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Repuesto</p>
|
||||
<p class="font-semibold">{stock?.repuesto?.nombre ?? stock?.repuestoId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Almacén</p>
|
||||
<p class="font-semibold">{stock?.almacen?.codigo ?? stock?.almacenId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Disponible</p>
|
||||
<p class="font-semibold">{formatearCantidad(disponible)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NumberInput
|
||||
labelText="Cantidad a reservar"
|
||||
bind:value={cantidad}
|
||||
min={0}
|
||||
max={disponible}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
|
||||
<div class="mt-4">
|
||||
<Select labelText="Cliente" bind:selected={clienteId} required>
|
||||
<SelectItem value="" text="Seleccionar cliente" />
|
||||
{#each clientes as cliente (cliente.ID)}
|
||||
<SelectItem value={String(cliente.ID)} text={cliente.nombre} />
|
||||
{/each}
|
||||
</Select>
|
||||
{#if clientes.length === 0}
|
||||
<p class="mt-1 text-sm text-gray-500">No hay clientes cargados.</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput
|
||||
labelText="Fecha de vencimiento (opcional)"
|
||||
type="date"
|
||||
bind:value={fechaVencimiento}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Observación (opcional)" bind:value={observacion} maxlength={60} />
|
||||
<div class="mt-1 text-sm text-gray-500">{observacion.length}/60</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,112 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
} from 'carbon-components-svelte';
|
||||
import {
|
||||
AddComment,
|
||||
ArrowsHorizontal,
|
||||
Information,
|
||||
SettingsAdjust,
|
||||
Time
|
||||
} from 'carbon-icons-svelte';
|
||||
import EstadoStockTag from './EstadoStockTag.svelte';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import type { StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
stock = [],
|
||||
onTrasladar,
|
||||
onAjustar,
|
||||
onReservar,
|
||||
onComentar,
|
||||
onVer
|
||||
}: {
|
||||
stock?: StockItem[];
|
||||
onTrasladar?: (s: StockItem) => void;
|
||||
onAjustar?: (s: StockItem) => void;
|
||||
onReservar?: (s: StockItem) => void;
|
||||
onComentar?: (s: StockItem) => void;
|
||||
onVer?: (s: StockItem) => void;
|
||||
} = $props();
|
||||
|
||||
const headers = [
|
||||
{ key: 'repuesto', value: 'Repuesto' },
|
||||
{ key: 'descripcion', value: 'Descripción' },
|
||||
{ key: 'almacen', value: 'Almacén' },
|
||||
{ key: 'cantidad', value: 'Cantidad' },
|
||||
{ key: 'reservada', value: 'Reservado' },
|
||||
{ key: 'disponible', value: 'Disponible' },
|
||||
{ key: 'observacion', value: 'Observación' },
|
||||
{ key: 'estado', value: 'Estado' }
|
||||
];
|
||||
</script>
|
||||
|
||||
<TableContainer title="Existencias">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{#each headers as header}
|
||||
<TableHeader>{header.value}</TableHeader>
|
||||
{/each}
|
||||
<TableHeader>Acciones</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#if stock.length === 0}
|
||||
<TableRow>
|
||||
<TableCell colspan={headers.length + 1}>
|
||||
No hay stock para mostrar con los filtros seleccionados.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{:else}
|
||||
{#each stock as s (s.id)}
|
||||
<TableRow>
|
||||
<TableCell>{s.repuesto?.nombre ?? s.repuestoId}</TableCell>
|
||||
<TableCell title={s.repuesto?.descripcion ?? ''}
|
||||
>{s.repuesto?.descripcion || '-'}</TableCell
|
||||
>
|
||||
<TableCell>{s.almacen?.codigo ?? s.almacenId}</TableCell>
|
||||
<TableCell>{formatearCantidad(s.cantidad)}</TableCell>
|
||||
<TableCell>{formatearCantidad(s.cantidadReservada)}</TableCell>
|
||||
<TableCell>{formatearCantidad(s.cantidad - s.cantidadReservada)}</TableCell>
|
||||
<TableCell>{s.observacion || '-'}</TableCell>
|
||||
<TableCell>
|
||||
<EstadoStockTag
|
||||
cantidad={s.cantidad}
|
||||
reservada={s.cantidadReservada}
|
||||
minimo={s.repuesto?.stockMinimo ?? 0}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={ArrowsHorizontal}
|
||||
onclick={() => onTrasladar?.(s)}>Trasladar</Button
|
||||
>
|
||||
<Button kind="ghost" size="small" icon={SettingsAdjust} onclick={() => onAjustar?.(s)}
|
||||
>Ajustar</Button
|
||||
>
|
||||
<Button kind="ghost" size="small" icon={Time} onclick={() => onReservar?.(s)}
|
||||
>Reservar</Button
|
||||
>
|
||||
<Button kind="ghost" size="small" icon={AddComment} onclick={() => onComentar?.(s)}
|
||||
>Comentar</Button
|
||||
>
|
||||
<Button kind="ghost" size="small" icon={Information} onclick={() => onVer?.(s)}
|
||||
>Ver registro</Button
|
||||
>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
{/if}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
@@ -0,0 +1,143 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { trasladarStock } from '$lib/hooks/stock/trasladarStock';
|
||||
import { formatearCantidad } from './formatoCantidad';
|
||||
import type { Almacen, StockItem } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
onClose,
|
||||
stock = null,
|
||||
almacenes = []
|
||||
}: {
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
stock?: StockItem | null;
|
||||
almacenes?: Almacen[];
|
||||
} = $props();
|
||||
|
||||
let almacenDestinoId = $state<number>(0);
|
||||
let cantidad = $state(0);
|
||||
let observacion = $state('');
|
||||
let error = $state('');
|
||||
let enviando = $state(false);
|
||||
|
||||
const disponible = $derived(stock ? stock.cantidad - stock.cantidadReservada : 0);
|
||||
const destinos = $derived(almacenes.filter((a) => a.id !== stock?.almacenId));
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
almacenDestinoId = 0;
|
||||
cantidad = 0;
|
||||
observacion = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
}
|
||||
});
|
||||
|
||||
function handleClose() {
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !stock) return;
|
||||
enviando = true;
|
||||
error = '';
|
||||
|
||||
if (!almacenDestinoId) {
|
||||
error = 'Seleccioná el almacén destino.';
|
||||
} else if (cantidad <= 0) {
|
||||
error = 'La cantidad debe ser mayor a cero.';
|
||||
} else if (cantidad > disponible) {
|
||||
error = `La cantidad supera el disponible (${formatearCantidad(disponible)}).`;
|
||||
}
|
||||
|
||||
if (error === '') {
|
||||
const res = await trasladarStock({
|
||||
repuestoId: stock.repuestoId,
|
||||
almacenOrigenId: stock.almacenId,
|
||||
almacenDestinoId,
|
||||
cantidad,
|
||||
observacion
|
||||
});
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
} else {
|
||||
await invalidate('stock:load');
|
||||
handleClose();
|
||||
}
|
||||
}
|
||||
enviando = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="trasladarStockForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="trasladarStockForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading="Trasladar stock"
|
||||
primaryButtonText="Trasladar"
|
||||
primaryButtonDisabled={enviando}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Repuesto</p>
|
||||
<p class="font-semibold">{stock?.repuesto?.nombre ?? stock?.repuestoId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Almacén origen</p>
|
||||
<p class="font-semibold">{stock?.almacen?.codigo ?? stock?.almacenId ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Disponible para trasladar</p>
|
||||
<p class="font-semibold">{formatearCantidad(disponible)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Select labelText="Almacén destino" bind:selected={almacenDestinoId}>
|
||||
<SelectItem value={0} text="Seleccioná un almacén" />
|
||||
{#each destinos as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.ubicacion ? `${a.codigo} · ${a.ubicacion}` : a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
<div class="mt-4">
|
||||
<NumberInput
|
||||
labelText="Cantidad"
|
||||
bind:value={cantidad}
|
||||
min={0}
|
||||
max={disponible}
|
||||
step={1}
|
||||
allowEmpty
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<TextInput labelText="Observación (opcional)" bind:value={observacion} maxlength={60} />
|
||||
<div class="mt-1 text-sm text-gray-500">{observacion.length}/60</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -0,0 +1,10 @@
|
||||
// Formatea cantidades de stock sin separador decimal por coma.
|
||||
// Enteros como "7" y fracciones como "7.5" o "0.25".
|
||||
export function formatearCantidad(valor: number | null | undefined): string {
|
||||
if (valor === null || valor === undefined || Number.isNaN(valor)) return '-';
|
||||
|
||||
const redondeado = Math.round(valor * 1000) / 1000;
|
||||
if (Number.isInteger(redondeado)) return String(redondeado);
|
||||
|
||||
return redondeado.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
|
||||
}
|
||||
Vendored
+72
@@ -222,3 +222,75 @@ export interface Repuesto extends BaseModel {
|
||||
marca: Marca | string;
|
||||
aliases: string[];
|
||||
}
|
||||
|
||||
export interface Almacen {
|
||||
id: number;
|
||||
empresaId?: number;
|
||||
codigo: string;
|
||||
ubicacion?: string;
|
||||
}
|
||||
|
||||
export interface StockItem {
|
||||
id: number;
|
||||
empresaId?: number;
|
||||
cantidad: number;
|
||||
cantidadReservada: number;
|
||||
repuestoId: number;
|
||||
repuesto?: Repuesto;
|
||||
almacenId: number;
|
||||
almacen?: Almacen;
|
||||
observacion?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
deletedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface Cliente {
|
||||
ID: number;
|
||||
empresaId?: number;
|
||||
nombre: string;
|
||||
cuit?: string;
|
||||
email?: string | null;
|
||||
}
|
||||
|
||||
export interface ReservaStock {
|
||||
ID: number;
|
||||
CreatedAt?: string;
|
||||
UpdatedAt?: string;
|
||||
empresaId?: number;
|
||||
repuesto_id: number;
|
||||
repuesto?: Repuesto;
|
||||
almacen_id: number;
|
||||
almacen?: Almacen;
|
||||
cantidad: number;
|
||||
estado: string;
|
||||
cliente_id?: number | null;
|
||||
cliente?: Cliente;
|
||||
fecha_vencimiento?: string;
|
||||
creadoPorId?: number;
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export interface Proveedor {
|
||||
ID: number;
|
||||
CreatedAt?: string;
|
||||
UpdatedAt?: string;
|
||||
DeletedAt?: string | null;
|
||||
empresaId?: number;
|
||||
nombre: string;
|
||||
cuit?: string;
|
||||
email?: string;
|
||||
telefono?: string;
|
||||
}
|
||||
|
||||
export interface FacturaResumen {
|
||||
ID: number;
|
||||
numero?: string;
|
||||
total?: number;
|
||||
cliente?: Cliente;
|
||||
detalles?: Array<{
|
||||
productoId: number;
|
||||
cantidad: number;
|
||||
precioUnitario: number;
|
||||
}>;
|
||||
}
|
||||
Reference in new issue
Block a user