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,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
|
||||
}
|
||||
Reference in new issue
Block a user