Private
Public Access
commit parcial con la parte de email y comprobante correjido
Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
1 parent
fcf16df5d3
commit
320cc9c241
13 files changed
+813
-36
No files matched your search
@@ -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"})
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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(`<div style="max-width:640px;margin:0 auto;font-family:Arial,Helvetica,sans-serif;color:` + comprobanteColorText + `;">`)
|
||||
@@ -112,13 +118,16 @@ func htmlComprobanteVenta(factura *models.Factura, nombres map[uint64]string) st
|
||||
b.WriteString(`<tr><td colspan="4" style="padding:12px 8px;color:` + comprobanteColorMuted + `;">Sin detalles</td></tr>`)
|
||||
}
|
||||
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,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%.3f</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;font-weight:600;">%s</td></tr>`,
|
||||
comprobanteColorBorder, htmlutil.EscapeString(nombre), detalle.Cantidad,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;font-weight:600;">%s</td></tr>`,
|
||||
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(`</table>`)
|
||||
|
||||
// Sección de pagos realizados
|
||||
if len(pagos) > 0 {
|
||||
b.WriteString(`<h2 style="margin:24px 0 10px;font-size:14px;letter-spacing:1px;text-transform:uppercase;color:` + comprobanteColorMuted + `;">Pagos realizados</h2>`)
|
||||
b.WriteString(`<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;font-size:13px;">`)
|
||||
b.WriteString(`<thead><tr style="background:` + comprobanteColorSoft + `;color:` + comprobanteColorMuted + `;text-align:left;">`)
|
||||
b.WriteString(`<th style="padding:10px 8px;">Fecha</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Forma de pago</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Importe</th>`)
|
||||
b.WriteString(`<th align="right" style="padding:10px 8px;">Observación</th>`)
|
||||
b.WriteString(`</tr></thead><tbody>`)
|
||||
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,
|
||||
`<tr style="border-bottom:1px solid %s;"><td style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;">%s</td><td align="right" style="padding:10px 8px;font-weight:600;">%s</td><td style="padding:10px 8px;color:%s;">%s</td></tr>`,
|
||||
comprobanteColorBorder, fechaStr, htmlutil.EscapeString(forma), montoComprobante(pago.Importe), comprobanteColorMuted, htmlutil.EscapeString(obs),
|
||||
)
|
||||
}
|
||||
b.WriteString(`</tbody></table>`)
|
||||
}
|
||||
|
||||
if observacion := strings.TrimSpace(factura.Observacion); observacion != "" {
|
||||
fmt.Fprintf(&b, `<p style="margin:20px 0 0;font-size:12px;color:%s;"><strong>Observación:</strong> %s</p>`, 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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
}
|
||||
@@ -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</Button
|
||||
>
|
||||
@@ -260,28 +261,4 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal bind:open={openVer} modalHeading={`Comprobante ${facturaVer?.numero ?? ''}`} passiveModal>
|
||||
{#if facturaVer}
|
||||
<div class="space-y-2">
|
||||
<p><strong>Cliente:</strong> {facturaVer.cliente?.nombre ?? '-'}</p>
|
||||
<p><strong>CUIT:</strong> {facturaVer.cliente?.cuit ?? '-'}</p>
|
||||
<p><strong>Fecha:</strong> {formatFecha(facturaVer.CreatedAt)}</p>
|
||||
<p><strong>Total:</strong> {formatMonto(facturaVer.total)}</p>
|
||||
<p><strong>Estado:</strong> {facturaVer.estado}</p>
|
||||
{#if facturaVer.detalles && facturaVer.detalles.length > 0}
|
||||
<div class="mt-4">
|
||||
<p class="mb-2 font-semibold">Ítems</p>
|
||||
<ul class="list-disc pl-5">
|
||||
{#each facturaVer.detalles as d (d.repuestoId)}
|
||||
<li>
|
||||
Repuesto {d.repuestoId} — cant. {d.cantidad} × {formatMonto(d.precioUnitario)} = {formatMonto(
|
||||
d.subtotal
|
||||
)}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
<ModalVerComprobante bind:open={openVer} {facturaId} />
|
||||
@@ -0,0 +1,438 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Button,
|
||||
InlineNotification,
|
||||
Modal,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
Tag,
|
||||
TextInput
|
||||
} from 'carbon-components-svelte';
|
||||
import { Download, Email } from 'carbon-icons-svelte';
|
||||
import { obtenerComprobante, enviarEmailComprobante } from '$lib/hooks/facturas/comprobante';
|
||||
import type { ComprobanteResponse, PagoResumen } from '../../types';
|
||||
|
||||
let { open = $bindable(false), facturaId = 0, onEmailEnviado = () => {} } = $props();
|
||||
|
||||
let comprobante: ComprobanteResponse | null = $state(null);
|
||||
let pagos: PagoResumen[] = $state([]);
|
||||
let cargando = $state(false);
|
||||
let enviandoEmail = $state(false);
|
||||
let error = $state('');
|
||||
let info = $state('');
|
||||
|
||||
function formatFecha(iso?: string): string {
|
||||
if (!iso) return '-';
|
||||
try {
|
||||
return new Date(iso).toLocaleDateString('es-AR');
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
function formatFechaHora(iso?: string): string {
|
||||
if (!iso) return '-';
|
||||
try {
|
||||
return new Date(iso).toLocaleString('es-AR', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
function formatMonto(n?: number): string {
|
||||
if (n === undefined || n === null) return '-';
|
||||
return n.toLocaleString('es-AR', { style: 'currency', currency: 'ARS' });
|
||||
}
|
||||
|
||||
function estadoTagKind(estado: string): 'green' | 'blue' | 'red' | 'gray' | 'warm-gray' {
|
||||
switch (estado) {
|
||||
case 'PAGADA':
|
||||
return 'green';
|
||||
case 'PARCIAL':
|
||||
return 'blue';
|
||||
case 'CANCELADA':
|
||||
return 'red';
|
||||
case 'EMITIDA':
|
||||
return 'warm-gray';
|
||||
default:
|
||||
return 'gray';
|
||||
}
|
||||
}
|
||||
|
||||
function nombreRepuesto(d: { repuestoId: number; nombre?: string }): string {
|
||||
return d.nombre ?? `Repuesto ${d.repuestoId}`;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!open) {
|
||||
comprobante = null;
|
||||
pagos = [];
|
||||
error = '';
|
||||
info = '';
|
||||
}
|
||||
});
|
||||
|
||||
async function cargarComprobante() {
|
||||
if (!facturaId) return;
|
||||
cargando = true;
|
||||
const res = await obtenerComprobante(fetch, facturaId);
|
||||
cargando = false;
|
||||
if (res && typeof res === 'object' && !(res as any).error) {
|
||||
const c = res as ComprobanteResponse;
|
||||
comprobante = c;
|
||||
pagos = c.pagos ?? [];
|
||||
} else {
|
||||
error = typeof res === 'string' ? res : 'no se pudo cargar el comprobante';
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (open && facturaId) {
|
||||
void cargarComprobante();
|
||||
}
|
||||
});
|
||||
|
||||
function descargarComprobante() {
|
||||
if (!comprobante) return;
|
||||
const html = generarHtmlComprobante(comprobante);
|
||||
const win = window.open('', '_blank');
|
||||
if (!win) return;
|
||||
win.document.write(html);
|
||||
win.document.close();
|
||||
win.print();
|
||||
}
|
||||
|
||||
function generarHtmlComprobante(c: ComprobanteResponse): string {
|
||||
const numero = c.numero ?? `F-${c.ID}`;
|
||||
const fecha = c.FechaEmision ? formatFecha(c.FechaEmision) : '-';
|
||||
const cliente = c.cliente?.nombre ?? '-';
|
||||
const cuit = c.cliente?.cuit ?? '-';
|
||||
const estado = c.estado;
|
||||
const total = formatMonto(c.total);
|
||||
const subtotal = formatMonto(c.subtotal);
|
||||
const descuento = c.descuentoTotal ?? 0;
|
||||
const impuestos = formatMonto(c.impuestos);
|
||||
const saldo = c.saldo ?? 0;
|
||||
|
||||
const detallesHtml = (c.detalles ?? [])
|
||||
.map(
|
||||
(d) => `
|
||||
<tr>
|
||||
<td style="border-bottom:1px solid #e0e0e0;padding:12px 8px;">${nombreRepuesto(d)}</td>
|
||||
<td style="border-bottom:1px solid #e0e0e0;padding:12px 8px;text-align:right;">${d.cantidad}</td>
|
||||
<td style="border-bottom:1px solid #e0e0e0;padding:12px 8px;text-align:right;">${formatMonto(d.precioUnitario)}</td>
|
||||
<td style="border-bottom:1px solid #e0e0e0;padding:12px 8px;text-align:right;font-weight:600;">${formatMonto(d.subtotal)}</td>
|
||||
</tr>
|
||||
`
|
||||
)
|
||||
.join('');
|
||||
|
||||
const pagosHtml = pagos.length
|
||||
? pagos
|
||||
.map(
|
||||
(p) => `
|
||||
<tr>
|
||||
<td style="border-bottom:1px solid #e0e0e0;padding:12px 8px;">${formatFechaHora(p.fecha)}</td>
|
||||
<td style="border-bottom:1px solid #e0e0e0;padding:12px 8px;">${p.formaDePago ?? '-'}</td>
|
||||
<td style="border-bottom:1px solid #e0e0e0;padding:12px 8px;text-align:right;font-weight:600;">${formatMonto(p.importe)}</td>
|
||||
<td style="border-bottom:1px solid #e0e0e0;padding:12px 8px;color:#525252;">${p.observacion ?? '-'}</td>
|
||||
</tr>
|
||||
`
|
||||
)
|
||||
.join('')
|
||||
: `<tr><td colspan="4" style="padding:24px;text-align:center;color:#525252;">Sin pagos registrados</td></tr>`;
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Comprobante ${numero}</title>
|
||||
<style>
|
||||
body { font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #161616; margin: 0; padding: 24px; }
|
||||
.header { background: linear-gradient(135deg, #0f62fe 0%, #0043ce 100%); color: #fff; padding: 32px 28px; border-radius: 12px 12px 0 0; margin-bottom: 0; }
|
||||
.header .brand { font-size: 11px; letter-spacing: 2px; text-transform: uppercase; opacity: .9; margin: 0 0 8px 0; }
|
||||
.header h1 { margin: 0 0 6px 0; font-size: 26px; font-weight: 700; }
|
||||
.header .numero { font-size: 15px; opacity: .95; margin: 0; }
|
||||
.body { border: 1px solid #e0e0e0; border-top: 0; padding: 28px; border-radius: 0 0 12px 12px; background: #fff; }
|
||||
.section-title { font-size: 13px; text-transform: uppercase; letter-spacing: 1px; color: #525252; font-weight: 700; margin: 24px 0 12px; display: flex; align-items: center; gap: 8px; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 14px; margin-bottom: 16px; }
|
||||
th { background: #f8fafc; color: #525252; text-align: left; padding: 12px 10px; font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: .5px; border-bottom: 2px solid #e0e0e0; }
|
||||
td { padding: 12px 10px; border-bottom: 1px solid #f0f0f0; color: #333; }
|
||||
tr:last-child td { border-bottom: none; }
|
||||
.right { text-align: right; }
|
||||
.muted { color: #525252; }
|
||||
.total-row td { font-size: 18px; font-weight: 800; border-top: 3px solid #0f62fe; padding-top: 16px; color: #0f62fe; }
|
||||
.saldo-row td { font-weight: 700; color: #da1e28; }
|
||||
.kv-table td { width: 40%; }
|
||||
.kv-table td:first-child { color: #525252; font-weight: 500; }
|
||||
.kv-table td:last-child { font-weight: 600; text-align: right; }
|
||||
.card { background: #f8fafc; border: 1px solid #e8eef6; border-radius: 10px; padding: 20px; margin-top: 16px; }
|
||||
.card-title { font-size: 13px; text-transform: uppercase; letter-spacing: 1px; color: #525252; font-weight: 700; margin: 0 0 12px 0; display: flex; align-items: center; gap: 8px; }
|
||||
@media print { body { padding: 0; background: #fff; } .no-print { display: none !important; } .card { background: #fff; border: none; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<p class="brand">Repuestera</p>
|
||||
<h1>Comprobante de venta</h1>
|
||||
<p class="numero">Factura <strong>${numero}</strong></p>
|
||||
</div>
|
||||
<div class="body">
|
||||
<table class="kv-table">
|
||||
<tr><td class="muted">Cliente</td><td>${cliente}</td></tr>
|
||||
<tr><td class="muted">CUIT</td><td>${cuit}</td></tr>
|
||||
<tr><td class="muted">Fecha de emisión</td><td>${fecha}</td></tr>
|
||||
<tr><td class="muted">Estado</td><td><strong>${estado}</strong></td></tr>
|
||||
</table>
|
||||
|
||||
<div class="section-title">🧾 Detalle de la compra</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Repuesto</th>
|
||||
<th class="right">Cant.</th>
|
||||
<th class="right">Precio unit.</th>
|
||||
<th class="right">Subtotal</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${detallesHtml}</tbody>
|
||||
</table>
|
||||
|
||||
<div class="card">
|
||||
<p class="card-title">💰 Resumen de importe</p>
|
||||
<table class="kv-table">
|
||||
<tr><td class="muted">Subtotal</td><td>${subtotal}</td></tr>
|
||||
${descuento > 0 ? `<tr><td class="muted">Descuento</td><td class="right" style="color:#da1e28;">-${formatMonto(descuento)}</td></tr>` : ''}
|
||||
<tr><td class="muted">IVA (21%)</td><td>${impuestos}</td></tr>
|
||||
<tr class="total-row"><td>Total</td><td class="right">${total}</td></tr>
|
||||
${saldo > 0 ? `<tr class="saldo-row"><td>Saldo a pagar</td><td class="right">${formatMonto(saldo)}</td></tr>` : ''}
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section-title">💳 Pagos realizados</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fecha</th>
|
||||
<th>Forma de pago</th>
|
||||
<th class="right">Importe</th>
|
||||
<th>Observación</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${pagosHtml}</tbody>
|
||||
</table>
|
||||
|
||||
<p style="margin:32px 0 0;padding-top:16px;border-top:1px solid #e0e0e0;font-size:12px;color:#525252;text-align:center;">
|
||||
Gracias por elegirnos. Si tenés consultas sobre esta factura, respondé a este correo.
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
async function enviarEmail() {
|
||||
if (!comprobante) return;
|
||||
enviandoEmail = true;
|
||||
const res = await enviarEmailComprobante(fetch, comprobante.ID);
|
||||
enviandoEmail = false;
|
||||
if (res && typeof res === 'object' && !(res as any).error) {
|
||||
info = 'Email enviado al cliente correctamente.';
|
||||
void onEmailEnviado?.();
|
||||
} else {
|
||||
error = typeof res === 'string' ? res : 'no se pudo enviar el email';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal bind:open={open} modalHeading={`Comprobante ${comprobante?.numero ?? ''}`} passiveModal>
|
||||
{#if cargando}
|
||||
<div class="p-6 flex flex-col items-center justify-center gap-3">
|
||||
<p class="text-gray-500 text-sm">Cargando comprobante…</p>
|
||||
</div>
|
||||
{:else if comprobante}
|
||||
<div class="space-y-5 max-w-3xl">
|
||||
<!-- Encabezado del comprobante -->
|
||||
<div class="bg-gradient-to-r from-blue-600 to-blue-800 text-white p-6 rounded-xl shadow-sm">
|
||||
<p class="text-xs uppercase tracking-wider text-blue-100 opacity-90 mb-1">Repuestera</p>
|
||||
<h2 class="text-xl font-bold mb-1">Comprobante de venta</h2>
|
||||
<p class="text-sm text-blue-100 opacity-95">Factura <strong>{comprobante.numero ?? `F-${comprobante.ID}`}</strong></p>
|
||||
</div>
|
||||
|
||||
<!-- Datos del cliente en tarjetas -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
|
||||
<p class="text-xs text-gray-500 uppercase font-semibold mb-1">Cliente</p>
|
||||
<p class="text-base font-medium">{comprobante.cliente?.nombre ?? '-'}</p>
|
||||
</div>
|
||||
<div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
|
||||
<p class="text-xs text-gray-500 uppercase font-semibold mb-1">CUIT</p>
|
||||
<p class="text-base font-mono font-medium">{comprobante.cliente?.cuit ?? '-'}</p>
|
||||
</div>
|
||||
<div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
|
||||
<p class="text-xs text-gray-500 uppercase font-semibold mb-1">Fecha</p>
|
||||
<p class="text-base font-medium">{formatFecha(comprobante.FechaEmision)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div class="flex-1 bg-gray-50 border border-gray-200 rounded-lg p-4">
|
||||
<p class="text-xs text-gray-500 uppercase font-semibold mb-1">Estado</p>
|
||||
<Tag type={estadoTagKind(comprobante.estado)} class="mt-1">
|
||||
{comprobante.estado}
|
||||
</Tag>
|
||||
</div>
|
||||
<div class="flex-1 bg-gray-50 border border-gray-200 rounded-lg p-4 text-right">
|
||||
<p class="text-xs text-gray-500 uppercase font-semibold mb-1">Total</p>
|
||||
<p class="text-lg font-bold text-blue-700">{formatMonto(comprobante.total)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if (comprobante.saldo ?? 0) > 0}
|
||||
<div class="bg-amber-50 border border-amber-200 rounded-lg p-4">
|
||||
<p class="text-xs text-amber-600 uppercase font-semibold mb-1">Saldo a pagar</p>
|
||||
<p class="text-base font-bold text-amber-700">{formatMonto(comprobante.saldo)}</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Ítems usando Carbon Table -->
|
||||
{#if comprobante.detalles && comprobante.detalles.length > 0}
|
||||
<TableContainer title="Ítems">
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Repuesto</TableHeader>
|
||||
<TableHeader>Cant.</TableHeader>
|
||||
<TableHeader>Precio unit.</TableHeader>
|
||||
<TableHeader>Subtotal</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#each comprobante.detalles as d}
|
||||
<TableRow>
|
||||
<TableCell>{nombreRepuesto(d)}</TableCell>
|
||||
<TableCell class="text-right">{d.cantidad}</TableCell>
|
||||
<TableCell class="text-right">{formatMonto(d.precioUnitario)}</TableCell>
|
||||
<TableCell class="text-right font-medium">{formatMonto(d.subtotal)}</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
{/if}
|
||||
|
||||
<!-- Resumen de importe -->
|
||||
<div class="bg-gray-50 border border-gray-200 rounded-lg p-5">
|
||||
<p class="text-xs uppercase tracking-wider text-gray-500 font-semibold mb-3 flex items-center gap-1">💰 Resumen de importe</p>
|
||||
<table class="w-full text-sm">
|
||||
<tbody>
|
||||
<tr class="border-b border-gray-200">
|
||||
<td class="py-2 text-gray-500">Subtotal</td>
|
||||
<td class="py-2 text-right">{formatMonto(comprobante.subtotal ?? 0)}</td>
|
||||
</tr>
|
||||
{#if (comprobante.descuentoTotal ?? 0) > 0}
|
||||
<tr class="border-b border-gray-200">
|
||||
<td class="py-2 text-gray-500">Descuento</td>
|
||||
<td class="py-2 text-right" style="color:#da1e28;">-{formatMonto(comprobante.descuentoTotal)}</td>
|
||||
</tr>
|
||||
{/if}
|
||||
<tr class="border-b border-gray-200">
|
||||
<td class="py-2 text-gray-500">IVA (21%)</td>
|
||||
<td class="py-2 text-right">{formatMonto(comprobante.impuestos ?? 0)}</td>
|
||||
</tr>
|
||||
<tr class="font-bold border-t border-gray-300 pt-2">
|
||||
<td class="py-2">Total</td>
|
||||
<td class="py-2 text-right text-blue-700">{formatMonto(comprobante.total)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Pagos realizados usando Carbon Table -->
|
||||
<div class="space-y-2">
|
||||
<p class="text-xs uppercase tracking-wider text-gray-500 font-semibold">💳 Pagos realizados</p>
|
||||
{#if pagos.length > 0}
|
||||
<TableContainer>
|
||||
<Table size="compact">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeader>Fecha</TableHeader>
|
||||
<TableHeader>Forma de pago</TableHeader>
|
||||
<TableHeader>Importe</TableHeader>
|
||||
<TableHeader>Observación</TableHeader>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{#each pagos as p}
|
||||
<TableRow>
|
||||
<TableCell>{formatFechaHora(p.fecha)}</TableCell>
|
||||
<TableCell>{p.formaDePago ?? '-'}</TableCell>
|
||||
<TableCell class="text-right font-medium">{formatMonto(p.importe)}</TableCell>
|
||||
<TableCell class="text-gray-500">{p.observacion ?? '-'}</TableCell>
|
||||
</TableRow>
|
||||
{/each}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
{:else}
|
||||
<div class="bg-gray-50 border border-gray-200 rounded-lg p-4 text-center">
|
||||
<p class="text-sm text-gray-500">Sin pagos registrados.</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Botones de acción -->
|
||||
<div class="mt-6 flex flex-wrap gap-3 no-print">
|
||||
<Button kind="ghost" icon={Download} onclick={descargarComprobante} size="small">
|
||||
Descargar comprobante
|
||||
</Button>
|
||||
{#if comprobante.cliente?.email}
|
||||
<Button
|
||||
kind="ghost"
|
||||
icon={Email}
|
||||
disabled={enviandoEmail}
|
||||
onclick={enviarEmail}
|
||||
size="small"
|
||||
>
|
||||
{enviandoEmail ? 'Enviando…' : 'Enviar email al cliente'}
|
||||
</Button>
|
||||
{:else}
|
||||
<Button kind="ghost" icon={Email} disabled size="small">
|
||||
Cliente sin email
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton class="mt-4" />
|
||||
{/if}
|
||||
{#if info}
|
||||
<InlineNotification kind="success" title="Enviado" subtitle={info} hideCloseButton class="mt-4" />
|
||||
{/if}
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="p-6 flex flex-col items-center justify-center gap-2">
|
||||
<InlineNotification kind="error" title="Error" subtitle={error} hideCloseButton />
|
||||
</div>
|
||||
{:else}
|
||||
<div class="p-6 flex flex-col items-center justify-center gap-2 text-gray-500">
|
||||
<p>Seleccioná una factura para ver su comprobante.</p>
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
<style>
|
||||
.no-print {
|
||||
display: flex;
|
||||
}
|
||||
</style>
|
||||
Vendored
+40
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user