Private
Public Access
224 lines
6.3 KiB
Go
224 lines
6.3 KiB
Go
package services
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"strings"
|
|
"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"
|
|
)
|
|
|
|
// Errores de dominio del registro de pagos. El controller los traduce a HTTP.
|
|
var (
|
|
ErrFacturaNoEncontrada = errors.New("factura no encontrada")
|
|
ErrFacturaSaldada = errors.New("la factura ya se encuentra saldada")
|
|
ErrFacturaCancelada = errors.New("la factura está cancelada")
|
|
ErrImporteInvalido = errors.New("el importe debe ser mayor a cero")
|
|
ErrImporteExcedeSaldo = errors.New("el importe supera el saldo pendiente")
|
|
ErrFormaPagoInvalida = errors.New("forma de pago no encontrada")
|
|
ErrFechaPagoInvalida = errors.New("la fecha de pago no es válida")
|
|
ErrImporteDecimales = errors.New("el importe debe tener como máximo 2 decimales")
|
|
)
|
|
|
|
const toleranciaCentavos = 0.005
|
|
|
|
// RegistrarPagoFactura registra un pago sobre una factura existente de forma
|
|
// atómica. Bloquea la factura para que dos cobros concurrentes no pisen el
|
|
// saldo y deja auditoría del movimiento.
|
|
func RegistrarPagoFactura(
|
|
db *gorm.DB,
|
|
repo *repositorios.Repositorios,
|
|
empresaID, usuarioID, facturaID uint,
|
|
entrada dto.RegistrarPagoDto,
|
|
) (*dto.RegistrarPagoResponse, error) {
|
|
var (
|
|
factura *models.Factura
|
|
pago *models.Pago
|
|
saldoAnterior float64
|
|
)
|
|
|
|
err := db.Transaction(func(tx *gorm.DB) error {
|
|
f, err := repo.Factura.BloquearPorID(tx, facturaID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return ErrFacturaNoEncontrada
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
factura = f
|
|
saldoAnterior = redondearMonto(f.Saldo)
|
|
|
|
p, _, err := registrarPagoTx(tx, repo, factura, entrada)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pago = p
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
registrarLogFactura(repo, empresaID, usuarioID, "REGISTRAR_PAGO", []models_logs.LogDetalle{
|
|
{NombreTabla: "factura", Columna: "facturaId", ValorNuevo: fmt.Sprintf("%d", factura.ID)},
|
|
{NombreTabla: "factura", Columna: "numero", ValorNuevo: factura.Numero},
|
|
{NombreTabla: "pago", Columna: "pagoId", ValorNuevo: fmt.Sprintf("%d", pago.ID)},
|
|
{NombreTabla: "pago", Columna: "importe", ValorNuevo: fmt.Sprintf("%.2f", pago.Importe)},
|
|
{NombreTabla: "pago", Columna: "formaDePagoId", ValorNuevo: fmt.Sprintf("%d", pago.FormaDePagoID)},
|
|
{NombreTabla: "factura", Columna: "saldo", ValorNuevo: fmt.Sprintf("%.2f", factura.Saldo)},
|
|
})
|
|
|
|
respuestaFactura, err := dto_directors.NewFacturaDirector().DesdeFactura(factura)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &dto.RegistrarPagoResponse{
|
|
Pago: pagoResumen(pago),
|
|
Factura: *respuestaFactura,
|
|
SaldoAnterior: saldoAnterior,
|
|
SaldoNuevo: factura.Saldo,
|
|
}, nil
|
|
}
|
|
|
|
// registrarPagoTx aplica el pago sobre una factura que ya fue bloqueada por
|
|
// el llamador. Se comparte entre el cobro de una factura existente y el cobro
|
|
// inmediato al crearla, para que ambas rutas tengan exactamente las mismas
|
|
// reglas.
|
|
func registrarPagoTx(
|
|
tx *gorm.DB,
|
|
repo *repositorios.Repositorios,
|
|
factura *models.Factura,
|
|
entrada dto.RegistrarPagoDto,
|
|
) (*models.Pago, float64, error) {
|
|
if factura == nil {
|
|
return nil, 0, ErrFacturaNoEncontrada
|
|
}
|
|
if factura.Estado == "CANCELADA" {
|
|
return nil, 0, ErrFacturaCancelada
|
|
}
|
|
|
|
saldoAnterior := redondearMonto(factura.Saldo)
|
|
if factura.Estado == estadoFacturaPagada || saldoAnterior <= toleranciaCentavos {
|
|
return nil, saldoAnterior, ErrFacturaSaldada
|
|
}
|
|
|
|
if err := validarImportePago(entrada.Importe); err != nil {
|
|
return nil, saldoAnterior, err
|
|
}
|
|
importe := redondearMonto(entrada.Importe)
|
|
if importe > saldoAnterior+toleranciaCentavos {
|
|
return nil, saldoAnterior, ErrImporteExcedeSaldo
|
|
}
|
|
|
|
forma, err := repo.FormaDePago.ObtenerActivaPorID(entrada.FormaDePagoID)
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, saldoAnterior, ErrFormaPagoInvalida
|
|
}
|
|
if err != nil {
|
|
return nil, saldoAnterior, err
|
|
}
|
|
|
|
fecha, err := parseFechaPago(entrada.Fecha, factura.FechaEmision, time.Now())
|
|
if err != nil {
|
|
return nil, saldoAnterior, err
|
|
}
|
|
|
|
pago := &models.Pago{
|
|
FacturaID: factura.ID,
|
|
FormaDePagoID: forma.ID,
|
|
Importe: importe,
|
|
Fecha: fecha,
|
|
Observacion: strings.TrimSpace(entrada.Observacion),
|
|
}
|
|
if err := repo.Pago.Registrar(tx, pago); err != nil {
|
|
return nil, saldoAnterior, err
|
|
}
|
|
pago.FormaDePago = *forma
|
|
|
|
nuevoSaldo := redondearMonto(saldoAnterior - importe)
|
|
if nuevoSaldo < toleranciaCentavos {
|
|
nuevoSaldo = 0
|
|
}
|
|
|
|
nuevoEstado := estadoFacturaParcial
|
|
if nuevoSaldo == 0 {
|
|
nuevoEstado = estadoFacturaPagada
|
|
}
|
|
|
|
if err := repo.Factura.ActualizarEstadoSaldo(tx, factura.ID, nuevoEstado, nuevoSaldo); err != nil {
|
|
return nil, saldoAnterior, err
|
|
}
|
|
|
|
factura.Saldo = nuevoSaldo
|
|
factura.Estado = nuevoEstado
|
|
|
|
return pago, saldoAnterior, nil
|
|
}
|
|
|
|
func pagoResumen(pago *models.Pago) dto.PagoResumen {
|
|
if pago == nil {
|
|
return dto.PagoResumen{}
|
|
}
|
|
return dto.PagoResumen{
|
|
ID: pago.ID,
|
|
FacturaID: pago.FacturaID,
|
|
FormaDePagoID: pago.FormaDePagoID,
|
|
FormaDePago: pago.FormaDePago.Descripcion,
|
|
Importe: pago.Importe,
|
|
Fecha: pago.Fecha,
|
|
Observacion: pago.Observacion,
|
|
}
|
|
}
|
|
|
|
func validarImportePago(importe float64) error {
|
|
if math.IsNaN(importe) || math.IsInf(importe, 0) || importe <= 0 {
|
|
return ErrImporteInvalido
|
|
}
|
|
if math.Abs(importe-redondearMonto(importe)) > toleranciaCentavos/1000 {
|
|
return ErrImporteDecimales
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// parseFechaPago acepta una fecha YYYY-MM-DD o vacía (hoy). Rechaza fechas
|
|
// futuras y anteriores a la emisión de la factura.
|
|
func parseFechaPago(raw string, emision, ahora time.Time) (time.Time, error) {
|
|
var fecha time.Time
|
|
if strings.TrimSpace(raw) == "" {
|
|
fecha = inicioDia(ahora)
|
|
} else {
|
|
f, err := time.ParseInLocation("2006-01-02", raw, ahora.Location())
|
|
if err != nil {
|
|
return time.Time{}, ErrFechaPagoInvalida
|
|
}
|
|
fecha = f
|
|
}
|
|
|
|
if fecha.After(inicioDia(ahora)) {
|
|
return time.Time{}, ErrFechaPagoInvalida
|
|
}
|
|
if !emision.IsZero() && fecha.Before(inicioDia(emision)) {
|
|
return time.Time{}, ErrFechaPagoInvalida
|
|
}
|
|
|
|
return fecha, nil
|
|
}
|
|
|
|
func inicioDia(fecha time.Time) time.Time {
|
|
return time.Date(fecha.Year(), fecha.Month(), fecha.Day(), 0, 0, 0, 0, fecha.Location())
|
|
}
|
|
|
|
func redondearMonto(valor float64) float64 {
|
|
return math.Round(valor*100) / 100
|
|
}
|