### Interact with Conversational AI Tax Assistant (TypeScript) Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt This function enables users to chat with an AI tax assistant for real-time Spanish tax advice. It manages chat history and sends new messages to a 'geminiService' for processing. It also includes an example of generating a context-aware prompt for tax-related queries. ```typescript import { sendChatMessage } from './services/geminiService'; // Send message to AI tax assistant const chatWithAssistant = async () => { const history = [ { role: 'user', parts: [{ text: '¿Puedo deducir los gastos de comidas con clientes?' }] }, { role: 'model', parts: [{ text: 'En España, los gastos de manutención con clientes son deducibles al 100% si están debidamente justificados.' }] } ]; const newMessage = '¿Qué documentación necesito guardar?'; try { const response = await sendChatMessage(history, newMessage); console.log(response); // Output: "Debes conservar: 1) La factura del restaurante (ticket válido con NIF), // 2) Justificación de la reunión (agenda, email, notas), 3) Identificación del cliente // invitado. Todo esto durante al menos 4 años por si Hacienda requiere inspección." // Add to chat history setMessages(prev => [ ...prev, { role: 'user', text: newMessage, timestamp: new Date() }, { role: 'model', text: response, timestamp: new Date() } ]); } catch (error) { console.error('Chat error:', error); } }; // Example: Context-aware tax question from Tax Models view const askAboutModel303 = () => { const ivaDevengado = 5250.00; const ivaSoportado = 1150.50; const result = ivaDevengado - ivaSoportado; const prompt = `Explícame cómo rellenar el Modelo 303 (IVA) con mis datos: - IVA Devengado: ${ivaDevengado}€ - IVA Soportado: ${ivaSoportado}€ - Resultado: ${result}€ ¿En qué casillas debo poner estos importes?`; sendChatMessage([], prompt); }; ``` -------------------------------- ### Generate Professional Invoice PDF (TypeScript) Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt Generates a legally compliant invoice PDF with professional formatting for the Spanish market. It takes invoice details and professional profile information as input. The PDF includes a header with lawyer credentials, client/invoice details, itemized services, tax calculations (IVA, IRPF), payment instructions, and a legal footer. Errors during generation are logged and an alert is shown to the user. ```typescript import { generateInvoicePDF } from './services/pdfGenerator'; import { Invoice, ProfessionalProfile } from './types'; // Generate PDF invoice const createInvoicePDF = () => { const invoice: Partial = { number: 'A-25-001', date: '2025-01-15', entityName: 'Construcciones García S.L.', nif: 'B87654321', fiscalAddress: 'Polígono Industrial Norte, Nave 5, Zaragoza', concept: 'Asesoramiento jurídico para contrato de arrendamiento comercial', fees: 800, taxableExpenses: 200, supplies: 50, baseAmount: 1000, ivaRate: 21, ivaAmount: 210, irpfRate: 15, irpfAmount: 150, totalAmount: 1110, retainer: 500 }; const profile: ProfessionalProfile = { name: 'Antonio José Muñoz González', nif: '25143721Y', address: 'Avenida de San José 173, Cuarto', city: 'Zaragoza', zipCode: '50007', province: 'Zaragoza', barAssociation: 'Ilustre Colegio de Abogados de Zaragoza', collegiateNumber: '4337', phone: '+34 976 123 456', email: 'antonio.munoz@abogado.es', website: 'www.munozabogados.es', iban: 'ES91 2100 0418 4502 0012 3456' }; try { // Generates and downloads PDF with: // - Professional header with lawyer credentials // - Client/invoice details // - Itemized services (fees, expenses, supplies) // - Tax calculations (IVA, IRPF) // - Payment instructions (IBAN) // - Legal footer (GDPR notice) generateInvoicePDF(invoice, profile); // File saved as: Factura_A-25-001.pdf } catch (error) { console.error('PDF generation error:', error); alert('Error al generar el PDF'); } }; ``` -------------------------------- ### Generate Fiscal Year Closing Report (TypeScript) Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt Generates a comprehensive fiscal year closing report. This report includes an income versus expense summary, VAT liquidation (303/390), IRPF calculations (130), and withholdings breakdown (111/190). It requires the fiscal year, a list of invoices, and the professional's profile information as input. The generated file is named based on the fiscal year. ```typescript // Generate fiscal year closing report import { generateFiscalYearReport } from './services/pdfGenerator'; const createYearEndReport = (year: number, invoices: Invoice[], profile: ProfessionalProfile) => { generateFiscalYearReport(year, invoices, profile); // Creates comprehensive report with: // - Income vs Expense summary // - VAT liquidation (303/390) // - IRPF calculations (130) // - Withholdings breakdown (111/190) // File saved as: Cierre_Fiscal_2024.pdf }; ``` -------------------------------- ### Project JavaScript Module Imports Source: https://github.com/antoniojm-netizen/gestion-fiscal-abogados/blob/main/index.html This JSON object lists all the external JavaScript modules imported into the AbogadoGestor AI project, along with their specific CDN URLs. This allows for easy dependency management and ensures correct versions are loaded. Libraries include React, Google GenAI, Lucide React, Recharts, jsPDF, PapaParse, and XLSX. ```json { "imports": { "react/": "https://aistudiocdn.com/react@^19.2.0/", "react": "https://aistudiocdn.com/react@^19.2.0", "@google/genai": "https://aistudiocdn.com/@google/genai@^1.30.0", "lucide-react": "https://aistudiocdn.com/lucide-react@^0.554.0", "recharts": "https://aistudiocdn.com/recharts@^3.4.1", "react-dom/": "https://aistudiocdn.com/react-dom@^19.2.0/", "jspdf": "https://aistudiocdn.com/jspdf@^2.5.1", "jspdf-autotable": "https://aistudiocdn.com/jspdf-autotable@^3.8.2", "papaparse": "https://aistudiocdn.com/papaparse@5.4.1", "xlsx": "https://aistudiocdn.com/xlsx@0.18.5" } } ``` -------------------------------- ### Import Invoices from CSV/Excel (TypeScript) Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt This function handles the bulk import of invoices from CSV or Excel files. It utilizes a 'parseFile' service to process the spreadsheet and automatically maps fields. The function takes a File object and an InvoiceType as input, and it validates the imported data before adding it to the system. Error handling and user confirmation are included. ```typescript import { parseFile } from './services/importService'; import { InvoiceType } from './types'; // Import invoices from CSV or Excel file const handleBulkImport = async (file: File, type: InvoiceType) => { try { const importedInvoices = await parseFile(file, type); console.log(`Imported ${importedInvoices.length} invoices`); // Each invoice object contains: // - number, date, nif, entityName, fiscalAddress // - concept, category, baseAmount, ivaRate, irpfRate // - totalAmount, deductible (for expenses) // Validate and add to system if (importedInvoices.length > 0) { const confirmed = window.confirm( `Se encontraron ${importedInvoices.length} facturas. ¿Importar?` ); if (confirmed) { setInvoices(prev => [...prev, ...importedInvoices]); alert('✅ Importación completada'); } } else { alert('No se encontraron facturas válidas en el archivo'); } } catch (error) { console.error('Import error:', error); alert(`Error al importar: ${error.message}`); } }; // Expected CSV/Excel columns (flexible mapping): // - Número, Fecha, NIF, Nombre, Domicilio // - Concepto, Categoría, Base, IVA %, IRPF %, Total // - Deducible (for expenses) // - Nº Factura Proveedor, Fecha Registro (for expenses) // Example usage { const file = e.target.files?.[0]; if (file) { handleBulkImport(file, InvoiceType.INCOME); } }} /> ``` -------------------------------- ### AI Expense Deductibility Analysis with TypeScript Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt Analyzes business expenses to determine tax deductibility based on Spanish fiscal laws using AI. This function takes the expense concept and amount as input and returns an analysis object detailing deductibility, reasons, and suggested tax categories and rates. It helps in accurately classifying expenses for tax purposes. ```typescript import { analyzeExpenseDeductibility } from './services/geminiService'; // Analyze if an expense is tax-deductible const analyzeExpense = async () => { const concept = "Microsoft Office 365 subscription"; const amount = 99.99; try { const analysis = await analyzeExpenseDeductibility(concept, amount); console.log(analysis); // Output: { // deductible: true, // reason: "Software de ofimática necesario para gestión del despacho profesional", // suggestedIrpfExpenseType: "Otros servicios exteriores", // suggestedIvaExpenseType: "Operaciones Interiores Corrientes", // suggestedIvaRate: 21, // suggestedIrpfRate: 0 // } // Update invoice form with AI suggestions setFormData(prev => ({ ...prev, deductible: analysis.deductible, category: analysis.suggestedIrpfExpenseType, ivaRate: analysis.suggestedIvaRate, irpfRate: analysis.suggestedIrpfRate, irpfExpenseType: analysis.suggestedIrpfExpenseType, ivaExpenseType: analysis.suggestedIvaExpenseType })); // Display explanation to user alert(`${analysis.deductible ? 'Deducible' : 'No Deducible'}\n${analysis.reason}`); } catch (error) { console.error('Error analyzing expense:', error); } }; ``` -------------------------------- ### AI Invoice Data Extraction with TypeScript Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt Extracts structured invoice data from PDF or image files using Google Gemini AI. This function takes a File object as input and returns an object containing extracted invoice details such as number, date, entity name, NIF, amounts, and tax rates. It's designed to be integrated with file upload or drag-and-drop interfaces. ```typescript import { extractInvoiceData } from './services/geminiService'; // Extract invoice data from uploaded file const handleFileUpload = async (file: File) => { try { const extractedData = await extractInvoiceData(file); console.log(extractedData); // Output: { // number: "FAC-2024-001", // date: "2024-03-15", // entityName: "Acme Corporation", // nif: "B12345678", // fiscalAddress: "Calle Mayor 123, Madrid", // concept: "Legal consulting services", // baseAmount: 1000, // ivaRate: 21, // irpfRate: 15, // totalAmount: 1060, // deductible: true, // inferredIrpfExpenseType: "Servicios de profesionales independientes", // inferredIvaExpenseType: "Operaciones Interiores Corrientes", // suggestedContext: "OTHER" // } // Apply to form setFormData({ ...formData, ...extractedData, baseAmount: extractedData.baseAmount, ivaRate: extractedData.ivaRate || 21, irpfRate: extractedData.irpfRate || 0 }); } catch (error) { console.error('Error extracting invoice data:', error); } }; // Use with drag-and-drop
{ e.preventDefault(); const file = e.dataTransfer.files[0]; if (file && (file.type.startsWith('image/') || file.type === 'application/pdf')) { handleFileUpload(file); } }} onDragOver={(e) => e.preventDefault()} > Drop invoice PDF or image here
``` -------------------------------- ### Export Invoices to Excel in TypeScript Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt This function exports invoice data to an Excel file using an HTML table. It constructs an HTML table with invoice data, and triggers a download. The function sets the file name using the current date and sets the correct MIME type for Excel. ```typescript // Export filtered invoices to Excel const exportToXLS = (invoices: Invoice[]) => { const tableHTML = ` ${invoices.map(inv => ` `).join('')}
FechaTipoNúmeroNIF NombreConceptoBase IVA %Cuota IVAIRPF % Cuota IRPFTotalDeducible
${new Date(inv.date).toLocaleDateString('es-ES')} ${inv.type} ${inv.number} ${inv.nif} ${inv.entityName} ${inv.concept} ${inv.baseAmount.toFixed(2)} ${inv.ivaRate} ${inv.ivaAmount.toFixed(2)} ${inv.irpfRate} ${inv.irpfAmount.toFixed(2)} ${inv.totalAmount.toFixed(2)} ${inv.deductible ? 'SI' : 'NO'}
`; const blob = new Blob([tableHTML], { type: 'application/vnd.ms-excel' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `Libro_Registro_${new Date().toISOString().slice(0,10)}.xls`; document.body.appendChild(link); link.click(); document.body.removeChild(link); }; ``` -------------------------------- ### AI-Powered Invoice Data Extraction API Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt This API endpoint leverages Google Gemini AI to extract structured data from invoice documents (PDF or images). It processes uploaded files and returns key invoice details such as number, date, entity, amounts, and tax information. ```APIDOC ## POST /api/invoices/extract ### Description Extracts structured invoice data from PDF or image files using Google Gemini AI with multimodal capabilities. ### Method POST ### Endpoint /api/invoices/extract ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (File) - Required - The invoice document (PDF or image) to process. ### Request Example ```json { "file": "" } ``` ### Response #### Success Response (200) - **number** (string) - The invoice number. - **date** (string) - The invoice date (YYYY-MM-DD). - **entityName** (string) - The name of the issuing or receiving entity. - **nif** (string) - The NIF/CIF of the entity. - **fiscalAddress** (string) - The fiscal address of the entity. - **concept** (string) - Description of the services or goods. - **baseAmount** (number) - The base amount of the invoice before taxes. - **ivaRate** (number) - The VAT rate applied (e.g., 21). - **irpfRate** (number) - The IRPF rate applied (e.g., 15). - **totalAmount** (number) - The total amount of the invoice, including taxes. - **deductible** (boolean) - Indicates if the expense is potentially tax-deductible. - **inferredIrpfExpenseType** (string) - AI-inferred category for IRPF expenses. - **inferredIvaExpenseType** (string) - AI-inferred category for VAT expenses. - **suggestedContext** (string) - AI-suggested context for the invoice (e.g., "OTHER"). #### Response Example ```json { "number": "FAC-2024-001", "date": "2024-03-15", "entityName": "Acme Corporation", "nif": "B12345678", "fiscalAddress": "Calle Mayor 123, Madrid", "concept": "Legal consulting services", "baseAmount": 1000, "ivaRate": 21, "irpfRate": 15, "totalAmount": 1060, "deductible": true, "inferredIrpfExpenseType": "Servicios de profesionales independientes", "inferredIvaExpenseType": "Operaciones Interiores Corrientes", "suggestedContext": "OTHER" } ``` ``` -------------------------------- ### Expense Deductibility Analysis API Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt This API endpoint uses AI to analyze business expenses based on Spanish fiscal rules, determining their tax deductibility. It suggests appropriate expense categories and tax rates for IRPF and IVA. ```APIDOC ## POST /api/expenses/analyze-deductibility ### Description Analyzes business expenses to determine tax deductibility using AI-powered fiscal rules for Spanish law. ### Method POST ### Endpoint /api/expenses/analyze-deductibility ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **concept** (string) - Required - The description or concept of the expense. - **amount** (number) - Required - The monetary amount of the expense. ### Request Example ```json { "concept": "Microsoft Office 365 subscription", "amount": 99.99 } ``` ### Response #### Success Response (200) - **deductible** (boolean) - Indicates if the expense is tax-deductible. - **reason** (string) - Explanation for the deductibility decision. - **suggestedIrpfExpenseType** (string) - AI-suggested category for IRPF expenses. - **suggestedIvaExpenseType** (string) - AI-suggested category for VAT expenses. - **suggestedIvaRate** (number) - AI-suggested VAT rate (e.g., 21). - **suggestedIrpfRate** (number) - AI-suggested IRPF rate (e.g., 0). #### Response Example ```json { "deductible": true, "reason": "Software de ofimática necesario para gestión del despacho profesional", "suggestedIrpfExpenseType": "Otros servicios exteriores", "suggestedIvaExpenseType": "Operaciones Interiores Corrientes", "suggestedIvaRate": 21, "suggestedIrpfRate": 0 } ``` ``` -------------------------------- ### Export Invoices to CSV in TypeScript Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt This function exports an array of invoice objects to a CSV file. It formats the data, including handling of special characters, and initiates a download in the user's browser. The function adds a Byte Order Mark (BOM) for compatibility with Excel and sets the file name using the current date. ```typescript // Export filtered invoices to CSV const exportToCSV = (invoices: Invoice[]) => { const headers = [ "ID", "Fecha Factura", "Tipo", "Número", "NIF", "Nombre", "Concepto", "Categoría", "Base Imponible", "IVA %", "Cuota IVA", "IRPF %", "Cuota IRPF", "Total", "Deducible" ]; const rows = invoices.map(inv => [ inv.id, new Date(inv.date).toLocaleDateString('es-ES'), inv.type, inv.number, inv.nif, inv.entityName, inv.concept, inv.category || '', inv.baseAmount.toFixed(2), inv.ivaRate, inv.ivaAmount.toFixed(2), inv.irpfRate, inv.irpfAmount.toFixed(2), inv.totalAmount.toFixed(2), inv.deductible ? 'SI' : 'NO' ].map(cell => { const str = String(cell); return str.includes(',') ? `"${str.replace(/"/g, '""')}"` : str; }).join(',')); const csvContent = [headers.join(','), ...rows].join('\n'); // Add BOM for Excel UTF-8 compatibility const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `Libro_Registro_${new Date().toISOString().slice(0,10)}.csv`; document.body.appendChild(link); link.click(); document.body.removeChild(link); }; ``` -------------------------------- ### Set Application Font Family Source: https://github.com/antoniojm-netizen/gestion-fiscal-abogados/blob/main/index.html This CSS rule sets the primary font family for the application to 'Inter', with a fallback to generic `sans-serif`. This ensures a consistent typography across the application. It requires the 'Inter' font to be available in the project or loaded via external resources. ```css body { font-family: 'Inter', sans-serif; } ``` -------------------------------- ### Audit Invoices for Compliance Issues (TypeScript) Source: https://context7.com/antoniojm-netizen/gestion-fiscal-abogados/llms.txt This function audits invoice records for duplicates, gaps, and inconsistencies using a service like Gemini AI. It takes an array of Invoice objects as input and outputs audit results, including severity levels and messages for any detected issues. It depends on a 'geminiService' for the audit logic and 'types' for the Invoice structure. ```typescript import { auditInvoices } from './services/geminiService'; import { Invoice } from './types'; // Audit all invoices for compliance issues const runComplianceAudit = async (invoices: Invoice[]) => { try { const auditResults = await auditInvoices(invoices); console.log(auditResults); // Output: { // alerts: [ // { // invoiceId: "inv-001", // severity: "HIGH", // message: "Número de factura duplicado: A-24-015 aparece 2 veces" // }, // { // invoiceId: "inv-045", // severity: "MEDIUM", // message: "Salto en numeración: Falta A-24-022 en la secuencia" // }, // { // invoiceId: "inv-078", // severity: "LOW", // message: "NIF del cliente no valida con algoritmo MOD-23" // } // ] // } // Display audit alerts to user if (auditResults.alerts.length > 0) { setAuditResults(auditResults.alerts); } else { alert('✅ Auditoría completada: No se detectaron errores'); } } catch (error) { console.error('Audit error:', error); } }; ``` -------------------------------- ### Apply Light Mode Scheme to Browser Native Elements Source: https://github.com/antoniojm-netizen/gestion-fiscal-abogados/blob/main/index.html This CSS rule forces browser native elements such as inputs and scrollbars to remain in light mode, overriding system preferences. It uses the `color-scheme` property, which is supported by modern browsers. This is useful for maintaining a consistent UI regardless of the user's system theme. ```css :root { color-scheme: light; } ``` -------------------------------- ### Configure Tailwind CSS Dark Mode (Manual) Source: https://github.com/antoniojm-netizen/gestion-fiscal-abogados/blob/main/index.html This snippet shows how to configure Tailwind CSS to use class-based dark mode manually. This effectively disables system auto-dark mode, forcing the application to adhere to the 'class' mode setting. No external dependencies are required beyond Tailwind CSS itself. ```javascript tailwind.config = { darkMode: 'class', } ``` -------------------------------- ### Hide Scrollbar for Chat Elements (Webkit/IE/FF) Source: https://github.com/antoniojm-netizen/gestion-fiscal-abogados/blob/main/index.html These CSS rules provide a way to hide the scrollbar for elements intended for chat interfaces. The first rule targets Webkit browsers (`::-webkit-scrollbar`) by setting `display: none`. The second rule targets Internet Explorer and Firefox (`-ms-overflow-style`, `scrollbar-width`) to achieve the same effect. This enhances the visual appearance of chat components by removing default scrollbars. ```css .scrollbar-hide::-webkit-scrollbar { display: none; } .scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.