@12-apps/fiscal 1.0.0 → 1.2.0

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 (140) hide show
  1. package/README.md +164 -7
  2. package/dist/chunk-2LBQRYPV.js +21 -0
  3. package/dist/chunk-2LBQRYPV.js.map +1 -0
  4. package/dist/chunk-3SDXLSG4.js +24 -0
  5. package/dist/chunk-3SDXLSG4.js.map +1 -0
  6. package/dist/chunk-5S2PJHAE.js +85 -0
  7. package/dist/chunk-5S2PJHAE.js.map +1 -0
  8. package/dist/chunk-G3V7IYNF.js +192 -0
  9. package/dist/chunk-G3V7IYNF.js.map +1 -0
  10. package/dist/chunk-JVQKJNOC.js +14 -0
  11. package/dist/chunk-JVQKJNOC.js.map +1 -0
  12. package/dist/chunk-N5DCKYFR.js +610 -0
  13. package/dist/chunk-N5DCKYFR.js.map +1 -0
  14. package/dist/chunk-NVRYAAQ4.js +212 -0
  15. package/dist/chunk-NVRYAAQ4.js.map +1 -0
  16. package/dist/chunk-PNTKG3DZ.js +47 -0
  17. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  18. package/dist/chunk-WTGASIZE.js +247 -0
  19. package/dist/chunk-WTGASIZE.js.map +1 -0
  20. package/dist/chunk-XQGW5HUG.js +30 -0
  21. package/dist/chunk-XQGW5HUG.js.map +1 -0
  22. package/dist/context-ChnWR4Kb.d.ts +455 -0
  23. package/dist/danfe/en-US.d.ts +12 -0
  24. package/dist/danfe/en-US.js +51 -0
  25. package/dist/danfe/en-US.js.map +1 -0
  26. package/dist/danfe/index.d.ts +50 -0
  27. package/dist/danfe/index.js +18 -0
  28. package/dist/danfe/index.js.map +1 -0
  29. package/dist/danfe/pt-BR.d.ts +11 -0
  30. package/dist/danfe/pt-BR.js +51 -0
  31. package/dist/danfe/pt-BR.js.map +1 -0
  32. package/dist/documents/index.d.ts +181 -0
  33. package/dist/documents/index.js +1234 -0
  34. package/dist/documents/index.js.map +1 -0
  35. package/dist/engine/index.d.ts +3 -246
  36. package/dist/http.d.ts +75 -0
  37. package/dist/http.js +16 -0
  38. package/dist/http.js.map +1 -0
  39. package/dist/issuer/index.d.ts +43 -0
  40. package/dist/issuer/index.js +131 -0
  41. package/dist/issuer/index.js.map +1 -0
  42. package/dist/jobs.d.ts +74 -0
  43. package/dist/jobs.js +22 -0
  44. package/dist/jobs.js.map +1 -0
  45. package/dist/labels-BNvflT0h.d.ts +44 -0
  46. package/dist/manifest/index.d.ts +30 -16
  47. package/dist/manifest/index.js +11 -17
  48. package/dist/manifest/index.js.map +1 -1
  49. package/dist/manifest/server.d.ts +57 -0
  50. package/dist/manifest/server.js +25 -0
  51. package/dist/manifest/server.js.map +1 -0
  52. package/dist/notifications.d.ts +93 -0
  53. package/dist/notifications.js +41 -0
  54. package/dist/notifications.js.map +1 -0
  55. package/dist/port-DpRFK56U.d.ts +238 -0
  56. package/dist/sale/index.d.ts +269 -0
  57. package/dist/sale/index.js +1 -0
  58. package/dist/sale/index.js.map +1 -0
  59. package/dist/service-KTjH7AxW.d.ts +139 -0
  60. package/dist/sidecar/index.d.ts +218 -0
  61. package/dist/sidecar/index.js +8 -0
  62. package/dist/sidecar/index.js.map +1 -0
  63. package/dist/types-B1b8LIWX.d.ts +247 -0
  64. package/package.json +63 -5
  65. package/prisma/fiscal.prisma +158 -0
  66. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  67. package/sidecar/.dockerignore +5 -0
  68. package/sidecar/Dockerfile +68 -0
  69. package/sidecar/README.md +162 -0
  70. package/sidecar/composer.json +30 -0
  71. package/sidecar/composer.lock +2224 -0
  72. package/sidecar/docker/apache.conf +14 -0
  73. package/sidecar/docker/icp-brasil.pem +8031 -0
  74. package/sidecar/docker/mpm.conf +17 -0
  75. package/sidecar/docker/openssl.cnf +16 -0
  76. package/sidecar/docker/php.ini +19 -0
  77. package/sidecar/public/index.php +15 -0
  78. package/sidecar/schema/sale-for-document.schema.json +422 -0
  79. package/sidecar/src/ErrorClass.php +31 -0
  80. package/sidecar/src/Http/Request.php +48 -0
  81. package/sidecar/src/Http/Response.php +32 -0
  82. package/sidecar/src/Http/Router.php +59 -0
  83. package/sidecar/src/Kernel.php +99 -0
  84. package/sidecar/src/Module.php +31 -0
  85. package/sidecar/src/Nfe/Classifier.php +89 -0
  86. package/sidecar/src/Nfe/Credentials.php +52 -0
  87. package/sidecar/src/Nfe/DocumentMapper.php +428 -0
  88. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  89. package/sidecar/src/Nfe/Input.php +125 -0
  90. package/sidecar/src/Nfe/Model.php +17 -0
  91. package/sidecar/src/Nfe/NfeModule.php +62 -0
  92. package/sidecar/src/Nfe/NfeService.php +504 -0
  93. package/sidecar/src/Nfe/Sefaz.php +49 -0
  94. package/sidecar/src/Nfe/SefazReply.php +81 -0
  95. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  96. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  97. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  98. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  99. package/sidecar/src/RequestLog.php +54 -0
  100. package/sidecar/src/ServiceError.php +69 -0
  101. package/src/danfe/en-US.ts +53 -0
  102. package/src/danfe/index.ts +11 -0
  103. package/src/danfe/labels.ts +49 -0
  104. package/src/danfe/pt-BR.ts +52 -0
  105. package/src/danfe/render.ts +265 -0
  106. package/src/danfe/xml.ts +45 -0
  107. package/src/documents/context.ts +260 -0
  108. package/src/documents/errors.ts +48 -0
  109. package/src/documents/helpers.ts +177 -0
  110. package/src/documents/index.ts +40 -0
  111. package/src/documents/lines.ts +63 -0
  112. package/src/documents/machine-steps.ts +260 -0
  113. package/src/documents/machine.ts +128 -0
  114. package/src/documents/memory.ts +138 -0
  115. package/src/documents/nfe-proc.ts +51 -0
  116. package/src/documents/ports.ts +130 -0
  117. package/src/documents/profile-input.ts +168 -0
  118. package/src/documents/profile.ts +98 -0
  119. package/src/documents/service-profile.ts +104 -0
  120. package/src/documents/service.ts +299 -0
  121. package/src/documents/settle.ts +121 -0
  122. package/src/documents/signing.ts +61 -0
  123. package/src/documents/sql-rows.ts +180 -0
  124. package/src/documents/sql-store.ts +242 -0
  125. package/src/documents/sql.ts +18 -0
  126. package/src/documents/steps.ts +173 -0
  127. package/src/documents/tests/integration/pglite.ts +73 -0
  128. package/src/documents/types.ts +193 -0
  129. package/src/http.ts +266 -0
  130. package/src/issuer/index.ts +9 -0
  131. package/src/issuer/port.ts +109 -0
  132. package/src/issuer/sidecar.ts +171 -0
  133. package/src/jobs.ts +115 -0
  134. package/src/manifest/index.ts +25 -16
  135. package/src/manifest/server.ts +20 -0
  136. package/src/notifications.ts +120 -0
  137. package/src/sale/index.ts +8 -0
  138. package/src/sale/types.ts +318 -0
  139. package/src/sidecar/index.ts +9 -0
  140. package/src/sidecar/types.ts +245 -0
