Private
Public Access
hecho lo ded Registro de pagos
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
b68db07c92
commit
09830e15ec
19 files changed
+722
-46
No files matched your search
@@ -0,0 +1,99 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"repuestera_back/models"
|
||||
models_seguridad "repuestera_back/models/seguridad"
|
||||
)
|
||||
|
||||
var formasPagoDemo = []string{
|
||||
"Transferencia",
|
||||
"Efectivo",
|
||||
"Tarjeta de Débito",
|
||||
"Tarjeta de Crédito",
|
||||
"Cheque",
|
||||
}
|
||||
|
||||
// MigrarPagos completa la preparacion posterior a AutoMigrate del modulo de
|
||||
// pagos:
|
||||
// - garantiza que pago.importe tenga la misma precision que factura.total;
|
||||
// - siembra formas de pago basicas para las empresas que todavia no tienen
|
||||
// ninguna cargada.
|
||||
//
|
||||
// Es idempotente.
|
||||
func MigrarPagos() error {
|
||||
if !DB.Migrator().HasTable("pago") {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := migrarImportePago(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return sembrarFormasPagoDemo()
|
||||
}
|
||||
|
||||
// migrarImportePago convierte pago.importe a decimal(15,2) si quedo con la
|
||||
// precision vieja. GORM no siempre detecta el cambio solo con AutoMigrate.
|
||||
func migrarImportePago() error {
|
||||
columnas, err := DB.Migrator().ColumnTypes(&models.Pago{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("leer columnas de pago: %w", err)
|
||||
}
|
||||
|
||||
for _, columna := range columnas {
|
||||
if columna.Name() != "importe" {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(columna.DatabaseTypeName(), "decimal") {
|
||||
precision, escala, ok := columna.DecimalSize()
|
||||
if ok && precision >= 15 && escala >= 2 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := DB.Migrator().AlterColumn(&models.Pago{}, "importe"); err != nil {
|
||||
return fmt.Errorf("convertir pago.importe a decimal(15,2): %w", err)
|
||||
}
|
||||
log.Printf("pagos: columna pago.importe convertida a decimal(15,2)")
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// sembrarFormasPagoDemo crea un catalogo minimo solo cuando la empresa no
|
||||
// tiene ninguna forma de pago. No pisa catalogos existentes.
|
||||
func sembrarFormasPagoDemo() error {
|
||||
var empresas []models_seguridad.Empresa
|
||||
if err := DB.Find(&empresas).Error; err != nil {
|
||||
return fmt.Errorf("listar empresas para formas de pago: %w", err)
|
||||
}
|
||||
|
||||
for _, empresa := range empresas {
|
||||
var count int64
|
||||
if err := DB.Unscoped().Model(&models.FormaDePago{}).
|
||||
Where("empresa_id = ?", empresa.ID).
|
||||
Count(&count).Error; err != nil {
|
||||
return fmt.Errorf("contar formas de pago de empresa %d: %w", empresa.ID, err)
|
||||
}
|
||||
if count > 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, descripcion := range formasPagoDemo {
|
||||
forma := models.FormaDePago{
|
||||
EmpresaID: empresa.ID,
|
||||
Descripcion: descripcion,
|
||||
}
|
||||
if err := DB.Create(&forma).Error; err != nil {
|
||||
return fmt.Errorf("crear forma de pago %s de empresa %d: %w", descripcion, empresa.ID, err)
|
||||
}
|
||||
}
|
||||
log.Printf("pagos: formas de pago iniciales creadas para empresa %d", empresa.ID)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package factura
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
dto "repuestera_back/dto/Facturas"
|
||||
"repuestera_back/repositorios"
|
||||
"repuestera_back/services"
|
||||
"repuestera_back/utils"
|
||||
)
|
||||
|
||||
// RegistrarPago registra un cobro sobre una factura existente.
|
||||
func RegistrarPago(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
var data dto.RegistrarPagoDto
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resultado, err := services.RegistrarPagoFactura(
|
||||
repositorios.BaseDeDatos(),
|
||||
repositorios.ObtenerRepositorios(c),
|
||||
utils.EmpresaID(c),
|
||||
c.GetUint("userID"),
|
||||
uint(id),
|
||||
data,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, resultado)
|
||||
}
|
||||
@@ -5,11 +5,22 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"repuestera_back/models"
|
||||
r "repuestera_back/repositorios"
|
||||
)
|
||||
|
||||
func ObtenerFormasPago(c *gin.Context) {
|
||||
formas, err := r.ObtenerRepositorios(c).FormaDePago.ObtenerTodos()
|
||||
repo := r.ObtenerRepositorios(c).FormaDePago
|
||||
|
||||
var (
|
||||
formas []models.FormaDePago
|
||||
err error
|
||||
)
|
||||
if c.Query("activas") == "true" {
|
||||
formas, err = repo.ListarActivas()
|
||||
} else {
|
||||
formas, err = repo.ObtenerTodos()
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package dto
|
||||
|
||||
// RegistrarPagoDto representa el cobro de una factura existente.
|
||||
type RegistrarPagoDto struct {
|
||||
FormaDePagoID uint `json:"formaDePagoId" binding:"required"`
|
||||
Importe float64 `json:"importe" binding:"required,gt=0"`
|
||||
Fecha string `json:"fecha"`
|
||||
Observacion string `json:"observacion" binding:"max=255"`
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package dto
|
||||
|
||||
// RegistrarPagoResponse devuelve el pago creado y el estado final de la
|
||||
// factura para que el frontend refresque saldo y estado sin otra consulta.
|
||||
type RegistrarPagoResponse struct {
|
||||
Pago PagoResumen `json:"pago"`
|
||||
Factura FacturaResponse `json:"factura"`
|
||||
SaldoAnterior float64 `json:"saldoAnterior"`
|
||||
SaldoNuevo float64 `json:"saldoNuevo"`
|
||||
}
|
||||
+1
-1
@@ -15,7 +15,7 @@ type Pago struct {
|
||||
FormaDePago FormaDePago `gorm:"foreignKey:FormaDePagoID"`
|
||||
ReciboID *uint `json:"reciboId,omitempty"`
|
||||
Recibo *Recibo `gorm:"foreignKey:ReciboID" json:"recibo,omitempty"`
|
||||
Importe float64 `gorm:"type:decimal(10,2)"`
|
||||
Importe float64 `gorm:"type:decimal(15,2)"`
|
||||
Fecha time.Time `gorm:"not null" json:"fecha"`
|
||||
Observacion string `gorm:"type:varchar(255)" json:"observacion,omitempty"`
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
decorator "repuestera_back/repositorios/Decorator/facturas"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type RepositorioFactura interface {
|
||||
@@ -75,7 +76,7 @@ func (r *repositorioFactura) BloquearPorID(tx *gorm.DB, id uint) (*models.Factur
|
||||
if r.empresaID > 0 {
|
||||
db = db.Where("empresa_id = ?", r.empresaID)
|
||||
}
|
||||
if err := db.Set("gorm:query_option", "FOR UPDATE").Preload("Cliente").First(&factura, id).Error; err != nil {
|
||||
if err := db.Clauses(clause.Locking{Strength: "UPDATE"}).Preload("Cliente").First(&factura, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &factura, nil
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
type RepositorioFormaDePago interface {
|
||||
IRepositorio[models.FormaDePago]
|
||||
ObtenerPorDescripcion(descripcion string) (*models.FormaDePago, error)
|
||||
ListarActivas() ([]models.FormaDePago, error)
|
||||
ObtenerActivaPorID(id uint) (*models.FormaDePago, error)
|
||||
}
|
||||
|
||||
type repositorioFormaDePago struct {
|
||||
@@ -34,3 +36,21 @@ func (r *repositorioFormaDePago) ObtenerPorDescripcion(descripcion string) (*mod
|
||||
}
|
||||
return &fp, nil
|
||||
}
|
||||
|
||||
// ListarActivas devuelve las formas de pago vigentes de la empresa.
|
||||
func (r *repositorioFormaDePago) ListarActivas() ([]models.FormaDePago, error) {
|
||||
var formas []models.FormaDePago
|
||||
if err := r.db.Order("descripcion ASC").Find(&formas).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return formas, nil
|
||||
}
|
||||
|
||||
// ObtenerActivaPorID busca una forma de pago vigente de la empresa.
|
||||
func (r *repositorioFormaDePago) ObtenerActivaPorID(id uint) (*models.FormaDePago, error) {
|
||||
var fp models.FormaDePago
|
||||
if err := r.db.First(&fp, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &fp, nil
|
||||
}
|
||||
@@ -67,6 +67,10 @@ func main() {
|
||||
log.Fatalf("failed to migrate stock data: %v", err)
|
||||
}
|
||||
|
||||
if err := config.MigrarPagos(); err != nil {
|
||||
log.Fatalf("failed to migrate payment data: %v", err)
|
||||
}
|
||||
|
||||
config.InitPermisos()
|
||||
|
||||
fmt.Println("Database connected and migrated successfully")
|
||||
|
||||
@@ -19,11 +19,12 @@ func FacturaRoute(r *gin.Engine) {
|
||||
}
|
||||
|
||||
// Escritura: solo gestión de ventas. Se agregan en CU-02, CU-05, CU-06,
|
||||
// CU-07, CU-08 y CU-16.
|
||||
// CU-07, CU-08, CU-16 y CU-17.
|
||||
escritura := r.Group("/facturas")
|
||||
escritura.Use(middleware.AuthMiddleware(15))
|
||||
{
|
||||
escritura.POST("/", factura.CrearFactura)
|
||||
escritura.POST("/:id/pagos", factura.RegistrarPago)
|
||||
escritura.POST("/:id/enviar-email", factura.EnviarEmailComprobante)
|
||||
}
|
||||
}
|
||||
@@ -89,10 +89,10 @@ func CrearFactura(
|
||||
|
||||
// Validar pagos.
|
||||
for _, pago := range entrada.Pagos {
|
||||
if err := validarCantidad(pago.Importe); err != nil {
|
||||
if err := validarImportePago(pago.Importe); err != nil {
|
||||
return nil, fmt.Errorf("importe de pago inválido: %w", err)
|
||||
}
|
||||
if _, err := repo.FormaDePago.ObtenerPorID(pago.FormaDePagoID); err != nil {
|
||||
if _, err := repo.FormaDePago.ObtenerActivaPorID(pago.FormaDePagoID); err != nil {
|
||||
return nil, fmt.Errorf("forma de pago %d no encontrada", pago.FormaDePagoID)
|
||||
}
|
||||
}
|
||||
@@ -133,7 +133,7 @@ func CrearFactura(
|
||||
|
||||
var sumaPagos float64
|
||||
for _, pago := range entrada.Pagos {
|
||||
sumaPagos = redondearCantidad(sumaPagos + pago.Importe)
|
||||
sumaPagos = redondearMonto(sumaPagos + pago.Importe)
|
||||
}
|
||||
if sumaPagos > total {
|
||||
return nil, errors.New("los pagos superan el total de la factura")
|
||||
@@ -226,41 +226,19 @@ func CrearFactura(
|
||||
return err
|
||||
}
|
||||
|
||||
// Pagos inmediatos.
|
||||
// Pagos inmediatos: usan la misma lógica que el cobro posterior.
|
||||
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,
|
||||
_, _, err := registrarPagoTx(tx, repo, factura, dto.RegistrarPagoDto{
|
||||
FormaDePagoID: pagoEntrada.FormaDePagoID,
|
||||
Importe: pagoEntrada.Importe,
|
||||
Fecha: fecha,
|
||||
Fecha: pagoEntrada.Fecha,
|
||||
Observacion: pagoEntrada.Observacion,
|
||||
}
|
||||
if err := repo.Pago.Registrar(tx, pago); err != nil {
|
||||
})
|
||||
if 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 {
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
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
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export async function obtenerFormasPago(fetch2?: Function) {
|
||||
export async function obtenerFormasPago(fetch2?: Function, soloActivas = false) {
|
||||
const fetchfn = fetch2 ? fetch2 : fetch;
|
||||
const qs = soloActivas ? '?activas=true' : '';
|
||||
try {
|
||||
const req = await fetchfn(`${API_URL}/formas-pago/`, {
|
||||
const req = await fetchfn(`${API_URL}/formas-pago/${qs}`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }
|
||||
});
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { API_URL } from '$lib/env';
|
||||
import { getToken } from '../token';
|
||||
|
||||
export interface RegistrarPagoPayload {
|
||||
formaDePagoId: number;
|
||||
importe: number;
|
||||
fecha?: string;
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export async function registrarPago(facturaId: number, payload: RegistrarPagoPayload) {
|
||||
try {
|
||||
const req = await fetch(`${API_URL}/facturas/${facturaId}/pagos`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await req.json();
|
||||
if (req.ok) return data;
|
||||
return data.error ?? 'error';
|
||||
} catch {
|
||||
return 'no se pudo alcanzar el servidor';
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,14 @@
|
||||
Tag,
|
||||
TextInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
Modal
|
||||
SelectItem
|
||||
} from 'carbon-components-svelte';
|
||||
import { Add, View, Edit, Money, Close, Search } from 'carbon-icons-svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { getPermissions } from '$lib/hooks/token';
|
||||
import type { Factura } from '../../types';
|
||||
import ModalVerComprobante from './ModalVerComprobante.svelte';
|
||||
import RegistrarPagoModal from './RegistrarPagoModal.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
);
|
||||
let cargando = $derived(data.facturas === undefined || data.facturas === null);
|
||||
|
||||
let puedeVentas = $derived(getPermissions().includes(13));
|
||||
let puedeVentas = $derived(getPermissions().includes(15));
|
||||
|
||||
let numero = $state('');
|
||||
let cliente = $state('');
|
||||
@@ -57,6 +57,8 @@
|
||||
|
||||
let facturaId = $state(0);
|
||||
let openVer = $state(false);
|
||||
let facturaPago = $state<Factura | null>(null);
|
||||
let openPago = $state(false);
|
||||
|
||||
function buscar() {
|
||||
const params = new URLSearchParams();
|
||||
@@ -129,7 +131,7 @@
|
||||
}}
|
||||
>
|
||||
<div class="min-w-56 flex-1">
|
||||
<TextInput labelText="Buscar" placeholder="N° factura o cliente" bind:value={numero} />
|
||||
<TextInput labelText="Buscar" placeholder="N° factura" bind:value={numero} />
|
||||
</div>
|
||||
<div class="min-w-40">
|
||||
<TextInput labelText="Cliente" placeholder="Nombre del cliente" bind:value={cliente} />
|
||||
@@ -241,14 +243,19 @@
|
||||
kind="ghost"
|
||||
size="small"
|
||||
icon={Money}
|
||||
disabled={f.estado === 'CANCELADA' || f.estado === 'PAGADA'}
|
||||
>Registrar Pago</Button
|
||||
disabled={f.estado === 'CANCELADA' ||
|
||||
f.estado === 'PAGADA' ||
|
||||
(f.saldo ?? 0) <= 0}
|
||||
onclick={() => {
|
||||
facturaPago = f;
|
||||
openPago = true;
|
||||
}}>Registrar Pago</Button
|
||||
>
|
||||
<Button
|
||||
kind="danger-ghost"
|
||||
size="small"
|
||||
icon={Close}
|
||||
disabled={f.estado === 'CANCELADA'}>Cancelar</Button
|
||||
disabled={f.estado === 'CANCELADA' || f.estado === 'PAGADA'}>Cancelar</Button
|
||||
>
|
||||
</div>
|
||||
</TableCell>
|
||||
@@ -261,4 +268,9 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<ModalVerComprobante bind:open={openVer} {facturaId} />
|
||||
<ModalVerComprobante bind:open={openVer} {facturaId} />
|
||||
<RegistrarPagoModal
|
||||
bind:open={openPago}
|
||||
factura={facturaPago}
|
||||
onClose={() => (facturaPago = null)}
|
||||
/>
|
||||
@@ -0,0 +1,226 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
InlineNotification,
|
||||
Modal,
|
||||
NumberInput,
|
||||
Select,
|
||||
SelectItem,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { invalidate } from '$app/navigation';
|
||||
import { obtenerFormasPago } from '$lib/hooks/facturas/obtenerFormasPago';
|
||||
import { registrarPago } from '$lib/hooks/facturas/registrarPago';
|
||||
import type { Factura, FormaDePago } from '../../types';
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
factura = null,
|
||||
onClose
|
||||
}: {
|
||||
open?: boolean;
|
||||
factura?: Factura | null;
|
||||
onClose?: () => void;
|
||||
} = $props();
|
||||
|
||||
let monto = $state(0);
|
||||
let formaDePagoId = $state(0);
|
||||
let fecha = $state('');
|
||||
let observacion = $state('');
|
||||
let formasPago = $state<FormaDePago[]>([]);
|
||||
let cargandoFormas = $state(false);
|
||||
let enviando = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
const saldo = $derived(factura ? Number(factura.saldo ?? 0) : 0);
|
||||
const total = $derived(factura ? Number(factura.total ?? 0) : 0);
|
||||
const bloqueada = $derived(
|
||||
!factura || factura.estado === 'PAGADA' || factura.estado === 'CANCELADA' || saldo <= 0.005
|
||||
);
|
||||
|
||||
function redondear2(valor: number): number {
|
||||
return Math.round(valor * 100) / 100;
|
||||
}
|
||||
|
||||
function hoyISO(): string {
|
||||
const hoy = new Date();
|
||||
const mes = String(hoy.getMonth() + 1).padStart(2, '0');
|
||||
const dia = String(hoy.getDate()).padStart(2, '0');
|
||||
return `${hoy.getFullYear()}-${mes}-${dia}`;
|
||||
}
|
||||
|
||||
function formatMonto(valor?: number): string {
|
||||
if (valor === undefined || valor === null) return '-';
|
||||
return valor.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' });
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
open = false;
|
||||
onClose?.();
|
||||
}
|
||||
|
||||
async function cargarFormas() {
|
||||
cargandoFormas = true;
|
||||
const res = await obtenerFormasPago(fetch, true);
|
||||
cargandoFormas = false;
|
||||
if (Array.isArray(res)) {
|
||||
formasPago = res;
|
||||
} else {
|
||||
formasPago = [];
|
||||
error = typeof res === 'string' ? res : 'no se pudieron cargar las formas de pago';
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
monto = redondear2(factura?.saldo ?? 0);
|
||||
formaDePagoId = 0;
|
||||
fecha = hoyISO();
|
||||
observacion = '';
|
||||
error = '';
|
||||
enviando = false;
|
||||
void cargarFormas();
|
||||
});
|
||||
|
||||
async function enviar() {
|
||||
if (enviando || !factura) return;
|
||||
error = '';
|
||||
|
||||
const importe = Number(monto ?? 0);
|
||||
if (!Number.isFinite(importe) || importe <= 0) {
|
||||
error = 'El importe debe ser mayor a cero.';
|
||||
return;
|
||||
}
|
||||
if (Math.abs(importe - redondear2(importe)) > 0.000005) {
|
||||
error = 'El importe debe tener como máximo 2 decimales.';
|
||||
return;
|
||||
}
|
||||
if (importe > saldo + 0.005) {
|
||||
error = `El importe supera el saldo pendiente (${formatMonto(saldo)}).`;
|
||||
return;
|
||||
}
|
||||
if (!formaDePagoId) {
|
||||
error = 'Seleccioná una forma de pago.';
|
||||
return;
|
||||
}
|
||||
if (!fecha) {
|
||||
error = 'Ingresá la fecha de pago.';
|
||||
return;
|
||||
}
|
||||
if (fecha > hoyISO()) {
|
||||
error = 'La fecha de pago no puede ser futura.';
|
||||
return;
|
||||
}
|
||||
|
||||
enviando = true;
|
||||
const res = await registrarPago(factura.ID, {
|
||||
formaDePagoId: Number(formaDePagoId),
|
||||
importe,
|
||||
fecha,
|
||||
observacion: observacion.trim() || undefined
|
||||
});
|
||||
enviando = false;
|
||||
|
||||
if (typeof res === 'string') {
|
||||
error = res;
|
||||
return;
|
||||
}
|
||||
|
||||
await invalidate('facturas:load');
|
||||
open = false;
|
||||
onClose?.();
|
||||
}
|
||||
</script>
|
||||
|
||||
<form
|
||||
id="registrarPagoForm"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void enviar();
|
||||
}}
|
||||
>
|
||||
<Modal
|
||||
formId="registrarPagoForm"
|
||||
bind:open
|
||||
size="lg"
|
||||
modalHeading={`Registrar Pago - Factura ${factura?.numero ?? ''}`}
|
||||
primaryButtonText="Registrar Pago"
|
||||
primaryButtonDisabled={enviando || bloqueada || cargandoFormas}
|
||||
secondaryButtonText="Cancelar"
|
||||
on:click:button--secondary={handleClose}
|
||||
on:close={handleClose}
|
||||
>
|
||||
{#if error}
|
||||
<div class="mb-4">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if bloqueada}
|
||||
<div class="mb-4">
|
||||
<InlineNotification
|
||||
kind="warning"
|
||||
title="Sin saldo pendiente"
|
||||
subtitle="La factura ya está saldada o cancelada y no admite pagos."
|
||||
hideCloseButton
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-5 grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div class="sm:col-span-2">
|
||||
<p class="text-sm text-gray-400">Cliente</p>
|
||||
<p class="font-semibold">{factura?.cliente?.nombre ?? '-'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Total Factura</p>
|
||||
<p class="font-semibold">{formatMonto(total)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm text-gray-400">Saldo Pendiente</p>
|
||||
<p class="font-semibold">{formatMonto(saldo)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<NumberInput
|
||||
labelText="Monto a Pagar"
|
||||
bind:value={monto}
|
||||
min={0.01}
|
||||
max={saldo}
|
||||
step={0.01}
|
||||
allowEmpty
|
||||
disabled={bloqueada}
|
||||
/>
|
||||
|
||||
<Select
|
||||
labelText="Medio de Pago"
|
||||
bind:selected={formaDePagoId}
|
||||
disabled={cargandoFormas || bloqueada}
|
||||
>
|
||||
<SelectItem value={0} text="Seleccioná una forma de pago" />
|
||||
{#each formasPago as forma (forma.ID)}
|
||||
<SelectItem value={forma.ID} text={forma.descripcion} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
{#if !cargandoFormas && formasPago.length === 0}
|
||||
<p class="text-sm text-gray-500">No hay formas de pago configuradas.</p>
|
||||
{/if}
|
||||
|
||||
<TextInput
|
||||
labelText="Fecha de Pago"
|
||||
type="date"
|
||||
bind:value={fecha}
|
||||
max={hoyISO()}
|
||||
disabled={bloqueada}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
labelText="Observación (opcional)"
|
||||
bind:value={observacion}
|
||||
maxlength={255}
|
||||
disabled={bloqueada}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
</form>
|
||||
@@ -2,7 +2,7 @@
|
||||
import { Modal, TextInput, DataTable, Button } from 'carbon-components-svelte';
|
||||
import type { Cliente } from '../../../types';
|
||||
|
||||
let { open = false, clientes = [], onSeleccionar }: {
|
||||
let { open = $bindable(false), clientes = [], onSeleccionar }: {
|
||||
open?: boolean;
|
||||
clientes?: Cliente[];
|
||||
onSeleccionar?: (id: number) => void;
|
||||
|
||||
@@ -120,7 +120,7 @@
|
||||
<Select labelText="Almacén" bind:selected={filtros.almacenId}>
|
||||
<SelectItem value={0} text="Todos" />
|
||||
{#each data.almacenes as a (a.id)}
|
||||
<SelectItem value={a.id} text={a.nombre} />
|
||||
<SelectItem value={a.id} text={a.codigo} />
|
||||
{/each}
|
||||
</Select>
|
||||
|
||||
|
||||
Vendored
+14
@@ -372,3 +372,17 @@ export interface FormaDePago extends BaseModel {
|
||||
empresaId?: number;
|
||||
descripcion: string;
|
||||
}
|
||||
|
||||
export interface RegistrarPagoPayload {
|
||||
formaDePagoId: number;
|
||||
importe: number;
|
||||
fecha?: string;
|
||||
observacion?: string;
|
||||
}
|
||||
|
||||
export interface RegistrarPagoResponse {
|
||||
pago: PagoResumen;
|
||||
factura: Factura;
|
||||
saldoAnterior: number;
|
||||
saldoNuevo: number;
|
||||
}
|
||||
Reference in new issue
Block a user