@dwast/verifactu-lib 0.1.0-beta.1 → 0.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/cjs/aeat/client.d.ts +115 -14
  2. package/dist/cjs/aeat/client.d.ts.map +1 -1
  3. package/dist/cjs/aeat/client.js +223 -47
  4. package/dist/cjs/aeat/client.js.map +1 -1
  5. package/dist/cjs/aeat/index.d.ts +1 -0
  6. package/dist/cjs/aeat/index.d.ts.map +1 -1
  7. package/dist/cjs/aeat/index.js +1 -0
  8. package/dist/cjs/aeat/index.js.map +1 -1
  9. package/dist/cjs/aeat/response.d.ts +80 -0
  10. package/dist/cjs/aeat/response.d.ts.map +1 -0
  11. package/dist/cjs/aeat/response.js +118 -0
  12. package/dist/cjs/aeat/response.js.map +1 -0
  13. package/dist/cjs/core/hash/chain.d.ts +42 -0
  14. package/dist/cjs/core/hash/chain.d.ts.map +1 -1
  15. package/dist/cjs/core/hash/chain.js +40 -0
  16. package/dist/cjs/core/hash/chain.js.map +1 -1
  17. package/dist/cjs/core/index.d.ts +2 -0
  18. package/dist/cjs/core/index.d.ts.map +1 -1
  19. package/dist/cjs/core/index.js +2 -0
  20. package/dist/cjs/core/index.js.map +1 -1
  21. package/dist/cjs/core/models/index.d.ts +0 -1
  22. package/dist/cjs/core/models/index.d.ts.map +1 -1
  23. package/dist/cjs/core/models/index.js +0 -1
  24. package/dist/cjs/core/models/index.js.map +1 -1
  25. package/dist/cjs/core/models/invoice.d.ts +42 -17
  26. package/dist/cjs/core/models/invoice.d.ts.map +1 -1
  27. package/dist/cjs/core/utils/date.d.ts +16 -0
  28. package/dist/cjs/core/utils/date.d.ts.map +1 -0
  29. package/dist/cjs/core/utils/date.js +27 -0
  30. package/dist/cjs/core/utils/date.js.map +1 -0
  31. package/dist/cjs/core/utils/index.d.ts +2 -0
  32. package/dist/cjs/core/utils/index.d.ts.map +1 -0
  33. package/dist/cjs/core/utils/index.js +18 -0
  34. package/dist/cjs/core/utils/index.js.map +1 -0
  35. package/dist/cjs/core/validation/index.d.ts +2 -0
  36. package/dist/cjs/core/validation/index.d.ts.map +1 -0
  37. package/dist/cjs/core/validation/index.js +18 -0
  38. package/dist/cjs/core/validation/index.js.map +1 -0
  39. package/dist/cjs/core/validation/validate.d.ts +18 -0
  40. package/dist/cjs/core/validation/validate.d.ts.map +1 -0
  41. package/dist/cjs/core/validation/validate.js +65 -0
  42. package/dist/cjs/core/validation/validate.js.map +1 -0
  43. package/dist/cjs/core/xml/generator.d.ts +117 -11
  44. package/dist/cjs/core/xml/generator.d.ts.map +1 -1
  45. package/dist/cjs/core/xml/generator.js +239 -64
  46. package/dist/cjs/core/xml/generator.js.map +1 -1
  47. package/dist/cjs/integration/accountability.d.ts +41 -0
  48. package/dist/cjs/integration/accountability.d.ts.map +1 -0
  49. package/dist/cjs/integration/accountability.js +92 -0
  50. package/dist/cjs/integration/accountability.js.map +1 -0
  51. package/dist/cjs/integration/index.d.ts +2 -0
  52. package/dist/cjs/integration/index.d.ts.map +1 -1
  53. package/dist/cjs/integration/index.js +2 -0
  54. package/dist/cjs/integration/index.js.map +1 -1
  55. package/dist/cjs/integration/p12.d.ts +58 -0
  56. package/dist/cjs/integration/p12.d.ts.map +1 -0
  57. package/dist/cjs/integration/p12.js +127 -0
  58. package/dist/cjs/integration/p12.js.map +1 -0
  59. package/dist/cjs/integration/repository.d.ts +4 -3
  60. package/dist/cjs/integration/repository.d.ts.map +1 -1
  61. package/dist/cjs/integration/service.d.ts +11 -2
  62. package/dist/cjs/integration/service.d.ts.map +1 -1
  63. package/dist/cjs/integration/service.js +115 -15
  64. package/dist/cjs/integration/service.js.map +1 -1
  65. package/dist/cjs/integration/tenant-credentials.d.ts +44 -0
  66. package/dist/cjs/integration/tenant-credentials.d.ts.map +1 -0
  67. package/dist/cjs/integration/tenant-credentials.js +62 -0
  68. package/dist/cjs/integration/tenant-credentials.js.map +1 -0
  69. package/dist/esm/aeat/client.d.ts +115 -14
  70. package/dist/esm/aeat/client.d.ts.map +1 -1
  71. package/dist/esm/aeat/client.js +218 -46
  72. package/dist/esm/aeat/client.js.map +1 -1
  73. package/dist/esm/aeat/index.d.ts +1 -0
  74. package/dist/esm/aeat/index.d.ts.map +1 -1
  75. package/dist/esm/aeat/index.js +1 -0
  76. package/dist/esm/aeat/index.js.map +1 -1
  77. package/dist/esm/aeat/response.d.ts +80 -0
  78. package/dist/esm/aeat/response.d.ts.map +1 -0
  79. package/dist/esm/aeat/response.js +115 -0
  80. package/dist/esm/aeat/response.js.map +1 -0
  81. package/dist/esm/core/hash/chain.d.ts +42 -0
  82. package/dist/esm/core/hash/chain.d.ts.map +1 -1
  83. package/dist/esm/core/hash/chain.js +37 -0
  84. package/dist/esm/core/hash/chain.js.map +1 -1
  85. package/dist/esm/core/index.d.ts +2 -0
  86. package/dist/esm/core/index.d.ts.map +1 -1
  87. package/dist/esm/core/index.js +2 -0
  88. package/dist/esm/core/index.js.map +1 -1
  89. package/dist/esm/core/models/index.d.ts +0 -1
  90. package/dist/esm/core/models/index.d.ts.map +1 -1
  91. package/dist/esm/core/models/index.js +0 -1
  92. package/dist/esm/core/models/index.js.map +1 -1
  93. package/dist/esm/core/models/invoice.d.ts +42 -17
  94. package/dist/esm/core/models/invoice.d.ts.map +1 -1
  95. package/dist/esm/core/utils/date.d.ts +16 -0
  96. package/dist/esm/core/utils/date.d.ts.map +1 -0
  97. package/dist/esm/core/utils/date.js +24 -0
  98. package/dist/esm/core/utils/date.js.map +1 -0
  99. package/dist/esm/core/utils/index.d.ts +2 -0
  100. package/dist/esm/core/utils/index.d.ts.map +1 -0
  101. package/dist/esm/core/utils/index.js +2 -0
  102. package/dist/esm/core/utils/index.js.map +1 -0
  103. package/dist/esm/core/validation/index.d.ts +2 -0
  104. package/dist/esm/core/validation/index.d.ts.map +1 -0
  105. package/dist/esm/core/validation/index.js +2 -0
  106. package/dist/esm/core/validation/index.js.map +1 -0
  107. package/dist/esm/core/validation/validate.d.ts +18 -0
  108. package/dist/esm/core/validation/validate.d.ts.map +1 -0
  109. package/dist/esm/core/validation/validate.js +62 -0
  110. package/dist/esm/core/validation/validate.js.map +1 -0
  111. package/dist/esm/core/xml/generator.d.ts +117 -11
  112. package/dist/esm/core/xml/generator.d.ts.map +1 -1
  113. package/dist/esm/core/xml/generator.js +233 -64
  114. package/dist/esm/core/xml/generator.js.map +1 -1
  115. package/dist/esm/integration/accountability.d.ts +41 -0
  116. package/dist/esm/integration/accountability.d.ts.map +1 -0
  117. package/dist/esm/integration/accountability.js +88 -0
  118. package/dist/esm/integration/accountability.js.map +1 -0
  119. package/dist/esm/integration/index.d.ts +2 -0
  120. package/dist/esm/integration/index.d.ts.map +1 -1
  121. package/dist/esm/integration/index.js +2 -0
  122. package/dist/esm/integration/index.js.map +1 -1
  123. package/dist/esm/integration/p12.d.ts +58 -0
  124. package/dist/esm/integration/p12.d.ts.map +1 -0
  125. package/dist/esm/integration/p12.js +119 -0
  126. package/dist/esm/integration/p12.js.map +1 -0
  127. package/dist/esm/integration/repository.d.ts +4 -3
  128. package/dist/esm/integration/repository.d.ts.map +1 -1
  129. package/dist/esm/integration/service.d.ts +11 -2
  130. package/dist/esm/integration/service.d.ts.map +1 -1
  131. package/dist/esm/integration/service.js +117 -17
  132. package/dist/esm/integration/service.js.map +1 -1
  133. package/dist/esm/integration/tenant-credentials.d.ts +44 -0
  134. package/dist/esm/integration/tenant-credentials.d.ts.map +1 -0
  135. package/dist/esm/integration/tenant-credentials.js +58 -0
  136. package/dist/esm/integration/tenant-credentials.js.map +1 -0
  137. package/package.json +3 -1
  138. package/readme.md +731 -38
  139. package/src/aeat/client.ts +298 -57
  140. package/src/aeat/index.ts +1 -0
  141. package/src/aeat/response.ts +198 -0
  142. package/src/core/hash/chain.ts +68 -0
  143. package/src/core/index.ts +2 -0
  144. package/src/core/models/index.ts +0 -1
  145. package/src/core/models/invoice.ts +40 -18
  146. package/src/core/utils/date.ts +27 -0
  147. package/src/core/utils/index.ts +1 -0
  148. package/src/core/validation/index.ts +1 -0
  149. package/src/core/validation/validate.ts +71 -0
  150. package/src/core/xml/generator.ts +312 -73
  151. package/src/integration/accountability.ts +125 -0
  152. package/src/integration/index.ts +2 -0
  153. package/src/integration/p12.ts +155 -0
  154. package/src/integration/repository.ts +4 -3
  155. package/src/integration/schema.sql +0 -14
  156. package/src/integration/service.ts +134 -16
  157. package/src/core/models/event.ts +0 -25
