@12-apps/fiscal 1.0.0 → 1.1.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 +152 -7
  2. package/dist/chunk-27B4HNO6.js +574 -0
  3. package/dist/chunk-27B4HNO6.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-ALABGVPO.js +247 -0
  7. package/dist/chunk-ALABGVPO.js.map +1 -0
  8. package/dist/chunk-FOFIN5M7.js +14 -0
  9. package/dist/chunk-FOFIN5M7.js.map +1 -0
  10. package/dist/chunk-HQ2NXSTX.js +85 -0
  11. package/dist/chunk-HQ2NXSTX.js.map +1 -0
  12. package/dist/chunk-PNTKG3DZ.js +47 -0
  13. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  14. package/dist/chunk-RRFKYVLZ.js +192 -0
  15. package/dist/chunk-RRFKYVLZ.js.map +1 -0
  16. package/dist/chunk-V5ZQAAJT.js +210 -0
  17. package/dist/chunk-V5ZQAAJT.js.map +1 -0
  18. package/dist/chunk-X6MRDUYH.js +21 -0
  19. package/dist/chunk-X6MRDUYH.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 +169 -0
  33. package/dist/documents/index.js +1228 -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 +73 -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 +243 -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 +216 -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 +149 -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 +401 -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 +383 -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 +41 -0
  109. package/src/documents/helpers.ts +128 -0
  110. package/src/documents/index.ts +39 -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 +296 -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 +264 -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 +292 -0
  139. package/src/sidecar/index.ts +9 -0
  140. package/src/sidecar/types.ts +243 -0
