diff --git a/back/controllers/facturas/EnviarEmailComprobante.go b/back/controllers/facturas/EnviarEmailComprobante.go new file mode 100644 index 0000000..260bcbd --- /dev/null +++ b/back/controllers/facturas/EnviarEmailComprobante.go @@ -0,0 +1,75 @@ +package factura + +import ( + "errors" + "fmt" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + dto_directors "repuestera_back/dto/Builders/Directors" + r "repuestera_back/repositorios" + "repuestera_back/services" +) + +// EnviarEmailComprobante envía por email el comprobante de venta al cliente +// de la factura indicada. Requiere que el cliente tenga email registrado. +func EnviarEmailComprobante(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"}) + return + } + + repo := r.ObtenerRepositorios(c) + factura, err := repo.Factura.ObtenerConRelaciones(uint(id)) + if errors.Is(err, gorm.ErrRecordNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "factura no encontrada"}) + return + } + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + if factura.Cliente.Email == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "el cliente no tiene email registrado"}) + return + } + + // Nombres reales de repuestos desde la base de datos. + nombres := make(map[uint64]string, len(factura.Detalles)) + for _, d := range factura.Detalles { + repuesto, err := repo.Repuesto.ObtenerPorID(uint(d.RepuestoID)) + if err == nil && repuesto != nil && *repuesto != nil { + nombres[d.RepuestoID] = (*repuesto).Nombre + } else { + nombres[d.RepuestoID] = fmt.Sprintf("Repuesto %d", d.RepuestoID) + } + } + + // Pagos realizados de esta factura. + pagos, err := repo.Pago.ListarPorFactura(factura.ID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta( + factura, nombres, pagos, factura.Cliente.Email, + ) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + userID := c.GetUint("userID") + if !services.EnviarEmail(*mensaje, userID) { + c.JSON(http.StatusInternalServerError, gin.H{"error": "no se pudo enviar el email"}) + return + } + + c.JSON(http.StatusOK, gin.H{"mensaje": "email enviado correctamente"}) +} diff --git a/back/controllers/facturas/ObtenerComprobante.go b/back/controllers/facturas/ObtenerComprobante.go new file mode 100644 index 0000000..55d9dc1 --- /dev/null +++ b/back/controllers/facturas/ObtenerComprobante.go @@ -0,0 +1,68 @@ +package factura + +import ( + "errors" + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" + + dto_directors "repuestera_back/dto/Builders/Directors" + dto_facturas "repuestera_back/dto/Facturas" + r "repuestera_back/repositorios" +) + +// ObtenerComprobante devuelve el detalle de una factura junto con sus pagos, +// listo para renderizar el comprobante de venta. +func ObtenerComprobante(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "id inválido"}) + return + } + + factura, err := r.ObtenerRepositorios(c).Factura.ObtenerConRelaciones(uint(id)) + if errors.Is(err, gorm.ErrRecordNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "factura no encontrada"}) + return + } + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + pagos, err := r.ObtenerRepositorios(c).Pago.ListarPorFactura(factura.ID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + respuesta, err := dto_directors.NewFacturaDirector().DesdeFactura(factura) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + pagosResumen := make([]dto_facturas.PagoResumen, 0, len(pagos)) + for _, p := range pagos { + forma := "" + if p.FormaDePago.ID != 0 { + forma = p.FormaDePago.Descripcion + } + pagosResumen = append(pagosResumen, dto_facturas.PagoResumen{ + ID: p.ID, + FacturaID: p.FacturaID, + FormaDePagoID: p.FormaDePagoID, + FormaDePago: forma, + Importe: p.Importe, + Fecha: p.Fecha, + Observacion: p.Observacion, + }) + } + + c.JSON(http.StatusOK, dto_facturas.ComprobanteResponse{ + FacturaResponse: respuesta, + Pagos: pagosResumen, + }) +} diff --git a/back/dto/Builders/ComprobanteVentaEmailBuilder.go b/back/dto/Builders/ComprobanteVentaEmailBuilder.go index ed9beb1..97a4945 100644 --- a/back/dto/Builders/ComprobanteVentaEmailBuilder.go +++ b/back/dto/Builders/ComprobanteVentaEmailBuilder.go @@ -17,6 +17,7 @@ import ( type ComprobanteVentaEmailBuilder struct { factura *models.Factura nombres map[uint64]string + pagos []models.Pago destinatario string err error } @@ -40,6 +41,11 @@ func (b *ComprobanteVentaEmailBuilder) ConNombresRepuestos(nombres map[uint64]st return b } +func (b *ComprobanteVentaEmailBuilder) ConPagos(pagos []models.Pago) *ComprobanteVentaEmailBuilder { + b.pagos = pagos + return b +} + func (b *ComprobanteVentaEmailBuilder) ConDestinatario(destinatario string) *ComprobanteVentaEmailBuilder { b.destinatario = strings.TrimSpace(destinatario) if b.destinatario == "" { @@ -58,7 +64,7 @@ func (b *ComprobanteVentaEmailBuilder) Build() (*dto_email.MensajeEmail, error) return NewMensajeEmailBuilder(). ConTitulo("Comprobante de venta " + b.factura.Numero). - ConDescripcion(htmlComprobanteVenta(b.factura, b.nombres)). + ConDescripcion(htmlComprobanteVenta(b.factura, b.nombres, b.pagos)). ConItems([]string{}). ConDestinatarios([]string{b.destinatario}). Build() @@ -75,7 +81,7 @@ const ( // htmlComprobanteVenta genera el cuerpo HTML del comprobante. Usa tablas y // estilos inline porque los clientes de correo suelen ignorar las hojas de // estilo. -func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) string { +func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string, pagos []models.Pago) string { var b strings.Builder b.WriteString(`
`) @@ -112,13 +118,16 @@ func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) st b.WriteString(`Sin detalles`) } for _, detalle := range factura.Detalles { - nombre := fmt.Sprintf("Repuesto %d", detalle.RepuestoID) + nombre := detalle.RepuestoID // placeholder, se reemplaza abajo + _ = nombre + nombreRepuesto := fmt.Sprintf("Repuesto %d", detalle.RepuestoID) if n := strings.TrimSpace(nombres[detalle.RepuestoID]); n != "" { - nombre = n + nombreRepuesto = n } fmt.Fprintf(&b, - `%s%.3f%s%s`, - comprobanteColorBorder, htmlutil.EscapeString(nombre), detalle.Cantidad, + `%s%s%s%s`, + comprobanteColorBorder, htmlutil.EscapeString(nombreRepuesto), + formatoCantidad(detalle.Cantidad), montoComprobante(detalle.PrecioUnitario), montoComprobante(detalle.Subtotal), ) } @@ -143,6 +152,34 @@ func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) st } b.WriteString(``) + // Sección de pagos realizados + if len(pagos) > 0 { + b.WriteString(`