@@ -1,17 +1,25 @@
1
- import type { Invoice } from '../models/invoice.js';
1
+ import type { Invoice, SistemaInformatico } from '../models/invoice.js';
2
2
 
3
3
  /**
4
- * Datos de la factura que se anula.
4
+ * Datos de un registro de anulación (RegistroFacturacionAnulacionType).
5
5
  */
6
6
  export interface AnulacionInput {
7
7
  /** NIF del emisor de la factura anulada. */
8
8
  idEmisorFacturaAnulada: string;
9
9
  /** Número y serie de la factura anulada. */
10
10
  numSerieFacturaAnulada: string;
11
- /** Fecha de expedición de la factura anulada. */
11
+ /** Fecha de expedición de la factura anulada (DD-MM-YYYY). */
12
12
  fechaExpedicionFacturaAnulada: string;
13
13
  /** Huella (hash) de la factura anulada. */
14
14
  huellaFacturaAnulada: string;
15
+ /** Sistema informático que genera el registro. */
16
+ sistemaInformatico: SistemaInformatico;
17
+ /** Fecha/hora de generación con huso horario. */
18
+ fechaHoraHusoGenRegistro: string;
19
+ /** Huella (hash) del propio registro de anulación. */
20
+ huella: string;
21
+ /** Versión del esquema (por defecto '1.0'). */
22
+ idVersion?: string;
15
23
  }