@@ -0,0 +1,198 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar\Nfe\Transport;
6
+
7
+ use NFePHP\Common\Certificate;
8
+
9
+ /**
10
+ * cURL with the client certificate handed over IN MEMORY (`CURLOPT_SSLCERT_BLOB`,
11
+ * `CURLOPT_SSLKEY_BLOB`). sped-common's own SoapCurl writes the private key to
12
+ * a temporary folder to give cURL a path; this transport is why the service
13
+ * writes nothing to disk.
14
+ *
15
+ * SEFAZ's server certificate is VERIFIED by default, against a bundle of the
16
+ * public (Mozilla) roots and the ICP-Brasil chain: some SEFAZ hosts present an
17
+ * ICP-Brasil server certificate, others a public one. Unverified, anyone on the
18
+ * path could read every document and forge SEFAZ's answers (a `100` for a
19
+ * document never sent). `FISCAL_SEFAZ_TLS_VERIFY=off` is the only way off, and
20
+ * `/health` says so.
21
+ */
22
+ final class CurlTransport implements Transport
23
+ {
24
+ /** Where the image puts the Mozilla bundle plus `docker/icp-brasil.pem` (see the Dockerfile). */
25
+ public const IMAGE_CA_BUNDLE = '/etc/ssl/fiscal-sidecar-ca.pem';
26
+ /** The ICP-Brasil chain committed beside the Dockerfile, for a run outside the image. */
27
+ public const ICP_BRASIL_PEM = __DIR__ . '/../../../docker/icp-brasil.pem';
28
+
29
+ /**
30
+ * @param int $timeoutSeconds to connect, TLS handshake included
31
+ * @param int|null $answerSeconds for the whole request; default 20 s more than the connect
32
+ */
33
+ public function __construct(
34
+ private readonly int $timeoutSeconds = 30,
35
+ private readonly bool $verify = true,
36
+ private readonly ?string $caBundle = null,
37
+ private readonly ?int $answerSeconds = null,
38
+ ) {
39
+ }
40
+
41
+ /**
42
+ * `FISCAL_SEFAZ_TIMEOUT_SECONDS` (default 30), `FISCAL_SEFAZ_TLS_VERIFY`
43
+ * (`off` disables verification; anything else, or unset, keeps it) and
44
+ * `FISCAL_SEFAZ_CA_BUNDLE` (a PEM path replacing the default bundle).
45
+ */
46
+ public static function fromEnvironment(): self
47
+ {
48
+ $timeout = (int) (getenv('FISCAL_SEFAZ_TIMEOUT_SECONDS') ?: 30);
49
+ $ca = getenv('FISCAL_SEFAZ_CA_BUNDLE');
50
+ return new self(
51
+ $timeout > 0 ? $timeout : 30,
52
+ self::verifiesFromEnvironment(),
53
+ is_string($ca) && $ca !== '' ? $ca : null,
54
+ );
55
+ }
56
+
57
+ public static function verifiesFromEnvironment(): bool
58
+ {
59
+ return strtolower(trim((string) getenv('FISCAL_SEFAZ_TLS_VERIFY'))) !== 'off';
60
+ }
61
+
62
+ public function verifies(): bool
63
+ {
64
+ return $this->verify;
65
+ }
66
+
67
+ public function verifiesServer(): bool
68
+ {
69
+ return $this->verify;
70
+ }
71
+
72
+ /**
73
+ * Every cURL option of one request — public so a test can read what is set.
74
+ *
75
+ * @return array<int, mixed>
76
+ */
77
+ public function options(string $url, string $action, string $envelope, Certificate $certificate): array
78
+ {
79
+ $options = [
80
+ CURLOPT_URL => $url,
81
+ CURLOPT_POST => true,
82
+ CURLOPT_POSTFIELDS => $envelope,
83
+ CURLOPT_HTTPHEADER => [
84
+ 'Content-Type: application/soap+xml;charset=utf-8;' . ($action !== '' ? "action=$action" : ''),
85
+ 'Content-Length: ' . strlen($envelope),
86
+ ],
87
+ CURLOPT_RETURNTRANSFER => true,
88
+ CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
89
+ CURLOPT_CONNECTTIMEOUT => $this->timeoutSeconds,
90
+ CURLOPT_TIMEOUT => $this->answerSeconds ?? $this->timeoutSeconds + 20,
91
+ CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
92
+ CURLOPT_SSLCERTTYPE => 'PEM',
93
+ CURLOPT_SSLCERT_BLOB => (string) $certificate,
94
+ CURLOPT_SSLKEYTYPE => 'PEM',
95
+ CURLOPT_SSLKEY_BLOB => (string) $certificate->privateKey,
96
+ CURLOPT_SSL_VERIFYPEER => $this->verify,
97
+ CURLOPT_SSL_VERIFYHOST => $this->verify ? 2 : 0,
98
+ ];
99
+ if ($this->verify) {
100
+ $options += $this->trustAnchors();
101
+ }
102
+ return $options;
103
+ }
104
+
105
+ public function post(string $url, string $action, string $envelope, Certificate $certificate): string
106
+ {
107
+ $curl = curl_init();
108
+ curl_setopt_array($curl, $this->options($url, $action, $envelope, $certificate));
109
+ $body = curl_exec($curl);
110
+ $failure = self::classify(
111
+ curl_errno($curl),
112
+ curl_error($curl),
113
+ (float) curl_getinfo($curl, CURLINFO_SIZE_UPLOAD),
114
+ (int) curl_getinfo($curl, CURLINFO_HTTP_CODE),
115
+ (int) curl_getinfo($curl, CURLINFO_HTTP_CONNECTCODE),
116
+ $this->verify,
117
+ is_string($body) ? $body : '',
118
+ );
119
+ curl_close($curl);
120
+ if ($failure !== null) {
121
+ throw $failure;
122
+ }
123
+ return trim((string) $body);
124
+ }
125
+
126
+ /**
127
+ * What went wrong, from what cURL reports: whether the body went out
128
+ * (`$uploaded` bytes), the error, the HTTP status, the proxy's CONNECT status.
129
+ * `null` is a 200. `$body` is what the SERVER answered (never request data):
130
+ * an HTTP failure quotes its IIS substatus or a short snippet of it, so a
131
+ * 403.6 (an IP block) reads differently from a 403.7 (no client certificate).
132
+ */
133
+ public static function classify(
134
+ int $errno,
135
+ string $error,
136
+ float $uploaded,
137
+ int $status,
138
+ int $proxyConnect,
139
+ bool $verified,
140
+ string $body = '',
141
+ ): ?TransportFailure {
142
+ $sent = $uploaded > 0;
143
+ if ($errno === 0) {
144
+ $said = 'HTTP ' . self::httpDetail($status, $body);
145
+ return match (true) {
146
+ $status === 200 => null,
147
+ $status === 403 && $verified => new TransportFailure(TransportFailure::TLS_REFUSED, 403, "$said from SEFAZ"),
148
+ $status >= 500 => new TransportFailure(TransportFailure::NO_ANSWER, $status, $said),
149
+ $verified && $status >= 400 && !in_array($status, [408, 429], true)
150
+ => new TransportFailure(TransportFailure::SEFAZ_HTTP, $status, "$said from SEFAZ"),
151
+ default => new TransportFailure(TransportFailure::REFUSED, $status, $said),
152
+ };
153
+ }
154
+ $refusedCertificate = preg_match('/alert|certificate (required|unknown|revoked|expired)|bad certificate|unknown ca/i', $error) === 1;
155
+ return match (true) {
156
+ $proxyConnect !== 0 && $proxyConnect !== 200 => new TransportFailure(TransportFailure::NOT_SENT, null, "proxy CONNECT answered $proxyConnect"),
157
+ $errno === CURLE_SSL_CERTPROBLEM => new TransportFailure(TransportFailure::TLS_REFUSED, null, 'cURL could not use the client certificate'),
158
+ in_array($errno, [CURLE_SSL_CONNECT_ERROR, CURLE_RECV_ERROR], true) && $refusedCertificate
159
+ => new TransportFailure(TransportFailure::TLS_REFUSED, null, "cURL error $errno: the client certificate was refused"),
160
+ $errno === 60 /* CURLE_PEER_FAILED_VERIFICATION */ || $errno === 77 /* CURLE_SSL_CACERT_BADFILE */
161
+ => new TransportFailure(TransportFailure::NOT_SENT, null, "cURL error $errno: SEFAZ's server certificate did not verify"),
162
+ $sent && in_array($errno, [CURLE_OPERATION_TIMEDOUT, CURLE_GOT_NOTHING, CURLE_RECV_ERROR, CURLE_SEND_ERROR], true)
163
+ => new TransportFailure(TransportFailure::NO_ANSWER, null, "cURL error $errno after the request went out"),
164
+ default => new TransportFailure(TransportFailure::NOT_SENT, null, "cURL error $errno before the request went out"),
165
+ };
166
+ }
167
+
168
+ /** `403.6`, as IIS names its substatus, or the status and the first words of the page. */
169
+ private static function httpDetail(int $status, string $body): string
170
+ {
171
+ if (preg_match('/\b' . $status . '\.(\d{1,2})\b/', $body, $sub) === 1) {
172
+ return "$status.{$sub[1]}";
173
+ }
174
+ $text = trim((string) preg_replace('/\s+/', ' ', strip_tags($body)));
175
+ return $text === '' ? (string) $status : $status . ' "' . mb_substr($text, 0, 80) . '"';
176
+ }
177
+
178
+ /** @return array<int, string> */
179
+ private function trustAnchors(): array
180
+ {
181
+ if ($this->caBundle !== null) {
182
+ return [CURLOPT_CAINFO => $this->caBundle];
183
+ }
184
+ if (is_readable(self::IMAGE_CA_BUNDLE)) {
185
+ return [CURLOPT_CAINFO => self::IMAGE_CA_BUNDLE];
186
+ }
187
+ // Outside the image: the system's bundle plus the committed ICP-Brasil chain, in memory.
188
+ $system = '';
189
+ foreach ([(string) (openssl_get_cert_locations()['default_cert_file'] ?? ''), '/etc/ssl/certs/ca-certificates.crt'] as $file) {
190
+ if ($system === '' && $file !== '' && is_readable($file)) {
191
+ $system = (string) file_get_contents($file);
192
+ }
193
+ }
194
+ $pem = $system . "\n"
195
+ . (string) file_get_contents(self::ICP_BRASIL_PEM);
196
+ return [CURLOPT_CAINFO_BLOB => $pem];
197
+ }
198
+ }
@@ -0,0 +1,57 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar\Nfe\Transport;
6
+
7
+ use NFePHP\Common\Certificate;
8
+ use NFePHP\Common\Soap\SoapBase;
9
+ use NFePHP\Common\Soap\SoapInterface;
10
+
11
+ /**
12
+ * sped-nfe's `Tools` speaks to a `SoapInterface`. This one builds the envelope
13
+ * the way sped-common does and hands it to a `Transport`, so the key material
14
+ * never reaches sped-common's temporary-folder code path, and a test can put
15
+ * recorded SEFAZ replies behind the very same `Tools` calls.
16
+ */
17
+ final class SoapAdapter extends SoapBase implements SoapInterface
18
+ {
19
+ public function __construct(
20
+ private readonly Transport $transport,
21
+ Certificate $certificate,
22
+ ) {
23
+ parent::__construct($certificate);
24
+ }
25
+
26
+ /**
27
+ * @param string $url
28
+ * @param string $operation
29
+ * @param string $action
30
+ * @param int $soapver
31
+ * @param array<string, string> $parameters
32
+ * @param array<string, string> $namespaces
33
+ * @param string $request
34
+ * @param \SoapHeader|null $soapheader
35
+ */
36
+ public function send(
37
+ $url,
38
+ $operation = '',
39
+ $action = '',
40
+ $soapver = SOAP_1_2,
41
+ $parameters = [],
42
+ $namespaces = [],
43
+ $request = '',
44
+ $soapheader = null,
45
+ ) {
46
+ $envelope = $this->makeEnvelopeSoap($request, $namespaces, $soapver, $soapheader);
47
+ $this->requestBody = $envelope;
48
+ $this->responseBody = $this->transport->post((string) $url, (string) $action, $envelope, $this->certificate);
49
+ return $this->responseBody;
50
+ }
51
+
52
+ /** sped-common writes key files here; this adapter never needs them. */
53
+ public function saveTemporarilyKeyFiles()
54
+ {
55
+ throw new \LogicException('The fiscal service never writes key material to disk.');
56
+ }
57
+ }
@@ -0,0 +1,20 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar\Nfe\Transport;
6
+
7
+ use NFePHP\Common\Certificate;
8
+
9
+ /** Posts one SOAP envelope to a SEFAZ web service over mutual TLS. */
10
+ interface Transport
11
+ {
12
+ /**
13
+ * @return string the response body
14
+ * @throws TransportFailure
15
+ */
16
+ public function post(string $url, string $action, string $envelope, Certificate $certificate): string;
17
+
18
+ /** Whether SEFAZ's server certificate is verified — what `/health` reports. */
19
+ public function verifiesServer(): bool;
20
+ }
@@ -0,0 +1,42 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar\Nfe\Transport;
6
+
7
+ use RuntimeException;
8
+
9
+ /**
10
+ * SEFAZ could not be heard from, sorted by the one question that decides what
11
+ * a caller may do next: did the request go out?
12
+ *
13
+ * - NOT_SENT: nothing reached SEFAZ (no route, a connect timeout, a refused
14
+ * proxy tunnel, a server certificate that does not verify). Safe to send
15
+ * again, or for an NFC-e to go offline.
16
+ * - NO_ANSWER: the request went out and no answer came back (an empty reply,
17
+ * a receive error or a timeout after the upload, HTTP 5xx). SEFAZ may have
18
+ * processed it: the outcome is unknown until the key is looked up.
19
+ * - TLS_REFUSED: the client certificate was refused (a TLS alert, a local key
20
+ * cURL cannot use, or an HTTP 403 from a VERIFIED SEFAZ host).
21
+ * - REFUSED: an HTTP answer that is not SEFAZ's (a 4xx, or a 403 from a host
22
+ * whose certificate was not verified): nothing was processed; try again.
23
+ * - SEFAZ_HTTP: a 4xx other than 403, 408 and 429 from the VERIFIED SEFAZ host
24
+ * (a 404 or 405: the web-service address or the request is wrong). The same
25
+ * request gets the same answer, so it is a defect, never a retry.
26
+ */
27
+ final class TransportFailure extends RuntimeException
28
+ {
29
+ public const NOT_SENT = 'NOT_SENT';
30
+ public const NO_ANSWER = 'NO_ANSWER';
31
+ public const TLS_REFUSED = 'TLS_REFUSED';
32
+ public const REFUSED = 'REFUSED';
33
+ public const SEFAZ_HTTP = 'SEFAZ_HTTP';
34
+
35
+ public function __construct(
36
+ public readonly string $kind,
37
+ public readonly ?int $httpStatus = null,
38
+ string $message = '',
39
+ ) {
40
+ parent::__construct($message !== '' ? $message : $kind);
41
+ }
42
+ }
@@ -0,0 +1,54 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar;
6
+
7
+ /**
8
+ * One JSON line per request: when, which endpoint, the answer's status, and
9
+ * for a failure its class and SEFAZ code. NEVER the body, a header, an
10
+ * exception message or anything read from the request: the certificate, its
11
+ * password and the CSC travel in the body, and a message can quote input. So
12
+ * the fields are a closed list, written here and nowhere else.
13
+ */
14
+ final class RequestLog
15
+ {
16
+ /** @var resource */
17
+ private $stream;
18
+
19
+ /** @param resource|null $stream defaults to stderr */
20
+ public function __construct($stream = null)
21
+ {
22
+ $this->stream = $stream ?? fopen('php://stderr', 'wb');
23
+ }
24
+
25
+ public function record(
26
+ string $method,
27
+ string $path,
28
+ int $status,
29
+ float $startedAt,
30
+ ?ErrorClass $class,
31
+ ?string $code,
32
+ ?string $failure = null,
33
+ ): void {
34
+ $line = [
35
+ 'at' => gmdate('Y-m-d\TH:i:s\Z'),
36
+ 'method' => $method,
37
+ 'path' => self::knownPath($path),
38
+ 'status' => $status,
39
+ 'ms' => (int) round((microtime(true) - $startedAt) * 1000),
40
+ 'class' => $class?->value,
41
+ 'code' => $code !== null && preg_match('/^[0-9]{1,4}$/', $code) === 1 ? $code : null,
42
+ ];
43
+ if ($failure !== null) {
44
+ $line['failure'] = $failure;
45
+ }
46
+ fwrite($this->stream, json_encode($line, JSON_UNESCAPED_SLASHES) . "\n");
47
+ }
48
+
49
+ /** The path, if it is made of route characters only; a probe's junk is not echoed. */
50
+ private static function knownPath(string $path): string
51
+ {
52
+ return preg_match('#^[a-z/-]{1,40}$#', $path) === 1 ? $path : '(other)';
53
+ }
54
+ }
@@ -0,0 +1,69 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Fiscal\Sidecar;
6
+
7
+ use RuntimeException;
8
+ use Throwable;
9
+
10
+ /**
11
+ * A classified failure. Its message goes to the CALLER, never to the request
12
+ * log, which records the class and the code only.
13
+ */
14
+ final class ServiceError extends RuntimeException
15
+ {
16
+ /**
17
+ * @param list<string> $details
18
+ */
19
+ public function __construct(
20
+ public readonly ErrorClass $class,
21
+ string $message,
22
+ public readonly ?string $sefazCode = null,
23
+ public readonly array $details = [],
24
+ public readonly ?string $accessKey = null,
25
+ public readonly ?string $signedXml = null,
26
+ public readonly ?string $sefazReply = null,
27
+ ?Throwable $previous = null,
28
+ public readonly bool $outcomeUnknown = false,
29
+ ) {
30
+ parent::__construct($message, 0, $previous);
31
+ }
32
+
33
+ /** @param list<string> $details */
34
+ public static function invalid(string $message, array $details = []): self
35
+ {
36
+ return new self(ErrorClass::INVALID, $message, null, $details);
37
+ }
38
+
39
+ /** The same failure, now knowing the document it concerned. */
40
+ public function withDocument(?string $accessKey, ?string $signedXml): self
41
+ {
42
+ return new self(
43
+ $this->class,
44
+ $this->getMessage(),
45
+ $this->sefazCode,
46
+ $this->details,
47
+ $this->accessKey ?? $accessKey,
48
+ $this->signedXml ?? $signedXml,
49
+ $this->sefazReply,
50
+ $this,
51
+ $this->outcomeUnknown,
52
+ );
53
+ }
54
+
55
+ /** @return array{error: array<string, mixed>} */
56
+ public function toBody(): array
57
+ {
58
+ return ['error' => [
59
+ 'class' => $this->class->value,
60
+ 'code' => $this->sefazCode,
61
+ 'message' => $this->getMessage(),
62
+ 'details' => $this->details,
63
+ 'accessKey' => $this->accessKey,
64
+ 'signedXml' => $this->signedXml,
65
+ 'sefazReply' => $this->sefazReply,
66
+ 'outcomeUnknown' => $this->outcomeUnknown,
67
+ ]];
68
+ }
69
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The DANFE NFC-e's words in English — a named pack, for a host that shows the
3
+ * paper to English readers (a preview, a support screen, a test). The paper a
4
+ * Brazilian consumer receives is printed with `./pt-BR`: the Manual do DANFE
5
+ * NFC-e fixes its legal phrases in Portuguese.
6
+ */
7
+
8
+ import type { DanfeNfceLabels } from "./labels";
9
+
10
+ export const DANFE_NFCE_EN_US: DanfeNfceLabels = {
11
+ cnpj: "CNPJ",
12
+ stateRegistration: "IE",
13
+ title: "Auxiliary Document of the Electronic Consumer Invoice",
14
+ itemsHeader: "CODE DESCRIPTION QTY UN UNIT PRICE TOTAL",
15
+ itemCount: "Total items",
16
+ totalValue: "Total BRL",
17
+ discounts: "Discounts BRL",
18
+ amountDue: "Amount due BRL",
19
+ paymentHeader: "PAYMENT METHOD / AMOUNT PAID BRL",
20
+ change: "Change BRL",
21
+ paymentMethods: {
22
+ "01": "Cash",
23
+ "02": "Check",
24
+ "03": "Credit card",
25
+ "04": "Debit card",
26
+ "05": "Store credit",
27
+ "10": "Food voucher",
28
+ "11": "Meal voucher",
29
+ "12": "Gift voucher",
30
+ "13": "Fuel voucher",
31
+ "15": "Bank slip",
32
+ "16": "Bank deposit",
33
+ "17": "Dynamic Pix",
34
+ "18": "Bank transfer",
35
+ "19": "Loyalty program",
36
+ "20": "Static Pix",
37
+ "90": "No payment",
38
+ "99": "Other",
39
+ },
40
+ lookupByKey: "Look the access key up at",
41
+ homologation: "ISSUED IN THE TEST ENVIRONMENT - NO FISCAL VALUE",
42
+ contingency: "ISSUED IN CONTINGENCY",
43
+ pendingAuthorization: "Pending authorisation",
44
+ consumerCopy: "Consumer copy",
45
+ consumer: "CONSUMER",
46
+ unidentifiedConsumer: "UNIDENTIFIED CONSUMER",
47
+ number: "NFC-e no.",
48
+ series: "Series",
49
+ protocol: "Authorisation protocol:",
50
+ authorizedAt: "Authorised at:",
51
+ qrCaption: "Look it up with a QR code reader",
52
+ approximateTaxes: "Total taxes (Federal Law 12.741/2012) BRL",
53
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@12-apps/fiscal/danfe` — the DANFE NFC-e as ESC/POS-ready lines for 58 and
3
+ * 80 mm rolls, from the authorised XML (or the signed one of a document issued
4
+ * offline, which prints the contingency variant). The words come from the
5
+ * host; `./danfe/pt-BR` carries the Manual's own words (`./danfe/en-US` an English pack for previews).
6
+ */
7
+
8
+ export { DANFE_COLUMNS, money, renderDanfeNfce, wrap } from "./render";
9
+ export type { DanfeDivision, DanfeLine, DanfeNfceInput, PaperWidth } from "./render";
10
+ export { DANFE_LABEL_KEYS } from "./labels";
11
+ export type { DanfeNfceLabels } from "./labels";
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The words a DANFE NFC-e prints. The layout is the Manual do DANFE NFC-e's
3
+ * and the words are the host's language: a host passes them all, or the
4
+ * `./pt-BR` pack, which carries the Manual's own texts. Nothing here defaults.
5
+ */
6
+
7
+ export interface DanfeNfceLabels {
8
+ /** Division I. */
9
+ readonly cnpj: string;
10
+ readonly stateRegistration: string;
11
+ /** Division II: the document's own title. */
12
+ readonly title: string;
13
+ /** Division III: the item table's header. */
14
+ readonly itemsHeader: string;
15
+ /** Division IV. */
16
+ readonly itemCount: string;
17
+ readonly totalValue: string;
18
+ readonly discounts: string;
19
+ readonly amountDue: string;
20
+ readonly paymentHeader: string;
21
+ readonly change: string;
22
+ /** `tPag` code (`01`, `17`…) → the method's name; an unknown code prints itself. */
23
+ readonly paymentMethods: Readonly<Record<string, string>>;
24
+ /** Division V. */
25
+ readonly lookupByKey: string;
26
+ readonly homologation: string;
27
+ readonly contingency: string;
28
+ readonly pendingAuthorization: string;
29
+ /** Printed on a paper signed offline and not yet authorised: the one copy, the consumer's. */
30
+ readonly consumerCopy: string;
31
+ /** Division VI. */
32
+ readonly consumer: string;
33
+ readonly unidentifiedConsumer: string;
34
+ /** Division VII. */
35
+ readonly number: string;
36
+ readonly series: string;
37
+ readonly protocol: string;
38
+ readonly authorizedAt: string;
39
+ /** Division VIII and after: the QR code's caption and the approximate tax line (Lei 12.741/2012). */
40
+ readonly qrCaption: string;
41
+ readonly approximateTaxes: string;
42
+ }
43
+
44
+ export const DANFE_LABEL_KEYS: readonly (keyof DanfeNfceLabels)[] = [
45
+ "cnpj", "stateRegistration", "title", "itemsHeader", "itemCount", "totalValue", "discounts", "amountDue",
46
+ "paymentHeader", "change", "paymentMethods", "lookupByKey", "homologation", "contingency", "pendingAuthorization",
47
+ "consumerCopy",
48
+ "consumer", "unidentifiedConsumer", "number", "series", "protocol", "authorizedAt", "qrCaption", "approximateTaxes",
49
+ ];
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The Manual do DANFE NFC-e's own texts, in Portuguese — a named pack, the
3
+ * words a Brazilian host passes as `labels`. The legal phrases (the title,
4
+ * the homologation and contingency notices) are the Manual's, verbatim.
5
+ */
6
+
7
+ import type { DanfeNfceLabels } from "./labels";
8
+
9
+ export const DANFE_NFCE_PT_BR: DanfeNfceLabels = {
10
+ cnpj: "CNPJ",
11
+ stateRegistration: "IE",
12
+ title: "Documento Auxiliar da Nota Fiscal de Consumidor Eletrônica",
13
+ itemsHeader: "CÓDIGO DESCRIÇÃO QTDE UN VL UNIT VL TOTAL",
14
+ itemCount: "Qtde. total de itens",
15
+ totalValue: "Valor total R$",
16
+ discounts: "Descontos R$",
17
+ amountDue: "Valor a Pagar R$",
18
+ paymentHeader: "FORMA PAGAMENTO / VALOR PAGO R$",
19
+ change: "Troco R$",
20
+ paymentMethods: {
21
+ "01": "Dinheiro",
22
+ "02": "Cheque",
23
+ "03": "Cartão de Crédito",
24
+ "04": "Cartão de Débito",
25
+ "05": "Crédito Loja",
26
+ "10": "Vale Alimentação",
27
+ "11": "Vale Refeição",
28
+ "12": "Vale Presente",
29
+ "13": "Vale Combustível",
30
+ "15": "Boleto Bancário",
31
+ "16": "Depósito Bancário",
32
+ "17": "PIX Dinâmico",
33
+ "18": "Transferência bancária",
34
+ "19": "Programa de fidelidade",
35
+ "20": "PIX Estático",
36
+ "90": "Sem pagamento",
37
+ "99": "Outros",
38
+ },
39
+ lookupByKey: "Consulte pela Chave de Acesso em",
40
+ homologation: "EMITIDA EM AMBIENTE DE HOMOLOGAÇÃO - SEM VALOR FISCAL",
41
+ contingency: "EMITIDA EM CONTINGÊNCIA",
42
+ pendingAuthorization: "Pendente de autorização",
43
+ consumerCopy: "Via consumidor",
44
+ consumer: "CONSUMIDOR",
45
+ unidentifiedConsumer: "CONSUMIDOR NÃO IDENTIFICADO",
46
+ number: "NFC-e nº",
47
+ series: "Série",
48
+ protocol: "Protocolo de autorização:",
49
+ authorizedAt: "Data de autorização:",
50
+ qrCaption: "Consulta via leitor de QR Code",
51
+ approximateTaxes: "Tributos totais incidentes (Lei Federal 12.741/2012) R$",
52
+ };