@@ -0,0 +1,504 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar\Nfe;
6
+
7
+ use DOMDocument;
8
+ use Fiscal\Sidecar\ErrorClass;
9
+ use Fiscal\Sidecar\Http\Response;
10
+ use Fiscal\Sidecar\Nfe\Transport\Transport;
11
+ use Fiscal\Sidecar\Nfe\Transport\TransportFailure;
12
+ use Fiscal\Sidecar\ServiceError;
13
+ use NFePHP\Common\Certificate;
14
+ use NFePHP\Common\UFList;
15
+ use NFePHP\NFe\Complements;
16
+ use NFePHP\NFe\Tools;
17
+ use Throwable;
18
+
19
+ /**
20
+ * The operations over sped-nfe, one call each. Every call opens its own
21
+ * certificate, builds its own `Tools` and keeps nothing.
22
+ */
23
+ final class NfeService
24
+ {
25
+ /** 100 authorised, 150 authorised late, 120 authorised with a warning (NT 2026.002). */
26
+ private const AUTHORIZED = ['100', '120', '150'];
27
+ private const CANCELLED = ['101', '151', '155'];
28
+ /** Denial of use (the number is spent; the denial is kept like an authorisation). */
29
+ private const DENIED = ['110', '301', '302', '303'];
30
+ private const NOT_FOUND = '217';
31
+ private const EVENT_REGISTERED = ['135', '136', '155'];
32
+ /** 204 "Duplicidade de NF-e" (the key is already authorised), 205 (already denied): a retried issue. */
33
+ private const ALREADY_HELD = ['204', '205'];
34
+ /** 218 "NF-e já está cancelada", 573 "Duplicidade de Evento": a retried cancel. */
35
+ private const ALREADY_CANCELLED = ['218', '573'];
36
+ /** 563 "Já existe pedido de Inutilização com a mesma faixa": a retried inutilização. */
37
+ private const INUTILIZATION_EXISTS = '563';
38
+
39
+ public function __construct(
40
+ private readonly Transport $transport,
41
+ private readonly DocumentMapper $mapper = new DocumentMapper(),
42
+ ) {
43
+ }
44
+
45
+ /** `POST /<model>/issue`: build, sign, transmit. */
46
+ public function issue(Model $model, Input $in): Response
47
+ {
48
+ [$environment, $csc, $document, $certificate] = $this->issueInputs($model, $in);
49
+ $built = $this->mapper->build($document, $model, $environment);
50
+ $tools = $this->toolsForDocument($certificate, $model, $environment, $document, $csc);
51
+ $signed = $this->sign($tools, $built['xml'], $built['accessKey']);
52
+ return $this->transmitSigned($tools, $signed, $built['accessKey'], true, $model === Model::NFCE);
53
+ }
54
+
55
+ /** `POST /nfce/sign-contingency`: build and sign with `tpEmis = 9`; nothing is sent. */
56
+ public function signContingency(Input $in): Response
57
+ {
58
+ [$environment, $csc, $document, $certificate] = $this->issueInputs(Model::NFCE, $in);
59
+ $contingency = $in->contingency();
60
+ $built = $this->mapper->build($document, Model::NFCE, $environment, $contingency);
61
+ $tools = $this->toolsForDocument($certificate, Model::NFCE, $environment, $document, $csc);
62
+ $signed = $this->sign($tools, $built['xml'], $built['accessKey']);
63
+ return new Response(200, ['status' => 'SIGNED', 'accessKey' => $built['accessKey'], 'signedXml' => $signed]);
64
+ }
65
+
66
+ /** `POST /<model>/transmit`: an XML signed earlier (offline, say). It never goes offline again. */
67
+ public function transmit(Model $model, Input $in): Response
68
+ {
69
+ $environment = $in->environment();
70
+ $signed = $in->text('signedXml', 100, 5_000_000);
71
+ $facts = self::signedFacts($signed, $model);
72
+ $certificate = Credentials::open($in->certificate());
73
+ $tools = Sefaz::tools($this->transport, $certificate, $model, $environment, $facts['uf'], $facts['cnpj'], null);
74
+ return $this->transmitSigned($tools, $signed, $facts['accessKey'], false, false);
75
+ }
76
+
77
+ /**
78
+ * `POST /<model>/cancel`. A cancel SEFAZ already holds (218 already
79
+ * cancelled, 573 duplicate event) and one sent with no answer are settled
80
+ * by looking the key up: a retried cancel answers CANCELLED, as the first did.
81
+ */
82
+ public function cancel(Model $model, Input $in): Response
83
+ {
84
+ $environment = $in->environment();
85
+ $key = self::keyOf($model, $in);
86
+ $protocol = $in->pattern('protocol', '/^[0-9]{15}$/', 'the 15-digit authorisation protocol');
87
+ $reason = $in->text('reason', 15, 255);
88
+ $tools = $this->toolsForKey($in, $model, $environment, $key);
89
+ return $this->sendCancel($tools, $key, fn (): string => $tools->sefazCancela($key, $reason, $protocol));
90
+ }
91
+
92
+ /**
93
+ * `POST /nfce/cancel-substitution`: the NFC-e "cancelamento por
94
+ * substituição" (event 110112). Cancels an online NFC-e found authorised
95
+ * after its sale was issued again in contingency, naming the substitute's
96
+ * key (`chNFeRef`). Settled like an ordinary cancel when retried.
97
+ */
98
+ public function cancelBySubstitution(Input $in): Response
99
+ {
100
+ $environment = $in->environment();
101
+ $key = self::keyOf(Model::NFCE, $in);
102
+ $substitute = $in->accessKey('substituteAccessKey');
103
+ if ((int) substr($substitute, 20, 2) !== Model::NFCE->code()) {
104
+ throw ServiceError::invalid('substituteAccessKey is not of a model 65 document.');
105
+ }
106
+ if ($substitute === $key) {
107
+ throw ServiceError::invalid('substituteAccessKey must be another document\'s key.');
108
+ }
109
+ $protocol = $in->pattern('protocol', '/^[0-9]{15}$/', 'the 15-digit authorisation protocol');
110
+ $reason = $in->text('reason', 15, 255);
111
+ $tools = $this->toolsForKey($in, Model::NFCE, $environment, $key);
112
+ return $this->sendCancel(
113
+ $tools,
114
+ $key,
115
+ fn (): string => $tools->sefazCancelaPorSubstituicao($key, $reason, $protocol, $substitute, DocumentMapper::PROCESS_VERSION),
116
+ );
117
+ }
118
+
119
+ /** One cancel event, sent and settled: 218/573 and a request with no answer are looked up. */
120
+ private function sendCancel(Tools $tools, string $key, callable $send): Response
121
+ {
122
+ try {
123
+ $reply = $this->exchange($send);
124
+ } catch (TransportFailure $failure) {
125
+ if ($failure->kind !== TransportFailure::NO_ANSWER) {
126
+ throw Classifier::fromTransport($failure, false);
127
+ }
128
+ return $this->cancelSettledByLookup($tools, $key, null);
129
+ }
130
+ $status = $reply->status() === '128' ? (string) $reply->value('cStat', 'infEvento') : $reply->status();
131
+ if (in_array($status, self::ALREADY_CANCELLED, true)) {
132
+ return $this->cancelSettledByLookup($tools, $key, Classifier::fromStatus($status, self::reasonOf($reply, 'infEvento'), $reply, false));
133
+ }
134
+ if (!in_array($status, self::EVENT_REGISTERED, true)) {
135
+ throw Classifier::fromStatus($status, self::reasonOf($reply, 'infEvento'), $reply, false);
136
+ }
137
+ return new Response(200, self::answer($reply, $status, 'infEvento') + [
138
+ 'status' => 'CANCELLED',
139
+ 'accessKey' => $key,
140
+ 'protocol' => (string) $reply->value('nProt', 'infEvento'),
141
+ 'registeredAt' => (string) $reply->value('dhRegEvento', 'infEvento'),
142
+ 'eventXml' => self::protocolled($tools->lastRequest, $reply->raw),
143
+ ]);
144
+ }
145
+
146
+ /** `POST /<model>/lookup`. */
147
+ public function lookup(Model $model, Input $in): Response
148
+ {
149
+ $environment = $in->environment();
150
+ $key = self::keyOf($model, $in);
151
+ $tools = $this->toolsForKey($in, $model, $environment, $key);
152
+ $reply = $this->settled(fn (): string => $tools->sefazConsultaChave($key), false);
153
+ $status = $reply->status();
154
+ $state = match (true) {
155
+ in_array($status, self::AUTHORIZED, true) => 'AUTHORIZED',
156
+ in_array($status, self::CANCELLED, true) => 'CANCELLED',
157
+ in_array($status, self::DENIED, true) => 'DENIED',
158
+ $status === self::NOT_FOUND => 'NOT_FOUND',
159
+ default => throw Classifier::fromStatus($status, $reply->reason(), $reply, false),
160
+ };
161
+ return new Response(200, self::answer($reply, $status, null) + [
162
+ 'status' => $state,
163
+ 'accessKey' => $key,
164
+ 'protocol' => $reply->value('nProt', 'protNFe'),
165
+ ]);
166
+ }
167
+
168
+ /**
169
+ * `POST /inutilize`. 563 ("a request for the same range already exists")
170
+ * is what a retried inutilização gets once the first went through, so it
171
+ * answers INUTILIZED too, with no protocol of its own: the range is void at
172
+ * SEFAZ either way, and SEFAZ offers no query that would return the first
173
+ * protocol. A request sent with no answer is RETRYABLE: resending is safe.
174
+ */
175
+ public function inutilize(Input $in): Response
176
+ {
177
+ $environment = $in->environment();
178
+ $model = Model::from($in->pattern('model', '/^(nfe|nfce)$/', '"nfe" or "nfce"'));
179
+ $uf = $in->pattern('uf', '/^[A-Z]{2}$/', 'a two-letter UF');
180
+ $cnpj = $in->pattern('cnpj', '/^[A-Z0-9]{12}[0-9]{2}$/', 'a 14-character CNPJ');
181
+ $year = $in->digits('year', 2000, 2099);
182
+ $series = $in->digits('series', 0, 999);
183
+ $from = $in->digits('from', 1, 999999999);
184
+ $to = $in->digits('to', $from, 999999999);
185
+ $reason = $in->text('reason', 15, 255);
186
+ $certificate = Credentials::open($in->certificate());
187
+ $tools = Sefaz::tools($this->transport, $certificate, $model, $environment, $uf, $cnpj, null);
188
+ $reply = $this->settled(
189
+ fn (): string => $tools->sefazInutiliza($series, $from, $to, $reason, $environment, substr((string) $year, 2)),
190
+ false,
191
+ );
192
+ $status = $reply->status();
193
+ if ($status === self::INUTILIZATION_EXISTS) {
194
+ return new Response(200, self::answer($reply, $status, null) + [
195
+ 'status' => 'INUTILIZED',
196
+ 'protocol' => null,
197
+ 'registeredAt' => $reply->value('dhRecbto'),
198
+ 'inutilizationXml' => null,
199
+ ]);
200
+ }
201
+ if ($status !== '102') {
202
+ throw Classifier::fromStatus($status, $reply->reason(), $reply, false);
203
+ }
204
+ return new Response(200, self::answer($reply, '102', null) + [
205
+ 'status' => 'INUTILIZED',
206
+ 'protocol' => (string) $reply->value('nProt'),
207
+ 'registeredAt' => (string) $reply->value('dhRecbto'),
208
+ 'inutilizationXml' => self::protocolled($tools->lastRequest, $reply->raw),
209
+ ]);
210
+ }
211
+
212
+ /** @return array{0: int, 1: array{id: string, token: string}|null, 2: array<string, mixed>, 3: Certificate} */
213
+ private function issueInputs(Model $model, Input $in): array
214
+ {
215
+ $environment = $in->environment();
216
+ $csc = $in->csc($model);
217
+ $document = $in->document();
218
+ return [$environment, $csc, $document, Credentials::open($in->certificate())];
219
+ }
220
+
221
+ /**
222
+ * @param array<string, mixed> $document
223
+ * @param array{id: string, token: string}|null $csc
224
+ */
225
+ private function toolsForDocument(
226
+ Certificate $certificate,
227
+ Model $model,
228
+ int $environment,
229
+ array $document,
230
+ ?array $csc,
231
+ ): Tools {
232
+ $issuer = $document['issuer'];
233
+ return $this->library(fn (): Tools => Sefaz::tools(
234
+ $this->transport,
235
+ $certificate,
236
+ $model,
237
+ $environment,
238
+ $issuer['address']['uf'],
239
+ $issuer['cnpj'],
240
+ $csc,
241
+ ));
242
+ }
243
+
244
+ private function toolsForKey(Input $in, Model $model, int $environment, string $key): Tools
245
+ {
246
+ $certificate = Credentials::open($in->certificate());
247
+ $uf = UFList::getUFByCode((int) substr($key, 0, 2));
248
+ return Sefaz::tools($this->transport, $certificate, $model, $environment, $uf, substr($key, 6, 14), null);
249
+ }
250
+
251
+ private function sign(Tools $tools, string $xml, string $accessKey): string
252
+ {
253
+ try {
254
+ return $this->library(fn (): string => $tools->signNFe($xml));
255
+ } catch (ServiceError $error) {
256
+ throw $error->withDocument($accessKey, null);
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Sends a signed document and answers what SEFAZ decided. When the answer
262
+ * says SEFAZ already holds the key (204 authorised, 205 denied) or the
263
+ * request went out with no answer, the key is looked up and THAT is the
264
+ * answer, so a retry never turns an authorised document into a rejection.
265
+ *
266
+ * @param bool $issuing the `/issue` endpoint: SEFAZ stopped (108, 109) is CONTINGENCY there
267
+ * @param bool $offlineAllowed issuing an NFC-e: nothing reached SEFAZ is CONTINGENCY there
268
+ */
269
+ private function transmitSigned(Tools $tools, string $signed, string $accessKey, bool $issuing, bool $offlineAllowed): Response
270
+ {
271
+ $batch = substr($accessKey, 22, 15);
272
+ try {
273
+ $reply = $this->exchange(fn (): string => $tools->sefazEnviaLote([$signed], $batch, 1));
274
+ } catch (TransportFailure $failure) {
275
+ if ($failure->kind === TransportFailure::NO_ANSWER) {
276
+ return $this->issueSettledByLookup($tools, $signed, $accessKey, $offlineAllowed, true);
277
+ }
278
+ throw Classifier::fromTransport($failure, $offlineAllowed)->withDocument($accessKey, $signed);
279
+ } catch (ServiceError $error) {
280
+ throw $error->withDocument($accessKey, $signed);
281
+ }
282
+ $processed = $reply->status() === '104' && $reply->has('infProt');
283
+ $status = $processed ? (string) $reply->value('cStat', 'infProt') : $reply->status();
284
+ if (in_array($status, self::AUTHORIZED, true) || in_array($status, self::DENIED, true)) {
285
+ return self::issued($reply, $status, $signed, $accessKey, null);
286
+ }
287
+ if (in_array($status, self::ALREADY_HELD, true)) {
288
+ return $this->issueSettledByLookup($tools, $signed, $accessKey, $offlineAllowed, false);
289
+ }
290
+ throw Classifier::fromStatus($status, self::reasonOf($reply, $processed ? 'infProt' : null), $reply, $issuing)
291
+ ->withDocument($accessKey, $signed);
292
+ }
293
+
294
+ /**
295
+ * The key looked up, after a 204/205 or a request with no answer. SEFAZ's
296
+ * answer is final; only when the lookup itself cannot reach SEFAZ does an
297
+ * NFC-e being issued go offline (owner's ruling: look up first, never a
298
+ * blind contingency that could put a second document on the same sale).
299
+ */
300
+ private function issueSettledByLookup(
301
+ Tools $tools,
302
+ string $signed,
303
+ string $accessKey,
304
+ bool $offlineAllowed,
305
+ bool $afterNoAnswer,
306
+ ): Response {
307
+ try {
308
+ $lookup = $this->exchange(fn (): string => $tools->sefazConsultaChave($accessKey));
309
+ } catch (TransportFailure $failure) {
310
+ throw self::unsettled($failure, $offlineAllowed, $afterNoAnswer)->withDocument($accessKey, $signed);
311
+ } catch (ServiceError $error) {
312
+ throw $error->withDocument($accessKey, $signed);
313
+ }
314
+ $status = $lookup->status();
315
+ if (in_array($status, self::AUTHORIZED, true) || in_array($status, self::DENIED, true)) {
316
+ return self::issued($lookup, $status, $signed, $accessKey, 'protNFe');
317
+ }
318
+ if ($status === self::NOT_FOUND) {
319
+ throw (new ServiceError(
320
+ ErrorClass::RETRYABLE,
321
+ 'SEFAZ holds no document under this key: it never received it, so send it again.',
322
+ $status,
323
+ [],
324
+ null,
325
+ null,
326
+ $lookup->raw,
327
+ ))->withDocument($accessKey, $signed);
328
+ }
329
+ throw Classifier::fromStatus($status, $lookup->reason(), $lookup, false)->withDocument($accessKey, $signed);
330
+ }
331
+
332
+ /** A cancel settled by the key's state, after 218/573 (`$original`) or a request with no answer (null). */
333
+ private function cancelSettledByLookup(Tools $tools, string $key, ?ServiceError $original): Response
334
+ {
335
+ try {
336
+ $lookup = $this->exchange(fn (): string => $tools->sefazConsultaChave($key));
337
+ } catch (TransportFailure $failure) {
338
+ throw $original ?? self::unsettled($failure, false, true);
339
+ }
340
+ $status = $lookup->status();
341
+ if (!in_array($status, self::CANCELLED, true)) {
342
+ throw $original ?? new ServiceError(
343
+ ErrorClass::RETRYABLE,
344
+ "The cancel got no answer and SEFAZ still reports [$status] {$lookup->reason()}: send it again.",
345
+ $status,
346
+ [],
347
+ null,
348
+ null,
349
+ $lookup->raw,
350
+ );
351
+ }
352
+ return new Response(200, self::answer($lookup, $status, null) + [
353
+ 'status' => 'CANCELLED',
354
+ 'accessKey' => $key,
355
+ 'protocol' => $lookup->value('nProt', 'retEvento'),
356
+ 'registeredAt' => $lookup->value('dhRegEvento', 'retEvento'),
357
+ 'eventXml' => $lookup->element('procEventoNFe'),
358
+ ]);
359
+ }
360
+
361
+ /** The lookup that would settle an outcome could not reach SEFAZ either. */
362
+ private static function unsettled(TransportFailure $failure, bool $offlineAllowed, bool $afterNoAnswer): ServiceError
363
+ {
364
+ if ($failure->kind === TransportFailure::TLS_REFUSED) {
365
+ return Classifier::fromTransport($failure, false);
366
+ }
367
+ return new ServiceError(
368
+ $offlineAllowed ? ErrorClass::CONTINGENCY : ErrorClass::RETRYABLE,
369
+ ($afterNoAnswer ? 'The request went out with no answer, and ' : '')
370
+ . 'the lookup that would settle it could not reach SEFAZ (' . $failure->getMessage() . ').',
371
+ outcomeUnknown: $afterNoAnswer,
372
+ );
373
+ }
374
+
375
+ /** `AUTHORIZED` or `DENIED`, with the protocol from the reply's `$group` (`infProt` when null). */
376
+ private static function issued(SefazReply $reply, string $status, string $signed, string $accessKey, ?string $group): Response
377
+ {
378
+ $group ??= 'infProt';
379
+ $sefazDigest = $reply->value('digVal', $group);
380
+ if ($sefazDigest !== null && $sefazDigest !== self::digestOf($signed)) {
381
+ throw (new ServiceError(
382
+ ErrorClass::REJECTED,
383
+ 'SEFAZ holds a DIFFERENT document under this key (its digest is not this XML\'s).',
384
+ $status,
385
+ [],
386
+ null,
387
+ null,
388
+ $reply->raw,
389
+ ))->withDocument($accessKey, $signed);
390
+ }
391
+ return new Response(200, self::answer($reply, $status, $group) + [
392
+ 'status' => in_array($status, self::DENIED, true) ? 'DENIED' : 'AUTHORIZED',
393
+ 'accessKey' => $accessKey,
394
+ 'protocol' => (string) $reply->value('nProt', $group),
395
+ 'authorizedAt' => (string) $reply->value('dhRecbto', $group),
396
+ 'signedXml' => $signed,
397
+ 'authorizedXml' => self::protocolled($signed, $reply->raw),
398
+ ]);
399
+ }
400
+
401
+ private static function digestOf(string $signed): ?string
402
+ {
403
+ return preg_match('#<DigestValue>([^<]+)</DigestValue>#', $signed, $match) === 1 ? $match[1] : null;
404
+ }
405
+
406
+ /**
407
+ * One request to SEFAZ, its reply read. A transport failure is thrown as
408
+ * is, for the caller to decide (a lookup first, or a class).
409
+ *
410
+ * @param callable(): string $call
411
+ */
412
+ private function exchange(callable $call): SefazReply
413
+ {
414
+ return SefazReply::parse($this->library($call));
415
+ }
416
+
417
+ /**
418
+ * An exchange whose transport failure is final: classified, never settled.
419
+ *
420
+ * @param callable(): string $call
421
+ */
422
+ private function settled(callable $call, bool $offlineAllowed): SefazReply
423
+ {
424
+ try {
425
+ return $this->exchange($call);
426
+ } catch (TransportFailure $failure) {
427
+ throw Classifier::fromTransport($failure, $offlineAllowed);
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Runs a sped-nfe call, sorting what it throws: the transport's failures
433
+ * pass through to be classified; a certificate the library finds expired is
434
+ * AUTH; what the library refuses about the input is INVALID.
435
+ *
436
+ * @template T
437
+ * @param callable(): T $call
438
+ * @return T
439
+ */
440
+ private function library(callable $call): mixed
441
+ {
442
+ try {
443
+ return $call();
444
+ } catch (TransportFailure | ServiceError $passThrough) {
445
+ throw $passThrough;
446
+ } catch (\NFePHP\Common\Certificate\Exception\Expired) {
447
+ throw new ServiceError(ErrorClass::AUTH, 'The certificate has expired.');
448
+ } catch (Throwable $refused) {
449
+ throw ServiceError::invalid('sped-nfe refused the request.', [$refused->getMessage()]);
450
+ }
451
+ }
452
+
453
+ /** @return array{statusCode: string, statusReason: string, sefazReply: string} */
454
+ private static function answer(SefazReply $reply, string $status, ?string $group): array
455
+ {
456
+ return ['statusCode' => $status, 'statusReason' => self::reasonOf($reply, $group), 'sefazReply' => $reply->raw];
457
+ }
458
+
459
+ private static function reasonOf(SefazReply $reply, ?string $group): string
460
+ {
461
+ return (string) ($group === null ? $reply->reason() : $reply->value('xMotivo', $group));
462
+ }
463
+
464
+ private static function protocolled(string $request, string $reply): string
465
+ {
466
+ try {
467
+ return Complements::toAuthorize($request, $reply);
468
+ } catch (Throwable $failure) {
469
+ throw new ServiceError(
470
+ ErrorClass::RETRYABLE,
471
+ 'SEFAZ accepted the request but its reply could not be attached to it: ' . $failure->getMessage(),
472
+ );
473
+ }
474
+ }
475
+
476
+ private static function keyOf(Model $model, Input $in): string
477
+ {
478
+ $key = $in->accessKey();
479
+ if ((int) substr($key, 20, 2) !== $model->code()) {
480
+ throw ServiceError::invalid("The access key is not of a model {$model->code()} document.");
481
+ }
482
+ return $key;
483
+ }
484
+
485
+ /** @return array{accessKey: string, uf: string, cnpj: string} */
486
+ private static function signedFacts(string $signed, Model $model): array
487
+ {
488
+ $dom = new DOMDocument();
489
+ $previous = libxml_use_internal_errors(true);
490
+ $loaded = $dom->loadXML($signed, LIBXML_NONET);
491
+ libxml_clear_errors();
492
+ libxml_use_internal_errors($previous);
493
+ $infNFe = $loaded ? $dom->getElementsByTagName('infNFe')->item(0) : null;
494
+ $signature = $loaded ? $dom->getElementsByTagName('Signature')->item(0) : null;
495
+ if (!$infNFe instanceof \DOMElement || $signature === null) {
496
+ throw ServiceError::invalid('signedXml must be a signed NFe XML.');
497
+ }
498
+ $key = substr($infNFe->getAttribute('Id'), 3);
499
+ if (strlen($key) !== 44 || (int) substr($key, 20, 2) !== $model->code()) {
500
+ throw ServiceError::invalid("signedXml is not a model {$model->code()} document.");
501
+ }
502
+ return ['accessKey' => $key, 'uf' => UFList::getUFByCode((int) substr($key, 0, 2)), 'cnpj' => substr($key, 6, 14)];
503
+ }
504
+ }
@@ -0,0 +1,49 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar\Nfe;
6
+
7
+ use Fiscal\Sidecar\Nfe\Transport\SoapAdapter;
8
+ use Fiscal\Sidecar\Nfe\Transport\Transport;
9
+ use NFePHP\Common\Certificate;
10
+ use NFePHP\NFe\Tools;
11
+
12
+ /**
13
+ * One sped-nfe `Tools`, built for one call: its config, the call's
14
+ * certificate and CSC, and the transport. Nothing here is cached; the next
15
+ * call builds its own.
16
+ */
17
+ final class Sefaz
18
+ {
19
+ /**
20
+ * @param array{id: string, token: string}|null $csc
21
+ */
22
+ public static function tools(
23
+ Transport $transport,
24
+ Certificate $certificate,
25
+ Model $model,
26
+ int $environment,
27
+ string $uf,
28
+ string $cnpj,
29
+ ?array $csc,
30
+ ): Tools {
31
+ $config = [
32
+ 'atualizacao' => null,
33
+ 'tpAmb' => $environment,
34
+ 'razaosocial' => $certificate->getCompanyName() ?: $cnpj,
35
+ 'cnpj' => $cnpj,
36
+ 'siglaUF' => $uf,
37
+ 'schemes' => NfeModule::SCHEMES,
38
+ 'versao' => '4.00',
39
+ 'tokenIBPT' => null,
40
+ 'CSC' => $csc['token'] ?? null,
41
+ 'CSCid' => $csc['id'] ?? null,
42
+ 'aProxyConf' => null,
43
+ ];
44
+ $tools = new Tools((string) json_encode($config), $certificate);
45
+ $tools->model($model->code());
46
+ $tools->loadSoapClass(new SoapAdapter($transport, $certificate));
47
+ return $tools;
48
+ }
49
+ }
@@ -0,0 +1,81 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar\Nfe;
6
+
7
+ use DOMDocument;
8
+ use DOMElement;
9
+ use Fiscal\Sidecar\ErrorClass;
10
+ use Fiscal\Sidecar\ServiceError;
11
+
12
+ /** What SEFAZ answered, read: the status of the reply and of the group inside it. */
13
+ final class SefazReply
14
+ {
15
+ private function __construct(
16
+ public readonly string $raw,
17
+ private readonly DOMDocument $dom,
18
+ ) {
19
+ }
20
+
21
+ public static function parse(string $raw): self
22
+ {
23
+ $dom = new DOMDocument();
24
+ $previous = libxml_use_internal_errors(true);
25
+ $loaded = $raw !== '' && $dom->loadXML($raw, LIBXML_NONET);
26
+ libxml_clear_errors();
27
+ libxml_use_internal_errors($previous);
28
+ if (!$loaded || $dom->getElementsByTagName('cStat')->length === 0) {
29
+ throw new ServiceError(
30
+ ErrorClass::RETRYABLE,
31
+ 'SEFAZ answered with no status the service can read.',
32
+ null,
33
+ [],
34
+ null,
35
+ null,
36
+ $raw,
37
+ );
38
+ }
39
+ return new self($raw, $dom);
40
+ }
41
+
42
+ /** `cStat` of the reply's own envelope (the first in document order). */
43
+ public function status(): string
44
+ {
45
+ return $this->value('cStat') ?? '';
46
+ }
47
+
48
+ public function reason(): string
49
+ {
50
+ return $this->value('xMotivo') ?? '';
51
+ }
52
+
53
+ /** The first `$tag` inside the first `$group`, or of the whole reply when `$group` is null. */
54
+ public function value(string $tag, ?string $group = null): ?string
55
+ {
56
+ $scope = $group === null ? $this->dom : $this->group($group);
57
+ if ($scope === null) {
58
+ return null;
59
+ }
60
+ $node = $scope->getElementsByTagName($tag)->item(0);
61
+ return $node === null ? null : trim($node->nodeValue ?? '');
62
+ }
63
+
64
+ /** The first `$tag` element, serialised, or null. */
65
+ public function element(string $tag): ?string
66
+ {
67
+ $node = $this->group($tag);
68
+ return $node === null ? null : (string) $this->dom->saveXML($node);
69
+ }
70
+
71
+ public function has(string $group): bool
72
+ {
73
+ return $this->group($group) !== null;
74
+ }
75
+
76
+ private function group(string $group): ?DOMElement
77
+ {
78
+ $node = $this->dom->getElementsByTagName($group)->item(0);
79
+ return $node instanceof DOMElement ? $node : null;
80
+ }
81
+ }