16
24
 
17
25
  /**
@@ -34,64 +42,85 @@ function formatAmount(value: number): string {
34
42
  }
35
43
 
36
44
  /**
37
- * Genera el XML Verifactu de una factura (registro de alta).
45
+ * Genera el elemento `<RegistroAlta>` de una factura (registro de alta).
38
46
  *
39
- * Estructura basada en el RD 1007/2023 y la documentación técnica de la
40
- * AEAT. NOTA: el esquema XSD oficial debe validarse antes de producción;
41
- * este esqueleto refleja los bloques principales (IDFactura, IDEmisorFactura,
42
- * TipoFactura, TipoDesglose, Desglose, CuotaTotal, Encadenamiento, Huella).
47
+ * Estructura según el XSD `SuministroInformacion.xsd` de la AEAT
48
+ * (`RegistroFacturacionAltaType`). NOTA: validar contra el XSD oficial
49
+ * antes de producción.
43
50
  */
44
- export function generateInvoiceXml(invoice: Invoice, previousHash: string | null): string {
45
- const { id, emisor, desglose, tipoFactura, tipoDesglose } = invoice;
46
-
47
- const detalles = desglose.tipoOperaciones
48
- .map((op) => {
49
- const iva = op.detallesIva
50
- .map(
51
- (d) =>
52
- ` <DetalleIVA>` +
53
- `<TipoImpositivo>${formatAmount(d.tipoImpositivo)}</TipoImpositivo>` +
54
- `<BaseImponible>${formatAmount(d.baseImponible)}</BaseImponible>` +
55
- `<CuotaRepercutida>${formatAmount(d.cuotaRepercutida)}</CuotaRepercutida>` +
56
- `</DetalleIVA>`,
57
- )
58
- .join('\n');
59
- return (
60
- ` <DesgloseTipoOperacion>` +
61
- `<TipoOperacion>${escapeXml(op.tipoOperacion)}</TipoOperacion>` +
62
- `\n <DesgloseIVA>\n${iva}\n </DesgloseIVA>` +
63
- `\n </DesgloseTipoOperacion>`
64
- );
65
- })
51
+ export function generateRegistroAltaXml(invoice: Invoice, previousHash: string | null): string {
52
+ const { id, emisor, desglose, tipoFactura, sistemaInformatico } = invoice;
53
+ const idVersion = invoice.idVersion ?? '1.0';
54
+ const descripcion = invoice.descripcion ?? '';
55
+
56
+ const detalles = desglose.detalles
57
+ .map(
58
+ (d) =>
59
+ ` <sf:DetalleDesglose>` +
60
+ (d.claveRegimen !== undefined
61
+ ? `<sf:ClaveRegimen>${escapeXml(d.claveRegimen)}</sf:ClaveRegimen>`
62
+ : '') +
63
+ `<sf:CalificacionOperacion>${escapeXml(d.calificacionOperacion)}</sf:CalificacionOperacion>` +
64
+ (d.tipoImpositivo !== undefined
65
+ ? `<sf:TipoImpositivo>${formatAmount(d.tipoImpositivo)}</sf:TipoImpositivo>`
66
+ : '') +
67
+ `<sf:BaseImponibleOimporteNoSujeto>${formatAmount(d.baseImponible)}</sf:BaseImponibleOimporteNoSujeto>` +
68
+ (d.cuotaRepercutida !== undefined
69
+ ? `<sf:CuotaRepercutida>${formatAmount(d.cuotaRepercutida)}</sf:CuotaRepercutida>`
70
+ : '') +
71
+ `</sf:DetalleDesglose>`,
72
+ )
66
73
  .join('\n');
67
74
 
75
+ const encadenamiento = previousHash
76
+ ? ` <sf:RegistroAnterior><sf:IDEmisorFactura>${escapeXml(emisor.nif)}</sf:IDEmisorFactura><sf:NumSerieFactura>${escapeXml(id.serie ?? '')}${escapeXml(id.numero)}</sf:NumSerieFactura><sf:FechaExpedicionFactura>${id.fechaExpedicion}</sf:FechaExpedicionFactura><sf:Huella>${previousHash}</sf:Huella></sf:RegistroAnterior>`
77
+ : ` <sf:PrimerRegistro>S</sf:PrimerRegistro>`;
78
+
68
79
  const xml = [
69
80
  '<?xml version="1.0" encoding="UTF-8"?>',
70
- '<RegistroFactura>',
71
- ' <IDFactura>',
72
- ' <IDEmisorFactura>',
73
- ` <NIF>${escapeXml(emisor.nif)}</NIF>`,
74
- ` <NombreRazon>${escapeXml(emisor.nombreRazon)}</NombreRazon>`,
75
- emisor.pais ? ` <Pais>${escapeXml(emisor.pais)}</Pais>` : '',
76
- emisor.codigoPostal ? ` <CodigoPostal>${escapeXml(emisor.codigoPostal)}</CodigoPostal>` : '',
77
- emisor.municipio ? ` <Municipio>${escapeXml(emisor.municipio)}</Municipio>` : '',
78
- emisor.direccion ? ` <Direccion>${escapeXml(emisor.direccion)}</Direccion>` : '',
79
- ' </IDEmisorFactura>',
80
- id.serie ? ` <SerieFactura>${escapeXml(id.serie)}</SerieFactura>` : '',
81
- ` <NumeroFactura>${escapeXml(id.numero)}</NumeroFactura>`,
82
- ` <FechaExpedicionFactura>${id.fechaExpedicion}</FechaExpedicionFactura>`,
83
- id.fechaOperacion ? ` <FechaOperacion>${id.fechaOperacion}</FechaOperacion>` : '',
84
- ' </IDFactura>',
85
- ` <TipoFactura>${tipoFactura}</TipoFactura>`,
86
- ` <TipoDesglose>${tipoDesglose}</TipoDesglose>`,
87
- ' <Desglose>',
81
+ `<sf:RegistroAlta xmlns:sf="${AEAT_INFORMACION_NAMESPACE}">`,
82
+ ` <sf:IDVersion>${idVersion}</sf:IDVersion>`,
83
+ ' <sf:IDFactura>',
84
+ ` <sf:IDEmisorFactura>${escapeXml(emisor.nif)}</sf:IDEmisorFactura>`,
85
+ ` <sf:NumSerieFactura>${escapeXml(id.serie ?? '')}${escapeXml(id.numero)}</sf:NumSerieFactura>`,
86
+ ` <sf:FechaExpedicionFactura>${id.fechaExpedicion}</sf:FechaExpedicionFactura>`,
87
+ ' </sf:IDFactura>',
88
+ ` <sf:NombreRazonEmisor>${escapeXml(emisor.nombreRazon)}</sf:NombreRazonEmisor>`,
89
+ ` <sf:TipoFactura>${tipoFactura}</sf:TipoFactura>`,
90
+ ` <sf:DescripcionOperacion>${escapeXml(descripcion)}</sf:DescripcionOperacion>`,
91
+ ...(invoice.destinatarios && invoice.destinatarios.length
92
+ ? [
93
+ ' <sf:Destinatarios>',
94
+ ...invoice.destinatarios.map(
95
+ (d) =>
96
+ ` <sf:IDDestinatario><sf:NombreRazon>${escapeXml(d.nombreRazon)}</sf:NombreRazon><sf:NIF>${escapeXml(d.nif)}</sf:NIF></sf:IDDestinatario>`,
97
+ ),
98
+ ' </sf:Destinatarios>',
99
+ ]
100
+ : []),
101
+ ' <sf:Desglose>',
88
102
  detalles,
89
- ' </Desglose>',
90
- ` <CuotaTotal>${formatAmount(desglose.cuotaTotal)}</CuotaTotal>`,
91
- ' <Encadenamiento>',
92
- ` <HashAnterior>${previousHash ?? ''}</HashAnterior>`,
93
- ' </Encadenamiento>',
94
- '</RegistroFactura>',
103
+ ' </sf:Desglose>',
104
+ ` <sf:CuotaTotal>${formatAmount(desglose.cuotaTotal)}</sf:CuotaTotal>`,
105
+ ` <sf:ImporteTotal>${formatAmount(desglose.importeTotal)}</sf:ImporteTotal>`,
106
+ ' <sf:Encadenamiento>',
107
+ encadenamiento,
108
+ ' </sf:Encadenamiento>',
109
+ ' <sf:SistemaInformatico>',
110
+ ` <sf:NombreRazon>${escapeXml(sistemaInformatico.nombreRazon)}</sf:NombreRazon>`,
111
+ ` <sf:NIF>${escapeXml(sistemaInformatico.nif)}</sf:NIF>`,
112
+ ` <sf:NombreSistemaInformatico>${escapeXml(sistemaInformatico.nombreSistemaInformatico)}</sf:NombreSistemaInformatico>`,
113
+ ` <sf:IdSistemaInformatico>${escapeXml(sistemaInformatico.idSistemaInformatico)}</sf:IdSistemaInformatico>`,
114
+ ` <sf:Version>${escapeXml(sistemaInformatico.version)}</sf:Version>`,
115
+ ` <sf:NumeroInstalacion>${escapeXml(sistemaInformatico.numeroInstalacion)}</sf:NumeroInstalacion>`,
116
+ ' <sf:TipoUsoPosibleSoloVerifactu>S</sf:TipoUsoPosibleSoloVerifactu>',
117
+ ' <sf:TipoUsoPosibleMultiOT>N</sf:TipoUsoPosibleMultiOT>',
118
+ ' <sf:IndicadorMultiplesOT>N</sf:IndicadorMultiplesOT>',
119
+ ' </sf:SistemaInformatico>',
120
+ ` <sf:FechaHoraHusoGenRegistro>${invoice.fechaHoraHusoGenRegistro}</sf:FechaHoraHusoGenRegistro>`,
121
+ ' <sf:TipoHuella>01</sf:TipoHuella>',
122
+ ` <sf:Huella>${invoice.huella}</sf:Huella>`,
123
+ '</sf:RegistroAlta>',
95
124
  ]
96
125
  .filter((line) => line !== '')
97
126
  .join('\n');
@@ -100,34 +129,244 @@ export function generateInvoiceXml(invoice: Invoice, previousHash: string | null
100
129
  }
101
130
 
102
131
  /**
103
- * Genera el XML Verifactu de un registro de anulación.
132
+ * Namespace del esquema `SuministroLR.xsd` de la AEAT.
133
+ */
134
+ export const AEAT_SUMINISTRO_NAMESPACE =
135
+ 'https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/tike/cont/ws/SuministroLR.xsd';
136
+
137
+ /**
138
+ * Namespace del esquema `SuministroInformacion.xsd` de la AEAT.
139
+ */
140
+ export const AEAT_INFORMACION_NAMESPACE =
141
+ 'https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/tike/cont/ws/SuministroInformacion.xsd';
142
+
143
+ /**
144
+ * Namespace del esquema `EventosSIF.xsd` de la AEAT (registro de eventos).
145
+ */
146
+ export const AEAT_EVENTO_NAMESPACE =
147
+ 'https://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/tike/cont/ws/EventosSIF.xsd';
148
+
149
+ /**
150
+ * Cabecera del suministro (CabeceraType del XSD).
151
+ */
152
+ export interface Cabecera {
153
+ /** Nombre o razón social del obligado a emitir. */
154
+ nombreRazon: string;
155
+ /** NIF del obligado a emitir. */
156
+ nif: string;
157
+ /** Representante del obligado (solo si el envío lo hace un representante). */
158
+ representante?: {
159
+ /** Nombre o razón social del representante. */
160
+ nombreRazon: string;
161
+ /** NIF del representante. */
162
+ nif: string;
163
+ };
164
+ }
165
+
166
+ /**
167
+ * Genera el elemento `<RegFactuSistemaFacturacion>` completo (operación SOAP),
168
+ * con la `Cabecera` y el `RegistroFactura` que envuelve el registro.
169
+ */
170
+ export function generateSuministroXml(registroXml: string, cabecera: Cabecera): string {
171
+ const body = registroXml.replace(/^<\?xml[^>]*\?>\s*/, '');
172
+ const representante = cabecera.representante
173
+ ? [
174
+ ' <sf:Representante>',
175
+ ` <sf:NombreRazon>${escapeXml(cabecera.representante.nombreRazon)}</sf:NombreRazon>`,
176
+ ` <sf:NIF>${escapeXml(cabecera.representante.nif)}</sf:NIF>`,
177
+ ' </sf:Representante>',
178
+ ].join('\n')
179
+ : '';
180
+ return [
181
+ '<?xml version="1.0" encoding="UTF-8"?>',
182
+ `<sfLR:RegFactuSistemaFacturacion xmlns:sfLR="${AEAT_SUMINISTRO_NAMESPACE}" xmlns:sf="${AEAT_INFORMACION_NAMESPACE}">`,
183
+ ' <sfLR:Cabecera>',
184
+ ' <sf:ObligadoEmision>',
185
+ ` <sf:NombreRazon>${escapeXml(cabecera.nombreRazon)}</sf:NombreRazon>`,
186
+ ` <sf:NIF>${escapeXml(cabecera.nif)}</sf:NIF>`,
187
+ ' </sf:ObligadoEmision>',
188
+ representante,
189
+ ' </sfLR:Cabecera>',
190
+ ' <sfLR:RegistroFactura>',
191
+ body,
192
+ ' </sfLR:RegistroFactura>',
193
+ '</sfLR:RegFactuSistemaFacturacion>',
194
+ ].join('\n');
195
+ }
196
+
197
+ /**
198
+ * Construye la `Cabecera` del suministro, detectando si el certificado es de
199
+ * un representante.
200
+ *
201
+ * Si se proporciona el certificado en PEM y su NIF difiere del NIF del
202
+ * obligado, se añade el bloque `Representante` (el certificado actúa como
203
+ * representante del obligado), usando el nombre del titular del certificado.
204
+ */
205
+ export function buildCabecera(
206
+ obligado: { nombreRazon: string; nif: string },
207
+ certificatePem?: string,
208
+ extractInfo?: (pem: string) => { nif: string; nombreRazon: string } | null,
209
+ ): Cabecera {
210
+ const cabecera: Cabecera = { nombreRazon: obligado.nombreRazon, nif: obligado.nif };
211
+ if (certificatePem && extractInfo) {
212
+ const info = extractInfo(certificatePem);
213
+ if (info && info.nif !== obligado.nif) {
214
+ cabecera.representante = { nombreRazon: info.nombreRazon, nif: info.nif };
215
+ }
216
+ }
217
+ return cabecera;
218
+ }
219
+
220
+ /**
221
+ * Genera el XML Verifactu de una factura (registro de alta).
222
+ *
223
+ * Alias de `generateRegistroAltaXml` por compatibilidad.
224
+ */
225
+ export function generateInvoiceXml(invoice: Invoice, previousHash: string | null): string {
226
+ return generateRegistroAltaXml(invoice, previousHash);
227
+ }
228
+
229
+ /**
230
+ * Genera el XML Verifactu de un registro de anulación (`<sf:RegistroAnulacion>`).
104
231
  *
105
- * Referencia la factura anulada (IDFactura + Huella) y encadena con el hash
106
- * anterior. Estructura basada en el RD 1007/2023; validar contra el XSD
107
- * oficial antes de producción.
232
+ * Referencia la factura anulada (IDFactura) y encadena con el hash anterior.
233
+ * Estructura según el XSD `SuministroInformacion.xsd` (`RegistroFacturacionAnulacionType`).
108
234
  */
109
235
  export function generateAnulacionXml(
110
236
  anulacion: AnulacionInput,
111
237
  previousHash: string | null,
112
238
  ): string {
239
+ const idVersion = anulacion.idVersion ?? '1.0';
240
+ const si = anulacion.sistemaInformatico;
241
+ const encadenamiento = previousHash
242
+ ? ` <sf:RegistroAnterior><sf:IDEmisorFactura>${escapeXml(anulacion.idEmisorFacturaAnulada)}</sf:IDEmisorFactura><sf:NumSerieFactura>${escapeXml(anulacion.numSerieFacturaAnulada)}</sf:NumSerieFactura><sf:FechaExpedicionFactura>${anulacion.fechaExpedicionFacturaAnulada}</sf:FechaExpedicionFactura><sf:Huella>${previousHash}</sf:Huella></sf:RegistroAnterior>`
243
+ : ` <sf:PrimerRegistro>S</sf:PrimerRegistro>`;
244
+
245
+ return [
246
+ '<?xml version="1.0" encoding="UTF-8"?>',
247
+ `<sf:RegistroAnulacion xmlns:sf="${AEAT_INFORMACION_NAMESPACE}">`,
248
+ ` <sf:IDVersion>${idVersion}</sf:IDVersion>`,
249
+ ' <sf:IDFactura>',
250
+ ` <sf:IDEmisorFacturaAnulada>${escapeXml(anulacion.idEmisorFacturaAnulada)}</sf:IDEmisorFacturaAnulada>`,
251
+ ` <sf:NumSerieFacturaAnulada>${escapeXml(anulacion.numSerieFacturaAnulada)}</sf:NumSerieFacturaAnulada>`,
252
+ ` <sf:FechaExpedicionFacturaAnulada>${anulacion.fechaExpedicionFacturaAnulada}</sf:FechaExpedicionFacturaAnulada>`,
253
+ ' </sf:IDFactura>',
254
+ ' <sf:Encadenamiento>',
255
+ encadenamiento,
256
+ ' </sf:Encadenamiento>',
257
+ ' <sf:SistemaInformatico>',
258
+ ` <sf:NombreRazon>${escapeXml(si.nombreRazon)}</sf:NombreRazon>`,
259
+ ` <sf:NIF>${escapeXml(si.nif)}</sf:NIF>`,
260
+ ` <sf:NombreSistemaInformatico>${escapeXml(si.nombreSistemaInformatico)}</sf:NombreSistemaInformatico>`,
261
+ ` <sf:IdSistemaInformatico>${escapeXml(si.idSistemaInformatico)}</sf:IdSistemaInformatico>`,
262
+ ` <sf:Version>${escapeXml(si.version)}</sf:Version>`,
263
+ ` <sf:NumeroInstalacion>${escapeXml(si.numeroInstalacion)}</sf:NumeroInstalacion>`,
264
+ ' <sf:TipoUsoPosibleSoloVerifactu>S</sf:TipoUsoPosibleSoloVerifactu>',
265
+ ' <sf:TipoUsoPosibleMultiOT>N</sf:TipoUsoPosibleMultiOT>',
266
+ ' <sf:IndicadorMultiplesOT>N</sf:IndicadorMultiplesOT>',
267
+ ' </sf:SistemaInformatico>',
268
+ ` <sf:FechaHoraHusoGenRegistro>${anulacion.fechaHoraHusoGenRegistro}</sf:FechaHoraHusoGenRegistro>`,
269
+ ' <sf:TipoHuella>01</sf:TipoHuella>',
270
+ ` <sf:Huella>${anulacion.huella}</sf:Huella>`,
271
+ '</sf:RegistroAnulacion>',
272
+ ].join('\n');
273
+ }
274
+
275
+ /**
276
+ * Datos de un registro de evento (RegistroEvento, EventosSIF.xsd).
277
+ */
278
+ export interface EventoInput {
279
+ /** Sistema informático que genera el evento. */
280
+ sistemaInformatico: SistemaInformatico;
281
+ /** Obligado a emitir (persona física o jurídica española). */
282
+ obligadoEmision: { nombreRazon: string; nif: string };
283
+ /** Fecha/hora de generación con huso horario (ISO 8601). */
284
+ fechaHoraHusoGenEvento: string;
285
+ /** Tipo de evento (01–10, 90). */
286
+ tipoEvento: string;
287
+ /** Huella (hash) del evento. */
288
+ huellaEvento: string;
289
+ /** Evento anterior de la cadena (obligatorio para el 2º evento en adelante). */
290
+ eventoAnterior?: {
291
+ /** Tipo de evento del evento anterior. */
292
+ tipoEvento: string;
293
+ /** Fecha/hora de generación del evento anterior. */
294
+ fechaHoraHusoGenEvento: string;
295
+ /** Huella (hash) del evento anterior. */
296
+ huellaEvento: string;
297
+ };
298
+ /** Versión del esquema (por defecto '1.0'). */
299
+ idVersion?: string;
300
+ }
301
+
302
+ /**
303
+ * Genera el XML Verifactu de un registro de evento (RegistroEvento).
304
+ *
305
+ * Estructura basada en `EventosSIF.xsd` (namespace `sf`). El evento se envía
306
+ * como un suministro independiente (no dentro de `RegFactuSistemaFacturacion`).
307
+ *
308
+ * El encadenado emite `<sf:PrimerEvento>S</sf:PrimerEvento>` si es el primer
309
+ * evento, o `<sf:EventoAnterior>` con los datos del evento previo si se
310
+ * proporciona `eventoAnterior`.
311
+ */
312
+ export function generateEventoXml(evento: EventoInput): string {
313
+ const si = evento.sistemaInformatico;
314
+ const encadenamiento = evento.eventoAnterior
315
+ ? [
316
+ ' <sf:Encadenamiento>',
317
+ ' <sf:EventoAnterior>',
318
+ ` <sf:TipoEvento>${escapeXml(evento.eventoAnterior.tipoEvento)}</sf:TipoEvento>`,
319
+ ` <sf:FechaHoraHusoGenEvento>${evento.eventoAnterior.fechaHoraHusoGenEvento}</sf:FechaHoraHusoGenEvento>`,
320
+ ` <sf:HuellaEvento>${evento.eventoAnterior.huellaEvento}</sf:HuellaEvento>`,
321
+ ' </sf:EventoAnterior>',
322
+ ' </sf:Encadenamiento>',
323
+ ]
324
+ : [' <sf:Encadenamiento>', ' <sf:PrimerEvento>S</sf:PrimerEvento>', ' </sf:Encadenamiento>'];
113
325
  const xml = [
114
326
  '<?xml version="1.0" encoding="UTF-8"?>',
115
- '<RegistroFactura>',
116
- ' <RegistroAnulacion>',
117
- ' <IDFactura>',
118
- ' <IDEmisorFactura>',
119
- ` <NIF>${escapeXml(anulacion.idEmisorFacturaAnulada)}</NIF>`,
120
- ' </IDEmisorFactura>',
121
- ` <NumeroFactura>${escapeXml(anulacion.numSerieFacturaAnulada)}</NumeroFactura>`,
122
- ` <FechaExpedicionFactura>${anulacion.fechaExpedicionFacturaAnulada}</FechaExpedicionFactura>`,
123
- ' </IDFactura>',
124
- ` <Huella>${anulacion.huellaFacturaAnulada}</Huella>`,
125
- ' </RegistroAnulacion>',
126
- ' <Encadenamiento>',
127
- ` <HashAnterior>${previousHash ?? ''}</HashAnterior>`,
128
- ' </Encadenamiento>',
129
- '</RegistroFactura>',
327
+ `<sf:RegistroEvento xmlns:sf="${AEAT_EVENTO_NAMESPACE}">`,
328
+ ` <sf:IDVersion>${escapeXml(evento.idVersion ?? '1.0')}</sf:IDVersion>`,
329
+ ' <sf:Evento>',
330
+ ' <sf:SistemaInformatico>',
331
+ ` <sf:NombreRazon>${escapeXml(si.nombreRazon)}</sf:NombreRazon>`,
332
+ ` <sf:NIF>${escapeXml(si.nif)}</sf:NIF>`,
333
+ ` <sf:NombreSistemaInformatico>${escapeXml(si.nombreSistemaInformatico)}</sf:NombreSistemaInformatico>`,
334
+ ` <sf:IdSistemaInformatico>${escapeXml(si.idSistemaInformatico)}</sf:IdSistemaInformatico>`,
335
+ ` <sf:Version>${escapeXml(si.version)}</sf:Version>`,
336
+ ` <sf:NumeroInstalacion>${escapeXml(si.numeroInstalacion)}</sf:NumeroInstalacion>`,
337
+ ' <sf:TipoUsoPosibleSoloVerifactu>S</sf:TipoUsoPosibleSoloVerifactu>',
338
+ ' <sf:TipoUsoPosibleMultiOT>N</sf:TipoUsoPosibleMultiOT>',
339
+ ' <sf:IndicadorMultiplesOT>N</sf:IndicadorMultiplesOT>',
340
+ ' </sf:SistemaInformatico>',
341
+ ' <sf:ObligadoEmision>',
342
+ ` <sf:NombreRazon>${escapeXml(evento.obligadoEmision.nombreRazon)}</sf:NombreRazon>`,
343
+ ` <sf:NIF>${escapeXml(evento.obligadoEmision.nif)}</sf:NIF>`,
344
+ ' </sf:ObligadoEmision>',
345
+ ` <sf:FechaHoraHusoGenEvento>${evento.fechaHoraHusoGenEvento}</sf:FechaHoraHusoGenEvento>`,
346
+ ` <sf:TipoEvento>${escapeXml(evento.tipoEvento)}</sf:TipoEvento>`,
347
+ ...encadenamiento,
348
+ ' <sf:TipoHuella>01</sf:TipoHuella>',
349
+ ` <sf:HuellaEvento>${evento.huellaEvento}</sf:HuellaEvento>`,
350
+ ' </sf:Evento>',
351
+ '</sf:RegistroEvento>',
130
352
  ].join('\n');
131
353
 
132
354
  return xml;
133
355
  }
356
+
357
+ /**
358
+ * Envuelve un elemento de operación Verifactu en el sobre SOAP que la AEAT
359
+ * espera en el envío. El XML de entrada DEBE ser ya el elemento de operación
360
+ * (p. ej. `<RegFactuSistemaFacturacion>` o `<ConsultaFactuSistemaFacturacion>`).
361
+ */
362
+ export function buildRemisionEnvelope(operationXml: string): string {
363
+ const body = operationXml.replace(/^<\?xml[^>]*\?>\s*/, '');
364
+ return [
365
+ '<?xml version="1.0" encoding="UTF-8"?>',
366
+ '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
367
+ ' <soap:Body>',
368
+ body,
369
+ ' </soap:Body>',
370
+ '</soap:Envelope>',
371
+ ].join('\n');
372
+ }
@@ -0,0 +1,125 @@
1
+ import type { Invoice } from '../core/models/invoice.js';
2
+ import { generateInvoiceXml } from '../core/xml/generator.js';
3
+ import { computeRegistroAlta } from '../core/hash/chain.js';
4
+ import { buildQrPayload } from '../core/qr/qr.js';
5
+ import { nowIsoWithOffset } from '../core/utils/date.js';
6
+ import { VerifactuClient } from '../aeat/client.js';
7
+ import { readP12 } from './p12.js';
8
+ import type { VerifactuRepository, StoredRecord } from './repository.js';
9
+
10
+ /**
11
+ * Configuración de la integración de accountability (contabilidad).
12
+ *
13
+ * Se puede aportar el material TLS ya extraído (`cert`/`key`) o el `.p12`
14
+ * en bruto (`p12Buffer` + `p12Password`). El NIF del emisor se aporta
15
+ * siempre en `nif` (la librería no interpreta los campos del certificado).
16
+ */
17
+ export interface AccountabilityConfig {
18
+ /** URL base del servicio AEAT. */
19
+ baseUrl: string;
20
+ /** NIF del emisor. */
21
+ nif: string;
22
+ /** Certificado de cliente en PEM (mTLS). */
23
+ cert?: string;
24
+ /** Clave privada del cliente en PEM (mTLS). */
25
+ key?: string;
26
+ /** Contenido del `.p12` (alternativa a `cert`/`key`). */
27
+ p12Buffer?: Buffer;
28
+ /** Contraseña del `.p12`. */
29
+ p12Password?: string;
30
+ }
31
+
32
+ /**
33
+ * Integración de accountability (contabilidad) para Verifactu.
34
+ *
35
+ * Une las credenciales del certificado (`.p12`) con el cliente mTLS y la
36
+ * persistencia, para registrar facturas de forma verificable ante la AEAT.
37
+ */
38
+ export class AccountabilityService {
39
+ private readonly client: VerifactuClient;
40
+ private readonly nif: string;
41
+
42
+ constructor(
43
+ private readonly repository: VerifactuRepository,
44
+ config: AccountabilityConfig,
45
+ ) {
46
+ let cert: string | undefined;
47
+ let key: string | undefined;
48
+
49
+ if (config.p12Buffer && config.p12Password) {
50
+ const content = readP12(config.p12Buffer, config.p12Password);
51
+ cert = content.certificates[0];
52
+ key = content.keys[0];
53
+ } else if (config.cert && config.key) {
54
+ cert = config.cert;
55
+ key = config.key;
56
+ }
57
+
58
+ if (!cert || !key) {
59
+ throw new Error(
60
+ 'AccountabilityService requiere un .p12 (p12Buffer + p12Password) o cert/key PEM.',
61
+ );
62
+ }
63
+
64
+ this.nif = config.nif;
65
+ this.client = new VerifactuClient({ baseUrl: config.baseUrl, cert, key });
66
+ }
67
+
68
+ /**
69
+ * Registra una factura (alta) ante la AEAT, usando el certificado del
70
+ * emisor para autenticar el envío.
71
+ */
72
+ async registerInvoice(invoice: Invoice): Promise<StoredRecord> {
73
+ // El NIF del emisor se toma del certificado (o del config).
74
+ const invoiceConNif: Invoice = {
75
+ ...invoice,
76
+ emisor: { ...invoice.emisor, nif: this.nif },
77
+ };
78
+
79
+ const last = await this.repository.getLastRecord();
80
+ const previousHash = last?.hash ?? null;
81
+
82
+ const xml = generateInvoiceXml(invoiceConNif, previousHash);
83
+ const fechaHoraHusoGenRegistro = nowIsoWithOffset();
84
+ const hash = computeRegistroAlta({
85
+ idEmisorFactura: this.nif,
86
+ numSerieFactura: `${invoice.id.serie ?? ''}${invoice.id.numero}`,
87
+ fechaExpedicionFactura: invoice.id.fechaExpedicion,
88
+ tipoFactura: invoice.tipoFactura,
89
+ cuotaTotal: invoice.desglose.cuotaTotal.toFixed(2),
90
+ importeTotal: invoice.desglose.importeTotal.toFixed(2),
91
+ huellaAnterior: previousHash,
92
+ fechaHoraHusoGenRegistro,
93
+ });
94
+
95
+ const now = new Date().toISOString();
96
+ const record: StoredRecord = {
97
+ id: `${invoice.id.serie ?? ''}${invoice.id.numero}`,
98
+ invoiceId: `${invoice.id.serie ?? ''}${invoice.id.numero}`,
99
+ emisorNif: this.nif,
100
+ xml,
101
+ hash,
102
+ previousHash,
103
+ qrPayload: buildQrPayload(hash),
104
+ status: 'PENDING',
105
+ createdAt: now,
106
+ updatedAt: now,
107
+ };
108
+ await this.repository.saveRecord(record);
109
+
110
+ const result = await this.client.sendRecord(xml);
111
+ await this.repository.saveResponse({
112
+ id: `${record.id}-${Date.now()}`,
113
+ recordId: record.id,
114
+ operationId: result.operationId,
115
+ status: result.status,
116
+ message: result.message,
117
+ receivedAt: new Date().toISOString(),
118
+ });
119
+
120
+ const status = result.status === 'OK' ? 'CONFIRMED' : 'REJECTED';
121
+ await this.repository.updateRecordStatus(record.id, status);
122
+
123
+ return { ...record, status };
124
+ }
125
+ }
@@ -1,2 +1,4 @@
1
1
  export * from './repository.js';
2
2
  export * from './service.js';
3
+ export * from './p12.js';
4
+ export * from './accountability.js';