arreglado tema de los nombres de repuestos y cocinado el tema de la

descarga de estos

Signed-off-by: fede <federico.nicolas.polidoro@gmail.com>
This commit is contained in:
fede committed 2026-12-02 00:54:10 -03:00
1 parent b6b2e7d465
commit 94a4e292c4
13 files changed
+290 -33

No files matched your search

@@ -40,6 +40,7 @@ export interface ComprobanteResponse {
};
detalles?: Array<{
repuestoId: number;
repuestoNombre?: string;
cantidad: number;
precioUnitario: number;
subtotal: number;
+165
View File
@@ -0,0 +1,165 @@
const PROPS_COLOR = [
'color',
'background-color',
'background-image',
'border-top-color',
'border-right-color',
'border-bottom-color',
'border-left-color',
'outline-color',
'text-decoration-color',
'fill',
'stroke',
'box-shadow'
];
const COLOR_MODERNO = /\b(?:oklab|oklch|lab|lch|color-mix|color)\((?:[^()]|\([^()]*\))*\)/g;
const INTERPOLACION =
/\s+in\s+(?:oklab|oklch|srgb|lab|lch|hsl|hwb)(?:\s+(?:shorter|longer|increasing|decreasing)\s+hue)?/g;
const DETECTAR = /oklab|oklch|\blab\(|\blch\(|\bcolor\(|color-mix/;
// CSS que se inyecta solo en el clon del DOM: fuerza tema claro con outline
const CSS_CLARO = `
.comprobante-print {
background: #fff !important;
color: #161616 !important;
border: 1px solid #8d8d8d !important;
}
/* Contenedores, tablas y celdas de Carbon */
.comprobante-print [class*="data-table"],
.comprobante-print table,
.comprobante-print thead,
.comprobante-print tbody,
.comprobante-print tr,
.comprobante-print td {
background: #fff !important;
color: #161616 !important;
border-color: #c6c6c6 !important;
}
.comprobante-print table {
border: 1px solid #8d8d8d !important;
border-collapse: collapse !important;
}
.comprobante-print th {
background: #f4f4f4 !important;
color: #161616 !important;
border-bottom: 1px solid #8d8d8d !important;
}
.comprobante-print td {
border-bottom: 1px solid #c6c6c6 !important;
}
/* Colores de énfasis */
.comprobante-print td.text-blue-700 { color: #1d4ed8 !important; }
.comprobante-print td.text-amber-700 { color: #b45309 !important; }
.comprobante-print td[style*="da1e28"] { color: #da1e28 !important; }
`;
const cache = new Map<string, string>();
let ctx: CanvasRenderingContext2D | null = null;
// Convierte un color CSS moderno (oklab, oklch, etc.) a rgba() usando un canvas de 1x1
function aRgb(color: string): string {
const hit = cache.get(color);
if (hit) return hit;
if (!ctx) {
const c = document.createElement('canvas');
c.width = c.height = 1;
ctx = c.getContext('2d', { willReadFrequently: true });
}
if (!ctx) return color;
ctx.clearRect(0, 0, 1, 1);
ctx.fillStyle = '#000';
ctx.fillStyle = color;
ctx.fillRect(0, 0, 1, 1);
const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
const rgb = `rgba(${r}, ${g}, ${b}, ${+(a / 255).toFixed(3)})`;
cache.set(color, rgb);
return rgb;
}
// Reescribe en el clon los estilos computados que usen colores modernos
function normalizarColores(raiz: HTMLElement) {
const win = raiz.ownerDocument.defaultView;
if (!win) return;
const elementos = [raiz, ...raiz.querySelectorAll<HTMLElement>('*')];
for (const el of elementos) {
const cs = win.getComputedStyle(el);
for (const prop of PROPS_COLOR) {
const valor = cs.getPropertyValue(prop);
if (!valor || !DETECTAR.test(valor)) continue;
el.style.setProperty(
prop,
valor.replace(INTERPOLACION, '').replace(COLOR_MODERNO, aRgb),
'important'
);
}
}
}
type OpcionesPdf = {
/** Texto de la pill de estado. Reemplaza al <Tag> de Carbon en el PDF. */
estado?: string;
};
// Reemplaza el marcador [data-pdf-estado] por una pill simple con el texto recibido
function reemplazarEstado(raiz: HTMLElement, estado?: string) {
const marcador = raiz.querySelector<HTMLElement>('[data-pdf-estado]');
if (!marcador) return;
const pill = raiz.ownerDocument.createElement('span');
pill.textContent = estado ?? '-';
pill.style.cssText = [
'display:inline-block',
'padding:3px 12px',
'border:1px solid #161616',
'border-radius:12px',
'background:#fff',
'color:#161616',
'font-size:12px',
'font-weight:600',
'line-height:1.2',
'white-space:nowrap'
].join(';');
marcador.replaceChildren(pill);
}
export async function htmlAPdf(el: HTMLElement, filename: string, opciones: OpcionesPdf = {}) {
const mod = await import('html2pdf.js');
const html2pdf = (mod as any).default ?? mod;
await html2pdf()
.set({
margin: 10,
filename,
image: { type: 'jpeg', quality: 0.95 },
html2canvas: {
scale: 1.5,
useCORS: true,
backgroundColor: '#ffffff',
onclone: (doc: Document, clon?: HTMLElement) => {
// 1) tema claro + outline
const style = doc.createElement('style');
style.textContent = CSS_CLARO;
doc.head.appendChild(style);
const raiz = clon ?? (doc.querySelector('.comprobante-print') as HTMLElement);
// 2) pill de estado con el texto pasado por parámetro
reemplazarEstado(raiz, opciones.estado);
// 3) convertir colores oklab/oklch a rgb para que html2canvas los entienda
normalizarColores(raiz);
}
},
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
})
.from(el)
.save();
}
@@ -15,6 +15,7 @@
import { Download, Email, Inspection } from 'carbon-icons-svelte';
import { obtenerComprobante, enviarEmailComprobante } from '$lib/hooks/facturas/comprobante';
import type { ComprobanteResponse, PagoResumen } from '../../types';
import { htmlAPdf } from '$lib/utils/pdf';
let { open = $bindable(false), facturaId = 0, onEmailEnviado = () => {} } = $props();
@@ -25,6 +26,8 @@
let error = $state('');
let info = $state('');
let contenedor: HTMLElement | null = $state(null);
function formatFecha(iso?: string): string {
if (!iso) return '-';
try {
@@ -69,8 +72,6 @@
}
}
$effect(() => {
if (!open) {
comprobante = null;
@@ -100,23 +101,6 @@
}
});
function descargarComprobante() {
if (!comprobante) return;
window.print();
}
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>
@@ -125,7 +109,7 @@
<p class="text-gray-500 text-sm">Cargando comprobante…</p>
</div>
{:else if comprobante}
<div class="comprobante-print space-y-6 max-w-3xl bg-white/10 border border-blue-200/20 p-1">
<div bind:this={contenedor} class="comprobante-print space-y-6 max-w-3xl bg-white/10 border border-blue-200/20 p-1">
<!-- Encabezado del comprobante -->
<div class="p-6 bg-linear-to-r from-blue-600/90 to-blue-800/90 text-white shadow-sm print:shadow-none">
<p class="text-xs uppercase tracking-wider text-blue-100 opacity-90 mb-1">Repuestera</p>
@@ -158,9 +142,11 @@
<TableRow>
<TableCell>Estado</TableCell>
<TableCell>
<Tag type={estadoTagKind(comprobante.estado)}>
{comprobante.estado}
</Tag>
<span data-pdf-estado>
<Tag type={estadoTagKind(comprobante.estado)}>
{comprobante.estado}
</Tag>
</span>
</TableCell>
</TableRow>
<TableRow>
@@ -193,10 +179,10 @@
<TableHeader>Subtotal</TableHeader>
</TableRow>
</TableHead>
<TableBody>{$inspect(comprobante)}
<TableBody>
{#each comprobante.detalles as d}
<TableRow>
<TableCell>{`Repuesto ${d.repuestoId}`}</TableCell>
<TableCell>{d.repuestoNombre ?? `Repuesto ${d.repuestoId}`}</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>
@@ -278,16 +264,39 @@
</div>
<!-- Botones de acción (ocultos al imprimir) -->
<div class="mt-6 flex flex-wrap gap-3 no-print">
<Button kind="ghost" icon={Download} onclick={descargarComprobante} size="small">
Descargar comprobante
</Button>
<div class="mt-6 flex flex-wrap gap-3 no-print" data-html2canvas-ignore="true">
<Button
kind="ghost"
icon={Download}
size="small"
onclick={async () => {
if (!contenedor || !comprobante) return;
await htmlAPdf(
contenedor,
`comprobante-${comprobante.numero ?? comprobante.ID}.pdf`,
{ estado: comprobante.estado }
);
}}
>
Descargar comprobante
</Button>
{#if comprobante.cliente?.email}
<Button
kind="ghost"
icon={Email}
disabled={enviandoEmail}
onclick={enviarEmail}
onclick={async () => {
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';
}
}}
size="small"
>
{enviandoEmail ? 'Enviando…' : 'Enviar email al cliente'}
+1
View File
@@ -300,6 +300,7 @@ export interface Proveedor {
export interface FacturaDetalle {
repuestoId: number;
repuestoNombre?: string;
cantidad: number;
descuentoId?: number;
descuento?: number;