### Configure SOAP Client for AEAT Communication in JavaScript Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Configures a singleton SOAP client for secure communication with the AEAT web service, utilizing mutual TLS authentication. It reads necessary certificates and passwords from mounted secret files. This example shows how to obtain the client and use it for invoice registration. ```javascript // apps/api/soap-client.js import { getClient, registerInvoice, queryInvoice } from './apps/api/soap-client.js'; // Environment variables required // AEAT_CERT_PATH=/var/secrets/aeat_cert/cert.p12 // AEAT_CERT_PASS_PATH=/var/secrets/aeat_pass/cert_pass.txt // AEAT_WSDL_FILE=/var/secrets/aeat_wsdl/wsdl_url.txt // Get configured SOAP client async function example() { try { const client = await getClient(); console.log('SOAP client ready:', client.describe()); // Register an invoice const invoice = { id: "INV-001", number: "F-001", issueDate: "2025-01-15", total: 1000, tax: { rate: 21, amount: 210 }, customer: { name: "Client", nif: "B12345678" }, issuer: { name: "Company", nif: "A87654321" } }; const result = await registerInvoice(invoice); console.log('Registration result:', result); } catch (error) { console.error('SOAP client error:', error.message); } } ``` -------------------------------- ### GET /api/verifactu/ops Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Retrieves service configuration and available SOAP operations. Useful for validating certificates, passwords, and WSDL files. ```APIDOC ## GET /api/verifactu/ops ### Description Retrieves service configuration and available SOAP operations. Useful for validating that certificates, passwords, and WSDL files are properly mounted and accessible. ### Method `GET` ### Endpoint `/api/verifactu/ops` ### Parameters None ### Request Example ```bash curl https://api.verifactu.business/api/verifactu/ops ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the service is operational. - **certPath** (string) - The path to the certificate file. - **certFound** (boolean) - Indicates if a certificate was found. - **passLength** (integer) - The length of the password. - **wsdlUrl** (string) - The URL of the WSDL file. - **operations** (array) - A list of available SOAP operations. - **service** (string) - The service name. - **port** (string) - The port name. - **operation** (string) - The operation name. #### Response Example ```json { "ok": true, "certPath": "/var/secrets/aeat_cert/cert.p12", "certFound": true, "passLength": 12, "wsdlUrl": "https://www1.agenciatributaria.gob.es/...", "operations": [ { "service": "sfVerifactu", "port": "SistemaVerifactu", "operation": "RegFactuSistemaFacturacion" }, { "service": "sfVerifactu", "port": "SistemaVerifactu", "operation": "ConsultaFactuSistemaFacturacion" } ] } ``` ``` -------------------------------- ### GET /api/healthz Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt A simple health check endpoint to monitor service availability. ```APIDOC ## GET /api/healthz ### Description Simple health check endpoint for monitoring service availability and uptime checks in cloud environments. ### Method `GET` ### Endpoint `/api/healthz` ### Parameters None ### Request Example ```bash curl https://api.verifactu.business/api/healthz ``` ### Response #### Success Response (200) - **status** (string) - Returns 'ok' to indicate the service is healthy. #### Response Example ``` ok ``` ``` -------------------------------- ### GET /api/verifactu/test-aeat Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Queries invoice information from AEAT for a specific accounting period. This endpoint retrieves registered invoices based on the company's NIF and specified period filters. ```APIDOC ## GET /api/verifactu/test-aeat ### Description Queries invoice information from AEAT for a specific period. This endpoint retrieves registered invoices based on company NIF and accounting period filters. ### Method GET ### Endpoint /api/verifactu/test-aeat ### Parameters This endpoint does not require explicit parameters in the request URL or body for typical usage, as it relies on internal configurations or previously set context for NIF and period. The example below shows an internal query structure for reference. #### Request Body (for reference - not directly sent by client) - **Cabecera** (object) - Required - Header information. - **IDVersion** (string) - Required - Version identifier. - **ObligadoEmision** (object) - Required - Emitting party details. - **NombreRazon** (string) - Required - Legal name. - **NIF** (string) - Required - Tax identification number. - **FiltroConsulta** (object) - Required - Query filter. - **PeriodoImputacion** (object) - Required - Accounting period. - **Ejercicio** (string) - Required - Fiscal year. - **Periodo** (string) - Required - Accounting period (e.g., month). ### Request Example ```bash curl https://api.verifactu.business/api/verifactu/test-aeat ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the query was successful. - **data** (object) - Contains the retrieved invoice query results from AEAT. #### Response Example ```json { "ok": true, "data": { // Invoice query results from AEAT } } ``` ``` -------------------------------- ### SOAP Client Configuration and Usage Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Details on how the SOAP client for AEAT communication is configured and used, including mutual TLS authentication and environment variable requirements for certificate management. ```APIDOC ## SOAP Client Configuration and Usage ### Description This section describes the configuration and usage of the singleton SOAP client responsible for AEAT communication. It emphasizes the use of mutual TLS authentication, reading certificates and credentials from mounted secret files, and provides an example of its integration for registering and querying invoices. ### Method N/A (This section describes internal logic and setup, not a specific HTTP endpoint.) ### Endpoint N/A ### Parameters #### Environment Variables (Required for Client Initialization) - **AEAT_CERT_PATH** (string) - Path to the client certificate file (e.g., `.p12`). - **AEAT_CERT_PASS_PATH** (string) - Path to the file containing the certificate password. - **AEAT_WSDL_FILE** (string) - Path to the file containing the AEAT WSDL URL. ### Request Example (Code Snippet for Usage) ```javascript // apps/api/soap-client.js import { getClient, registerInvoice, queryInvoice } from './apps/api/soap-client.js'; // Environment variables required // AEAT_CERT_PATH=/var/secrets/aeat_cert/cert.p12 // AEAT_CERT_PASS_PATH=/var/secrets/aeat_pass/cert_pass.txt // AEAT_WSDL_FILE=/var/secrets/aeat_wsdl/wsdl_url.txt // Get configured SOAP client and perform operations async function example() { try { const client = await getClient(); console.log('SOAP client ready:', client.describe()); // Example: Register an invoice const invoice = { id: "INV-001", number: "F-001", issueDate: "2025-01-15", total: 1000, tax: { rate: 21, amount: 210 }, customer: { name: "Client", nif: "B12345678" }, issuer: { name: "Company", nif: "A87654321" } }; const registrationResult = await registerInvoice(invoice); console.log('Registration result:', registrationResult); // Example: Query invoice data (assuming queryInvoice function exists and is imported) // const queryParams = { ... }; // Define query parameters // const queryResult = await queryInvoice(queryParams); // console.log('Query result:', queryResult); } catch (error) { console.error('SOAP client error:', error.message); } } example(); ``` ### Response N/A (This section describes internal client operations and their potential outcomes, not direct API responses.) ``` -------------------------------- ### In-Memory User Database Operations (TypeScript) Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Demonstrates the usage of an in-memory database mock for user management. It includes functions to find all users, find a user by ID, update a user's role, and delete a user. The expected 'User' data structure is also defined. This mock is intended for development and testing purposes. ```typescript import { db } from '@/app/db'; // Find all users const users = await db.user.findMany(); console.log('All users:', users); // Find user by ID const user = await db.user.findById('1'); console.log('User:', user); // Update user role const updated = await db.user.update('2', { role: 'ADMIN' }); console.log('Updated user:', updated); // Delete user await db.user.delete('2'); console.log('User deleted'); // Expected data structure type User = { id: string; name?: string | null; email?: string | null; image?: string | null; role: "ADMIN" | "USER"; }; ``` -------------------------------- ### Inspect Service Operations (Fetch API & cURL) Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Retrieves service configuration, including certificate status, password length, WSDL URL, and available SOAP operations. This is useful for verifying that service dependencies like certificates and WSDL files are correctly configured and accessible. It can be called using the Fetch API in JavaScript or via cURL. ```javascript fetch('https://api.verifactu.business/api/verifactu/ops') .then(response => response.json()) .then(data => { console.log('Certificate found:', data.certFound); console.log('Password length:', data.passLength); console.log('WSDL URL:', data.wsdlUrl); console.log('Available operations:', data.operations); }); ``` ```bash curl https://api.verifactu.business/api/verifactu/ops ``` -------------------------------- ### Custom React Hooks (TypeScript) Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Custom React hooks designed for a Next.js application to manage UI state and navigation. `useModal` handles modal visibility (open, close, toggle), and `useGoBack` provides a simple function to navigate the user back to the previous page. ```typescript // useModal hook import { useModal } from '@/hooks/useModal'; function MyComponent() { const { isOpen, openModal, closeModal, toggleModal } = useModal(false); return ( <> {isOpen && (