Pagos realizados

`) + b.WriteString(``) + b.WriteString(``) + b.WriteString(``) + b.WriteString(``) + b.WriteString(``) + b.WriteString(``) + b.WriteString(``) + for _, pago := range pagos { + forma := "-" + if pago.FormaDePago.ID != 0 { + forma = pago.FormaDePago.Descripcion + } + fechaStr := pago.Fecha.Format("02/01/2006 15:04") + obs := pago.Observacion + if obs == "" { + obs = "-" + } + fmt.Fprintf(&b, + ``, + comprobanteColorBorder, fechaStr, htmlutil.EscapeString(forma), montoComprobante(pago.Importe), comprobanteColorMuted, htmlutil.EscapeString(obs), + ) + } + b.WriteString(`
FechaForma de pagoImporteObservación
%s%s%s%s
`) + } + if observacion := strings.TrimSpace(factura.Observacion); observacion != "" { fmt.Fprintf(&b, `

Observación: %s

`, comprobanteColorMuted, htmlutil.EscapeString(observacion)) } @@ -153,6 +190,22 @@ func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) st return b.String() } +// formatoCantidad devuelve la cantidad como número entero si no tiene decimales, +// o con coma decimal si los tiene (formato AR). +func formatoCantidad(cantidad float64) string { + if cantidad == float64(int64(cantidad)) { + return strconv.FormatInt(int64(cantidad), 10) + } + // Tiene decimales: mostrar con coma + centavos := int64(math.Round(cantidad * 100)) + entero := centavos / 100 + dec := centavos % 100 + if dec == 0 { + return strconv.FormatInt(entero, 10) + } + return fmt.Sprintf("%d,%02d", entero, dec) +} + // montoComprobante formatea importes con separador de miles y coma decimal. func montoComprobante(valor float64) string { negativo := valor < 0 diff --git a/back/dto/Builders/Directors/EmailDirector.go b/back/dto/Builders/Directors/EmailDirector.go index 2a71409..a13b375 100644 --- a/back/dto/Builders/Directors/EmailDirector.go +++ b/back/dto/Builders/Directors/EmailDirector.go @@ -20,11 +20,13 @@ func NewEmailDirector() *EmailDirector { func (d *EmailDirector) ComprobanteVenta( factura *models.Factura, nombresRepuestos map[uint64]string, + pagos []models.Pago, destinatario string, ) (*dto_email.MensajeEmail, error) { return builders.NewComprobanteVentaEmailBuilder(). ConFactura(factura). ConNombresRepuestos(nombresRepuestos). + ConPagos(pagos). ConDestinatario(destinatario). Build() } diff --git a/back/dto/Facturas/ComprobanteResponse.go b/back/dto/Facturas/ComprobanteResponse.go new file mode 100644 index 0000000..65e03a1 --- /dev/null +++ b/back/dto/Facturas/ComprobanteResponse.go @@ -0,0 +1,9 @@ +package dto + +// ComprobanteResponse es la representación pública de una factura para +// visualizar el comprobante. Incluye todos los datos de FacturaResponse +// más la lista de pagos realizados. +type ComprobanteResponse struct { + *FacturaResponse + Pagos []PagoResumen `json:"pagos"` +} diff --git a/back/dto/Facturas/PagoResumen.go b/back/dto/Facturas/PagoResumen.go new file mode 100644 index 0000000..0f7cf07 --- /dev/null +++ b/back/dto/Facturas/PagoResumen.go @@ -0,0 +1,15 @@ +package dto + +import "time" + +// PagoResumen es la representación ligera de un pago de factura, +// usada para mostrar el historial de pagos en el comprobante. +type PagoResumen struct { + ID uint `json:"id"` + FacturaID uint `json:"facturaId,omitempty"` + FormaDePagoID uint `json:"formaDePagoId,omitempty"` + FormaDePago string `json:"formaDePago,omitempty"` + Importe float64 `json:"importe"` + Fecha time.Time `json:"fecha"` + Observacion string `json:"observacion,omitempty"` +} diff --git a/back/repositorios/RepositorioPago.go b/back/repositorios/RepositorioPago.go index 46b9fc4..59655ac 100644 --- a/back/repositorios/RepositorioPago.go +++ b/back/repositorios/RepositorioPago.go @@ -38,9 +38,11 @@ func (r *repositorioPago) Registrar(tx *gorm.DB, pago *models.Pago) error { return tx.Create(pago).Error } +// ListarPorFactura devuelve los pagos de una factura, con la forma de pago +// precargada para poder mostrar su descripción. func (r *repositorioPago) ListarPorFactura(facturaID uint) ([]models.Pago, error) { var pagos []models.Pago - if err := r.db.Where("factura_id = ?", facturaID).Find(&pagos).Error; err != nil { + if err := r.db.Where("facturaId = ?", facturaID).Preload("FormaDePago").Find(&pagos).Error; err != nil { return nil, err } return pagos, nil @@ -48,7 +50,7 @@ func (r *repositorioPago) ListarPorFactura(facturaID uint) ([]models.Pago, error func (r *repositorioPago) SumarPorFactura(facturaID uint) (float64, error) { var total float64 - if err := r.db.Model(&models.Pago{}).Where("factura_id = ?", facturaID).Select("COALESCE(SUM(importe),0)").Scan(&total).Error; err != nil { + if err := r.db.Model(&models.Pago{}).Where("facturaId = ?", facturaID).Select("COALESCE(SUM(importe),0)").Scan(&total).Error; err != nil { return 0, err } return total, nil diff --git a/back/routes/FacturaRoute.go b/back/routes/FacturaRoute.go index 499c1c6..09baf7c 100644 --- a/back/routes/FacturaRoute.go +++ b/back/routes/FacturaRoute.go @@ -15,6 +15,7 @@ func FacturaRoute(r *gin.Engine) { { grupo.GET("/", factura.ObtenerFacturas) grupo.GET("/:id", factura.ObtenerFactura) + grupo.GET("/:id/comprobante", factura.ObtenerComprobante) } // Escritura: solo gestión de ventas. Se agregan en CU-02, CU-05, CU-06, @@ -23,5 +24,6 @@ func FacturaRoute(r *gin.Engine) { escritura.Use(middleware.AuthMiddleware(15)) { escritura.POST("/", factura.CrearFactura) + escritura.POST("/:id/enviar-email", factura.EnviarEmailComprobante) } } diff --git a/back/services/facturacion.go b/back/services/facturacion.go index 29f4bd0..16bc953 100644 --- a/back/services/facturacion.go +++ b/back/services/facturacion.go @@ -270,7 +270,7 @@ func CrearFactura( // 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) + mensaje, err := dto_directors.NewEmailDirector().ComprobanteVenta(facturaCreada, nombresRepuestos, nil, 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) { diff --git a/front/src/lib/hooks/facturas/comprobante.ts b/front/src/lib/hooks/facturas/comprobante.ts new file mode 100644 index 0000000..dbc3efe --- /dev/null +++ b/front/src/lib/hooks/facturas/comprobante.ts @@ -0,0 +1,96 @@ +import { API_URL } from '$lib/env'; +import { getToken } from '../token'; + +export interface PagoResumen { + id: number; + facturaId?: number; + formaDePagoId?: number; + formaDePago?: string; + importe: number; + fecha: string; + observacion?: string; +} + +export interface ComprobanteResponse { + ID: number; + CreatedAt?: string; + UpdatedAt?: string; + DeletedAt?: string | null; + EmpresaID?: number; + numero?: string; + estado: string; + total: number; + subtotal?: number; + descuentoTotal?: number; + impuestos?: number; + alicuotaIva?: number; + saldo?: number; + FechaEmision?: string; + Observacion?: string; + ClienteID?: number; + cliente?: { + ID: number; + nombre: string; + cuit?: string; + email?: string | null; + CreatedAt?: string; + UpdatedAt?: string; + DeletedAt?: string | null; + EmpresaID?: number; + }; + detalles?: Array<{ + repuestoId: number; + cantidad: number; + precioUnitario: number; + subtotal: number; + alicuotaIva?: number; + }>; + ResponsableID?: number; + Version?: number; + SeAviso?: boolean; + pagos: PagoResumen[]; +} + +export async function obtenerComprobante( + fetch2?: Function, + facturaId: number = 0 +) { + const fetchfn = fetch2 ? fetch2 : fetch; + const url = `${API_URL}/facturas/${facturaId}/comprobante`; + try { + const req = await fetchfn(url, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${getToken()}` + } + }); + const data = await req.json(); + if (req.ok) return data; + return data.error ?? 'error'; + } catch { + return 'no se pudo alcanzar el servidor'; + } +} + +export async function enviarEmailComprobante( + fetch2?: Function, + facturaId: number = 0 +) { + const fetchfn = fetch2 ? fetch2 : fetch; + const url = `${API_URL}/facturas/${facturaId}/enviar-email`; + try { + const req = await fetchfn(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${getToken()}` + } + }); + const data = await req.json(); + if (req.ok) return data; + return data.error ?? 'error'; + } catch { + return 'no se pudo alcanzar el servidor'; + } +} diff --git a/front/src/routes/facturas/+page.svelte b/front/src/routes/facturas/+page.svelte index 44b1498..afd7e0b 100644 --- a/front/src/routes/facturas/+page.svelte +++ b/front/src/routes/facturas/+page.svelte @@ -23,6 +23,7 @@ import { goto } from '$app/navigation'; import { getPermissions } from '$lib/hooks/token'; import type { Factura } from '../../types'; + import ModalVerComprobante from './ModalVerComprobante.svelte'; let { data } = $props(); @@ -54,7 +55,7 @@ hasta = filtros.hasta ?? ''; }); - let facturaVer: Factura | null = $state(null); + let facturaId = $state(0); let openVer = $state(false); function buscar() { @@ -226,7 +227,7 @@ size="small" icon={View} onclick={() => { - facturaVer = f; + facturaId = f.ID; openVer = true; }}>Ver @@ -260,28 +261,4 @@ {/if}
- - {#if facturaVer} -
-

Cliente: {facturaVer.cliente?.nombre ?? '-'}

-

CUIT: {facturaVer.cliente?.cuit ?? '-'}

-

Fecha: {formatFecha(facturaVer.CreatedAt)}

-

Total: {formatMonto(facturaVer.total)}

-

Estado: {facturaVer.estado}

- {#if facturaVer.detalles && facturaVer.detalles.length > 0} -
-

Ítems

-
    - {#each facturaVer.detalles as d (d.repuestoId)} -
  • - Repuesto {d.repuestoId} — cant. {d.cantidad} × {formatMonto(d.precioUnitario)} = {formatMonto( - d.subtotal - )} -
  • - {/each} -
-
- {/if} -
- {/if} -
+ \ No newline at end of file diff --git a/front/src/routes/facturas/ModalVerComprobante.svelte b/front/src/routes/facturas/ModalVerComprobante.svelte new file mode 100644 index 0000000..4f0ecb0 --- /dev/null +++ b/front/src/routes/facturas/ModalVerComprobante.svelte @@ -0,0 +1,438 @@ + + + + {#if cargando} +
+

Cargando comprobante…

+
+ {:else if comprobante} +
+ +
+

Repuestera

+

Comprobante de venta

+

Factura {comprobante.numero ?? `F-${comprobante.ID}`}

+
+ + +
+
+

Cliente

+

{comprobante.cliente?.nombre ?? '-'}

+
+
+

CUIT

+

{comprobante.cliente?.cuit ?? '-'}

+
+
+

Fecha

+

{formatFecha(comprobante.FechaEmision)}

+
+
+ +
+
+

Estado

+ + {comprobante.estado} + +
+
+

Total

+

{formatMonto(comprobante.total)}

+
+
+ + {#if (comprobante.saldo ?? 0) > 0} +
+

Saldo a pagar

+

{formatMonto(comprobante.saldo)}

+
+ {/if} + + + {#if comprobante.detalles && comprobante.detalles.length > 0} + + + + + Repuesto + Cant. + Precio unit. + Subtotal + + + + {#each comprobante.detalles as d} + + {nombreRepuesto(d)} + {d.cantidad} + {formatMonto(d.precioUnitario)} + {formatMonto(d.subtotal)} + + {/each} + +
+
+ {/if} + + +
+

💰 Resumen de importe

+ + + + + + + {#if (comprobante.descuentoTotal ?? 0) > 0} + + + + + {/if} + + + + + + + + + +
Subtotal{formatMonto(comprobante.subtotal ?? 0)}
Descuento-{formatMonto(comprobante.descuentoTotal)}
IVA (21%){formatMonto(comprobante.impuestos ?? 0)}
Total{formatMonto(comprobante.total)}
+
+ + +
+

💳 Pagos realizados

+ {#if pagos.length > 0} + + + + + Fecha + Forma de pago + Importe + Observación + + + + {#each pagos as p} + + {formatFechaHora(p.fecha)} + {p.formaDePago ?? '-'} + {formatMonto(p.importe)} + {p.observacion ?? '-'} + + {/each} + +
+
+ {:else} +
+

Sin pagos registrados.

+
+ {/if} +
+ + +
+ + {#if comprobante.cliente?.email} + + {:else} + + {/if} +
+ + {#if error} + + {/if} + {#if info} + + {/if} +
+ {:else if error} +
+ +
+ {:else} +
+

Seleccioná una factura para ver su comprobante.

+
+ {/if} +
+ + \ No newline at end of file diff --git a/front/src/types.d.ts b/front/src/types.d.ts index f0bb13d..f926052 100644 --- a/front/src/types.d.ts +++ b/front/src/types.d.ts @@ -306,6 +306,14 @@ export interface Factura { numero?: string; estado: string; total: number; + subtotal?: number; + descuentoTotal?: number; + impuestos?: number; + alicuotaIva?: number; + saldo?: number; + FechaEmision?: string; + Observacion?: string; + Version?: number; ClienteID?: number; cliente?: Cliente; ProveedorID?: number | null; @@ -316,6 +324,38 @@ export interface Factura { responsable?: Usuario | null; } +export interface PagoResumen { + id: number; + facturaId?: number; + formaDePagoId?: number; + formaDePago?: string; + importe: number; + fecha: string; + observacion?: string; +} + +export interface ComprobanteResponse { + ID: number; + numero?: string; + estado: string; + total: number; + subtotal?: number; + descuentoTotal?: number; + impuestos?: number; + alicuotaIva?: number; + saldo?: number; + FechaEmision?: string; + Observacion?: string; + cliente?: { + ID: number; + nombre: string; + cuit?: string; + email?: string | null; + }; + detalles?: FacturaDetalle[]; + pagos: PagoResumen[]; +} + export interface FacturaResumen { ID: number; numero?: string;