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