Private
Public Access
326 lines
9.6 KiB
Go
326 lines
9.6 KiB
Go
package services
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
applog "log"
|
|
"math"
|
|
"sort"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
|
dto "repuestera_back/dto/Facturas"
|
|
"repuestera_back/models"
|
|
models_logs "repuestera_back/models/logs"
|
|
"repuestera_back/repositorios"
|
|
)
|
|
|
|
const (
|
|
estadoFacturaParcial = "PARCIAL"
|
|
estadoFacturaPagada = "PAGADA"
|
|
)
|
|
|
|
var errCantidadInvalida = errors.New("la cantidad debe ser mayor a cero")
|
|
|
|
// CrearFactura valida los datos, emite la factura y registra sus efectos
|
|
// (stock, contabilidad y pagos) dentro de una misma transacción.
|
|
func CrearFactura(
|
|
db *gorm.DB,
|
|
repo *repositorios.Repositorios,
|
|
empresaID, usuarioID uint,
|
|
entrada dto.CrearFacturaDto,
|
|
) (*dto.CrearFacturaResponse, error) {
|
|
if len(entrada.Items) == 0 {
|
|
return nil, errors.New("la factura debe tener al menos un ítem")
|
|
}
|
|
|
|
cliente, err := repo.Cliente.ObtenerPorID(entrada.ClienteID)
|
|
if err != nil || cliente == nil {
|
|
return nil, fmt.Errorf("cliente %d no encontrado", entrada.ClienteID)
|
|
}
|
|
|
|
if _, err := repo.Almacen.ObtenerPorID(entrada.AlmacenID); err != nil {
|
|
return nil, fmt.Errorf("almacén %d no encontrado", entrada.AlmacenID)
|
|
}
|
|
|
|
var descuento *models.Descuento
|
|
if entrada.DescuentoID > 0 {
|
|
d, err := repo.Descuento.ObtenerPorID(entrada.DescuentoID)
|
|
if err != nil || d == nil {
|
|
return nil, fmt.Errorf("descuento %d no encontrado", entrada.DescuentoID)
|
|
}
|
|
if !d.Activo {
|
|
return nil, errors.New("el descuento no está activo")
|
|
}
|
|
descuento = d
|
|
}
|
|
|
|
// Ordenar ítems por repuesto para bloquear en orden estable.
|
|
items := append([]dto.ItemFacturaDto(nil), entrada.Items...)
|
|
sort.Slice(items, func(i, j int) bool { return items[i].RepuestoID < items[j].RepuestoID })
|
|
|
|
// Validar repuestos y cantidades, y detectar duplicados.
|
|
vistos := make(map[uint64]bool, len(items))
|
|
nombresRepuestos := make(map[uint64]string, len(items))
|
|
for i := range items {
|
|
item := &items[i]
|
|
if item.RepuestoID == 0 {
|
|
return nil, errors.New("repuesto inválido")
|
|
}
|
|
if vistos[item.RepuestoID] {
|
|
return nil, fmt.Errorf("el repuesto %d está repetido", item.RepuestoID)
|
|
}
|
|
vistos[item.RepuestoID] = true
|
|
if err := validarCantidad(item.Cantidad); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
repuesto, err := repo.Repuesto.ObtenerPorID(uint(item.RepuestoID))
|
|
if err != nil || repuesto == nil || *repuesto == nil {
|
|
return nil, fmt.Errorf("repuesto %d no encontrado", item.RepuestoID)
|
|
}
|
|
if item.PrecioUnitario <= 0 {
|
|
item.PrecioUnitario = (*repuesto).Precio
|
|
}
|
|
nombresRepuestos[item.RepuestoID] = (*repuesto).Nombre
|
|
}
|
|
|
|
// Validar pagos.
|
|
for _, pago := range entrada.Pagos {
|
|
if err := validarCantidad(pago.Importe); err != nil {
|
|
return nil, fmt.Errorf("importe de pago inválido: %w", err)
|
|
}
|
|
if _, err := repo.FormaDePago.ObtenerPorID(pago.FormaDePagoID); err != nil {
|
|
return nil, fmt.Errorf("forma de pago %d no encontrada", pago.FormaDePagoID)
|
|
}
|
|
}
|
|
|
|
// Calcular totales.
|
|
var subtotal float64
|
|
detalles := make([]models.FacturaDetalle, 0, len(items))
|
|
for _, item := range items {
|
|
sub := redondearCantidad(item.Cantidad * item.PrecioUnitario)
|
|
subtotal = redondearCantidad(subtotal + sub)
|
|
detalles = append(detalles, models.FacturaDetalle{
|
|
RepuestoID: item.RepuestoID,
|
|
Cantidad: item.Cantidad,
|
|
DescuentoID: entrada.DescuentoID,
|
|
PrecioUnitario: item.PrecioUnitario,
|
|
Subtotal: sub,
|
|
AlicuotaIVA: 21,
|
|
})
|
|
}
|
|
|
|
descuentoTotal := 0.0
|
|
if descuento != nil {
|
|
switch descuento.Tipo {
|
|
case models.Porcentaje:
|
|
descuentoTotal = redondearCantidad(subtotal * descuento.Valor / 100)
|
|
case models.Fijo:
|
|
descuentoTotal = redondearCantidad(descuento.Valor)
|
|
}
|
|
if descuentoTotal > subtotal {
|
|
descuentoTotal = subtotal
|
|
}
|
|
}
|
|
|
|
baseImponible := redondearCantidad(subtotal - descuentoTotal)
|
|
alicuota := 21.0
|
|
impuestos := redondearCantidad(baseImponible * alicuota / 100)
|
|
total := redondearCantidad(baseImponible + impuestos)
|
|
|
|
var sumaPagos float64
|
|
for _, pago := range entrada.Pagos {
|
|
sumaPagos = redondearCantidad(sumaPagos + pago.Importe)
|
|
}
|
|
if sumaPagos > total {
|
|
return nil, errors.New("los pagos superan el total de la factura")
|
|
}
|
|
|
|
var facturaCreada *models.Factura
|
|
stocks := make([]*models.Stock, 0, len(items))
|
|
|
|
err = db.Transaction(func(tx *gorm.DB) error {
|
|
// Bloquear stock y validar disponibilidad.
|
|
stocksPorRepuesto := make(map[uint64]*models.Stock, len(items))
|
|
for _, item := range items {
|
|
stock, err := repo.Stock.BloquearPorRepuestoAlmacen(tx, item.RepuestoID, entrada.AlmacenID)
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return fmt.Errorf("stock insuficiente: repuesto %d", item.RepuestoID)
|
|
}
|
|
return err
|
|
}
|
|
disponible := redondearCantidad(stock.Cantidad - stock.CantidadReservada)
|
|
if disponible < redondearCantidad(item.Cantidad) {
|
|
return fmt.Errorf(
|
|
"stock insuficiente: repuesto %d, disponible %.3f, solicitado %.3f",
|
|
item.RepuestoID, disponible, item.Cantidad,
|
|
)
|
|
}
|
|
stocksPorRepuesto[item.RepuestoID] = stock
|
|
}
|
|
|
|
numero, err := repo.Secuencia.Siguiente(tx, empresaID, "FACTURA")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
factura, err := dto_directors.NewFacturaDirector().Crear(dto.FacturaCalculada{
|
|
EmpresaID: empresaID,
|
|
Numero: fmt.Sprintf("F-%08d", numero),
|
|
ClienteID: entrada.ClienteID,
|
|
AlmacenID: entrada.AlmacenID,
|
|
FechaEmision: time.Now(),
|
|
Subtotal: subtotal,
|
|
DescuentoID: entrada.DescuentoID,
|
|
DescuentoTotal: descuentoTotal,
|
|
Impuestos: impuestos,
|
|
AlicuotaIVA: alicuota,
|
|
Total: total,
|
|
Saldo: total,
|
|
Detalles: detalles,
|
|
Observacion: entrada.Observacion,
|
|
ResponsableID: usuarioID,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := repo.Factura.CrearConDetalles(tx, factura); err != nil {
|
|
return err
|
|
}
|
|
facturaCreada = factura
|
|
|
|
// Descontar stock y registrar el movimiento.
|
|
for _, item := range items {
|
|
stock := stocksPorRepuesto[item.RepuestoID]
|
|
saldoAnterior := stock.Cantidad
|
|
stock.Cantidad = redondearCantidad(stock.Cantidad - item.Cantidad)
|
|
if err := repo.Stock.ActualizarCantidades(tx, stock); err != nil {
|
|
return err
|
|
}
|
|
|
|
movimiento := &models.MovimientoStock{
|
|
StockID: stock.ID,
|
|
RepuestoID: stock.RepuestoID,
|
|
AlmacenID: stock.AlmacenID,
|
|
Tipo: models.MovimientoVenta,
|
|
Cantidad: redondearCantidad(item.Cantidad),
|
|
SaldoAnterior: redondearCantidad(saldoAnterior),
|
|
SaldoPosterior: redondearCantidad(stock.Cantidad),
|
|
ReferenciaTipo: "FACTURA",
|
|
ReferenciaID: uint64(factura.ID),
|
|
UsuarioID: usuarioID,
|
|
Observacion: entrada.Observacion,
|
|
Fecha: time.Now(),
|
|
}
|
|
if err := repo.MovimientoStock.Registrar(tx, movimiento); err != nil {
|
|
return err
|
|
}
|
|
stocks = append(stocks, stock)
|
|
}
|
|
|
|
if err := RegistrarAsientoVenta(tx, repo, factura, subtotal, descuentoTotal, impuestos, total); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Pagos inmediatos.
|
|
for _, pagoEntrada := range entrada.Pagos {
|
|
fecha := time.Now()
|
|
if pagoEntrada.Fecha != "" {
|
|
if f, err := time.Parse("2006-01-02", pagoEntrada.Fecha); err == nil {
|
|
fecha = f
|
|
}
|
|
}
|
|
|
|
pago := &models.Pago{
|
|
FacturaID: factura.ID,
|
|
FormaDePagoID: pagoEntrada.FormaDePagoID,
|
|
Importe: pagoEntrada.Importe,
|
|
Fecha: fecha,
|
|
Observacion: pagoEntrada.Observacion,
|
|
}
|
|
if err := repo.Pago.Registrar(tx, pago); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
if sumaPagos > 0 {
|
|
nuevoSaldo := redondearCantidad(total - sumaPagos)
|
|
nuevoEstado := estadoFacturaParcial
|
|
if nuevoSaldo <= 0 {
|
|
nuevoEstado = estadoFacturaPagada
|
|
nuevoSaldo = 0
|
|
}
|
|
if err := repo.Factura.ActualizarEstadoSaldo(tx, factura.ID, nuevoEstado, nuevoSaldo); err != nil {
|
|
return err
|
|
}
|
|
factura.Estado = nuevoEstado
|
|
factura.Saldo = nuevoSaldo
|
|
}
|
|
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Email post-commit: un fallo no revierte la factura.
|
|
facturaCreada.Cliente = *cliente
|
|
if entrada.EnviarEmail && cliente.Email != "" {
|
|
mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta(facturaCreada, nombresRepuestos, cliente.Email)
|
|
if err != nil {
|
|
applog.Printf("facturas: no se pudo construir el email de la factura %s: %v", facturaCreada.Numero, err)
|
|
} else if EnviarEmail(*mensaje, usuarioID) {
|
|
facturaCreada.SeAviso = true
|
|
}
|
|
}
|
|
|
|
// Auditoría.
|
|
registrarLogFactura(repo, empresaID, usuarioID, "CREAR_FACTURA", []models_logs.LogDetalle{
|
|
{NombreTabla: "factura", Columna: "facturaId", ValorNuevo: fmt.Sprintf("%d", facturaCreada.ID)},
|
|
{NombreTabla: "factura", Columna: "numero", ValorNuevo: facturaCreada.Numero},
|
|
{NombreTabla: "factura", Columna: "total", ValorNuevo: fmt.Sprintf("%.2f", total)},
|
|
})
|
|
|
|
respuestaFactura, err := dto_directors.NewFacturaDirector().DesdeFactura(facturaCreada)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &dto.CrearFacturaResponse{
|
|
Factura: respuestaFactura,
|
|
Stocks: stocks,
|
|
}, nil
|
|
}
|
|
|
|
func registrarLogFactura(
|
|
repo *repositorios.Repositorios,
|
|
empresaID, usuarioID uint,
|
|
accion string,
|
|
detalles []models_logs.LogDetalle,
|
|
) {
|
|
log, err := dto_directors.NewLogDirector().Custom(usuarioID, accion, detalles)
|
|
if err != nil {
|
|
applog.Printf("facturas: 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("facturas: no se pudo registrar el log de %s: %v", accion, err)
|
|
}
|
|
}
|
|
|
|
func validarCantidad(cantidad float64) error {
|
|
if math.IsNaN(cantidad) || math.IsInf(cantidad, 0) || cantidad <= 0 {
|
|
return errCantidadInvalida
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func redondearCantidad(valor float64) float64 {
|
|
return math.Round(valor*1000) / 1000
|
|
}
|