Modal Content

)} ); } // useGoBack hook import useGoBack from '@/hooks/useGoBack'; function BackButton() { const goBack = useGoBack(); return ( ); } ``` -------------------------------- ### User Management API Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Admin-only API endpoints for managing user roles and accounts. ```APIDOC ## PUT /api/users/[userId] ### Description Updates the role of a specific user. Requires an active NextAuth session with the ADMIN role. ### Method `PUT` ### Endpoint `/api/users/[userId]` ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to update. #### Request Body - **role** (string) - Required - The new role to assign to the user (e.g., 'ADMIN'). ### Request Example ```javascript const response = await fetch('https://verifactu.business/api/users/123', { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Cookie': 'next-auth.session-token=...' }, credentials: 'include', body: JSON.stringify({ role: 'ADMIN' }) }); const updatedUser = await response.json(); console.log('Updated user:', updatedUser); ``` ### Response #### Success Response (200) - **user** (object) - The updated user object. #### Error Response (403) - Indicates unauthorized access if the user is not an admin. ``` ```APIDOC ## DELETE /api/users/[userId] ### Description Deletes a specific user. Admins cannot delete their own account. Requires an active NextAuth session with the ADMIN role. ### Method `DELETE` ### Endpoint `/api/users/[userId]` ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to delete. ### Request Example ```javascript const deleteResponse = await fetch('https://verifactu.business/api/users/456', { method: 'DELETE', headers: { 'Cookie': 'next-auth.session-token=...' }, credentials: 'include' }); if (deleteResponse.ok) { const result = await deleteResponse.json(); console.log('Delete result:', result.message); } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message of the deletion. #### Error Response (400) - Indicates an error if an admin attempts to delete their own account. #### Error Response (403) - Indicates unauthorized access if the user is not an admin. ``` -------------------------------- ### User Management API (TypeScript) Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Provides admin-only API endpoints for managing user roles and accounts. These routes are protected and require a NextAuth session with the ADMIN role. It supports updating user roles (PUT) and deleting users (DELETE), with specific error handling for unauthorized access and self-deletion prevention. ```typescript // PUT /api/users/[userId]/route.ts // Update user role const response = await fetch('https://verifactu.business/api/users/123', { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Cookie': 'next-auth.session-token=...' }, credentials: 'include', body: JSON.stringify({ role: 'ADMIN' }) }); const updatedUser = await response.json(); console.log('Updated user:', updatedUser); // DELETE /api/users/[userId]/route.ts // Delete a user (admin cannot delete themselves) const deleteResponse = await fetch('https://verifactu.business/api/users/456', { method: 'DELETE', headers: { 'Cookie': 'next-auth.session-token=...' }, credentials: 'include' }); if (deleteResponse.ok) { const result = await deleteResponse.json(); console.log('Delete result:', result.message); } // Error handling if (response.status === 403) { console.error('Unauthorized: Admin role required'); } else if (response.status === 400) { console.error('Cannot delete own account'); } ``` -------------------------------- ### Query Invoice Data from AEAT using JavaScript Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Queries invoice information from AEAT for a specified accounting period and company NIF. This endpoint retrieves registered invoices, supporting filtering by period. The snippet demonstrates how to use `fetch` and `curl` for the query. ```javascript // GET /api/verifactu/test-aeat // Internal query structure (for reference) const testQuery = { Cabecera: { IDVersion: "1.0", ObligadoEmision: { NombreRazon: "MI EMPRESA DE PRUEBAS", NIF: "A12345678" } }, FiltroConsulta: { PeriodoImputacion: { Ejercicio: "2025", Periodo: "10" } } }; // Using fetch fetch('https://api.verifactu.business/api/verifactu/test-aeat') .then(response => response.json()) .then(data => { if (data.ok) { console.log('Query successful:', data.data); } else { console.error('Query failed:', data.error); } }) .catch(error => console.error('Request error:', error)); // Using curl curl https://api.verifactu.business/api/verifactu/test-aeat // Expected response { "ok": true, "data": { // Invoice query results from AEAT } } ``` -------------------------------- ### POST /api/verifactu/register-invoice Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Registers a new invoice with the Spanish tax agency (AEAT) by converting JSON invoice data to AEAT-compliant XML and submitting it via a secure SOAP service using mutual TLS authentication. ```APIDOC ## POST /api/verifactu/register-invoice ### Description Registers a new invoice with the Spanish tax agency through the VeriFactu SOAP service. The API endpoint accepts invoice data in JSON format, converts it to AEAT-compliant XML, and submits it using mutual TLS authentication with a client certificate. ### Method POST ### Endpoint /api/verifactu/register-invoice ### Parameters #### Request Body - **id** (string) - Required - Unique identifier for the invoice. - **number** (string) - Required - Invoice number. - **issueDate** (string) - Required - Date of invoice issuance (YYYY-MM-DD). - **total** (number) - Required - Total amount of the invoice. - **tax** (object) - Required - Tax details. - **rate** (number) - Required - Tax rate. - **amount** (number) - Required - Tax amount. - **customer** (object) - Required - Customer details. - **name** (string) - Required - Customer name. - **nif** (string) - Required - Customer NIF (tax identification number). - **issuer** (object) - Required - Issuer details. - **name** (string) - Required - Issuer name. - **nif** (string) - Required - Issuer NIF (tax identification number). ### Request Example ```json { "id": "INV-2025-001", "number": "F-001-2025", "issueDate": "2025-01-15", "total": 1210.00, "tax": { "rate": 21, "amount": 210.00 }, "customer": { "name": "Cliente Ejemplo S.L.", "nif": "B12345678" }, "issuer": { "name": "Mi Empresa S.A.", "nif": "A87654321" } } ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the operation was successful. - **data** (object) - Contains AEAT response data upon successful registration. #### Response Example ```json { "ok": true, "data": { // AEAT response data } } ``` ``` -------------------------------- ### Register Invoice with AEAT using JavaScript Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Registers a new invoice with the Spanish tax agency (AEAT) by sending JSON data to a RESTful API endpoint. The system handles the conversion to AEAT-compliant XML and uses mutual TLS authentication. This snippet shows how to use `fetch` and `curl` for the request. ```javascript // POST /api/verifactu/register-invoice // Request body const invoice = { id: "INV-2025-001", number: "F-001-2025", issueDate: "2025-01-15", total: 1210.00, tax: { rate: 21, amount: 210.00 }, customer: { name: "Cliente Ejemplo S.L.", nif: "B12345678" }, issuer: { name: "Mi Empresa S.A.", nif: "A87654321" } }; // Using fetch fetch('https://api.verifactu.business/api/verifactu/register-invoice', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(invoice) }) .then(response => response.json()) .then(data => { if (data.ok) { console.log('Invoice registered successfully:', data.data); } else { console.error('Registration failed:', data.error); } }) .catch(error => console.error('Request error:', error)); // Using curl curl -X POST https://api.verifactu.business/api/verifactu/register-invoice \ -H "Content-Type: application/json" \ -d '{ "id": "INV-2025-001", "number": "F-001-2025", "issueDate": "2025-01-15", "total": 1210.00, "tax": {"rate": 21, "amount": 210.00}, "customer": {"name": "Cliente Ejemplo S.L.", "nif": "B12345678"}, "issuer": {"name": "Mi Empresa S.A.", "nif": "A87654321"} }' // Expected response { "ok": true, "data": { // AEAT response data } } ``` -------------------------------- ### Convert Invoice to VeriFactu XML (JavaScript) Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Converts invoice data objects into AEAT-compliant XML format using the Facturae schema. This function is essential for generating tax-compliant invoices in Spain. It takes an invoice object as input and returns the XML string. ```javascript import { invoiceToVeriFactuXML } from './apps/api/verifactu-xml.js'; const invoice = { id: "INV-2025-001", number: "F-001-2025", issueDate: "2025-01-15", total: 1210.00, tax: { rate: 21, amount: 210.00 }, customer: { name: "Cliente Ejemplo S.L.", nif: "B12345678" }, issuer: { name: "Mi Empresa S.A.", nif: "A87654321" } }; const xml = invoiceToVeriFactuXML(invoice); console.log(xml); ``` -------------------------------- ### Health Check Endpoint (Fetch API & cURL) Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt Provides a simple health check for monitoring service availability and uptime. It returns a 'ok' status when the service is running. This endpoint is commonly used in cloud environments for automated monitoring and load balancer health checks. ```javascript fetch('https://api.verifactu.business/api/healthz') .then(response => response.text()) .then(data => console.log('Health status:', data)); ``` ```bash curl https://api.verifactu.business/api/healthz ``` -------------------------------- ### Invoice to VeriFactu XML Conversion Source: https://context7.com/kiabusiness2025/verifactu-monorepo/llms.txt This function converts an invoice object into AEAT-compliant XML format following the Facturae schema. ```APIDOC ## Invoice to VeriFactu XML Conversion ### Description Converts invoice objects to AEAT-compliant XML format following the Facturae schema required by Spanish tax authorities. ### Method `POST` (Implied, as it's a conversion function) ### Endpoint `/api/verifactu-xml` (Implied) ### Parameters #### Request Body - **invoice** (object) - Required - The invoice object containing details such as id, number, issueDate, total, tax, customer, and issuer. ### Request Example ```json { "id": "INV-2025-001", "number": "F-001-2025", "issueDate": "2025-01-15", "total": 1210.00, "tax": { "rate": 21, "amount": 210.00 }, "customer": { "name": "Cliente Ejemplo S.L.", "nif": "B12345678" }, "issuer": { "name": "Mi Empresa S.A.", "nif": "A87654321" } } ``` ### Response #### Success Response (200) - **xml** (string) - The AEAT-compliant XML string. #### Response Example ```xml INV-2025-001 F-001-2025 2025-01-15 1210 21 210 Cliente Ejemplo S.L. B12345678 Mi Empresa S.A. A87654321 ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.