@12-apps/fiscal 0.0.0-stage → 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.
- package/README.md +269 -2
- package/dist/chunk-27B4HNO6.js +574 -0
- package/dist/chunk-27B4HNO6.js.map +1 -0
- package/dist/chunk-3SDXLSG4.js +24 -0
- package/dist/chunk-3SDXLSG4.js.map +1 -0
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/chunk-ALABGVPO.js +247 -0
- package/dist/chunk-ALABGVPO.js.map +1 -0
- package/dist/chunk-FOFIN5M7.js +14 -0
- package/dist/chunk-FOFIN5M7.js.map +1 -0
- package/dist/chunk-HQ2NXSTX.js +85 -0
- package/dist/chunk-HQ2NXSTX.js.map +1 -0
- package/dist/chunk-PNTKG3DZ.js +47 -0
- package/dist/chunk-PNTKG3DZ.js.map +1 -0
- package/dist/chunk-RRFKYVLZ.js +192 -0
- package/dist/chunk-RRFKYVLZ.js.map +1 -0
- package/dist/chunk-V5ZQAAJT.js +210 -0
- package/dist/chunk-V5ZQAAJT.js.map +1 -0
- package/dist/chunk-X6MRDUYH.js +21 -0
- package/dist/chunk-X6MRDUYH.js.map +1 -0
- package/dist/chunk-XQGW5HUG.js +30 -0
- package/dist/chunk-XQGW5HUG.js.map +1 -0
- package/dist/context-ChnWR4Kb.d.ts +455 -0
- package/dist/danfe/en-US.d.ts +12 -0
- package/dist/danfe/en-US.js +51 -0
- package/dist/danfe/en-US.js.map +1 -0
- package/dist/danfe/index.d.ts +50 -0
- package/dist/danfe/index.js +18 -0
- package/dist/danfe/index.js.map +1 -0
- package/dist/danfe/pt-BR.d.ts +11 -0
- package/dist/danfe/pt-BR.js +51 -0
- package/dist/danfe/pt-BR.js.map +1 -0
- package/dist/documents/index.d.ts +169 -0
- package/dist/documents/index.js +1228 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/engine/index.d.ts +118 -0
- package/dist/engine/index.js +591 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/http.d.ts +73 -0
- package/dist/http.js +16 -0
- package/dist/http.js.map +1 -0
- package/dist/issuer/index.d.ts +43 -0
- package/dist/issuer/index.js +131 -0
- package/dist/issuer/index.js.map +1 -0
- package/dist/jobs.d.ts +74 -0
- package/dist/jobs.js +22 -0
- package/dist/jobs.js.map +1 -0
- package/dist/labels-BNvflT0h.d.ts +44 -0
- package/dist/manifest/index.d.ts +97 -0
- package/dist/manifest/index.js +27 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/server.d.ts +57 -0
- package/dist/manifest/server.js +25 -0
- package/dist/manifest/server.js.map +1 -0
- package/dist/notifications.d.ts +93 -0
- package/dist/notifications.js +41 -0
- package/dist/notifications.js.map +1 -0
- package/dist/port-DpRFK56U.d.ts +238 -0
- package/dist/sale/index.d.ts +243 -0
- package/dist/sale/index.js +1 -0
- package/dist/sale/index.js.map +1 -0
- package/dist/service-KTjH7AxW.d.ts +139 -0
- package/dist/sidecar/index.d.ts +216 -0
- package/dist/sidecar/index.js +8 -0
- package/dist/sidecar/index.js.map +1 -0
- package/dist/types-B1b8LIWX.d.ts +247 -0
- package/package.json +126 -4
- package/prisma/fiscal.prisma +158 -0
- package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
- package/sidecar/.dockerignore +5 -0
- package/sidecar/Dockerfile +68 -0
- package/sidecar/README.md +149 -0
- package/sidecar/composer.json +30 -0
- package/sidecar/composer.lock +2224 -0
- package/sidecar/docker/apache.conf +14 -0
- package/sidecar/docker/icp-brasil.pem +8031 -0
- package/sidecar/docker/mpm.conf +17 -0
- package/sidecar/docker/openssl.cnf +16 -0
- package/sidecar/docker/php.ini +19 -0
- package/sidecar/public/index.php +15 -0
- package/sidecar/schema/sale-for-document.schema.json +401 -0
- package/sidecar/src/ErrorClass.php +31 -0
- package/sidecar/src/Http/Request.php +48 -0
- package/sidecar/src/Http/Response.php +32 -0
- package/sidecar/src/Http/Router.php +59 -0
- package/sidecar/src/Kernel.php +99 -0
- package/sidecar/src/Module.php +31 -0
- package/sidecar/src/Nfe/Classifier.php +89 -0
- package/sidecar/src/Nfe/Credentials.php +52 -0
- package/sidecar/src/Nfe/DocumentMapper.php +383 -0
- package/sidecar/src/Nfe/DocumentSchema.php +39 -0
- package/sidecar/src/Nfe/Input.php +125 -0
- package/sidecar/src/Nfe/Model.php +17 -0
- package/sidecar/src/Nfe/NfeModule.php +62 -0
- package/sidecar/src/Nfe/NfeService.php +504 -0
- package/sidecar/src/Nfe/Sefaz.php +49 -0
- package/sidecar/src/Nfe/SefazReply.php +81 -0
- package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
- package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
- package/sidecar/src/Nfe/Transport/Transport.php +20 -0
- package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
- package/sidecar/src/RequestLog.php +54 -0
- package/sidecar/src/ServiceError.php +69 -0
- package/src/danfe/en-US.ts +53 -0
- package/src/danfe/index.ts +11 -0
- package/src/danfe/labels.ts +49 -0
- package/src/danfe/pt-BR.ts +52 -0
- package/src/danfe/render.ts +265 -0
- package/src/danfe/xml.ts +45 -0
- package/src/documents/context.ts +260 -0
- package/src/documents/errors.ts +41 -0
- package/src/documents/helpers.ts +128 -0
- package/src/documents/index.ts +39 -0
- package/src/documents/lines.ts +63 -0
- package/src/documents/machine-steps.ts +260 -0
- package/src/documents/machine.ts +128 -0
- package/src/documents/memory.ts +138 -0
- package/src/documents/nfe-proc.ts +51 -0
- package/src/documents/ports.ts +130 -0
- package/src/documents/profile-input.ts +168 -0
- package/src/documents/profile.ts +98 -0
- package/src/documents/service-profile.ts +104 -0
- package/src/documents/service.ts +296 -0
- package/src/documents/settle.ts +121 -0
- package/src/documents/signing.ts +61 -0
- package/src/documents/sql-rows.ts +180 -0
- package/src/documents/sql-store.ts +242 -0
- package/src/documents/sql.ts +18 -0
- package/src/documents/steps.ts +173 -0
- package/src/documents/tests/integration/pglite.ts +73 -0
- package/src/documents/types.ts +193 -0
- package/src/engine/compare.ts +68 -0
- package/src/engine/compute.ts +40 -0
- package/src/engine/errors.ts +28 -0
- package/src/engine/index.ts +20 -0
- package/src/engine/oracle.ts +81 -0
- package/src/engine/plan.ts +268 -0
- package/src/engine/rounding.ts +81 -0
- package/src/engine/types.ts +270 -0
- package/src/engine/validate.ts +222 -0
- package/src/http.ts +264 -0
- package/src/issuer/index.ts +9 -0
- package/src/issuer/port.ts +109 -0
- package/src/issuer/sidecar.ts +171 -0
- package/src/jobs.ts +115 -0
- package/src/manifest/index.ts +46 -0
- package/src/manifest/permissions.ts +28 -0
- package/src/manifest/server.ts +20 -0
- package/src/notifications.ts +120 -0
- package/src/sale/index.ts +8 -0
- package/src/sale/types.ts +292 -0
- package/src/sidecar/index.ts +9 -0
- package/src/sidecar/types.ts +243 -0
- package/tables/ibs-cbs-2026-11-13.json +156 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar;
|
|
6
|
+
|
|
7
|
+
use Fiscal\Sidecar\Http\Request;
|
|
8
|
+
use Fiscal\Sidecar\Http\Response;
|
|
9
|
+
use Fiscal\Sidecar\Http\Router;
|
|
10
|
+
use Fiscal\Sidecar\Nfe\NfeModule;
|
|
11
|
+
use Fiscal\Sidecar\Nfe\Transport\CurlTransport;
|
|
12
|
+
use Fiscal\Sidecar\Nfe\Transport\Transport;
|
|
13
|
+
use Throwable;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The service: a router over the library modules, one request at a time.
|
|
17
|
+
* Built per request by `public/index.php`, so nothing a call brings in (a
|
|
18
|
+
* certificate, above all) can outlive it.
|
|
19
|
+
*/
|
|
20
|
+
final class Kernel
|
|
21
|
+
{
|
|
22
|
+
private readonly Router $router;
|
|
23
|
+
|
|
24
|
+
/** @param list<Module> $modules */
|
|
25
|
+
public function __construct(
|
|
26
|
+
private readonly array $modules,
|
|
27
|
+
private readonly RequestLog $log,
|
|
28
|
+
) {
|
|
29
|
+
$this->router = new Router();
|
|
30
|
+
$this->router->add('GET', '/health', fn (): Response => $this->health());
|
|
31
|
+
foreach ($modules as $module) {
|
|
32
|
+
$module->register($this->router);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The production wiring: every module, talking to SEFAZ over cURL. */
|
|
37
|
+
public static function production(?Transport $transport = null, ?RequestLog $log = null): self
|
|
38
|
+
{
|
|
39
|
+
return new self(self::modules($transport ?? CurlTransport::fromEnvironment()), $log ?? new RequestLog());
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The libraries the service runs. A second one (NFS-e) is appended here.
|
|
44
|
+
*
|
|
45
|
+
* @return list<Module>
|
|
46
|
+
*/
|
|
47
|
+
public static function modules(Transport $transport): array
|
|
48
|
+
{
|
|
49
|
+
return [new NfeModule($transport)];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
public function router(): Router
|
|
53
|
+
{
|
|
54
|
+
return $this->router;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
public function handle(Request $request): Response
|
|
58
|
+
{
|
|
59
|
+
$startedAt = microtime(true);
|
|
60
|
+
try {
|
|
61
|
+
$response = $this->router->dispatch($request);
|
|
62
|
+
$class = isset($response->body['error']['class'])
|
|
63
|
+
? ErrorClass::from($response->body['error']['class'])
|
|
64
|
+
: null;
|
|
65
|
+
$this->log->record($request->method, $request->path, $response->status, $startedAt, $class, null);
|
|
66
|
+
return $response;
|
|
67
|
+
} catch (ServiceError $error) {
|
|
68
|
+
$status = $error->class->httpStatus();
|
|
69
|
+
$this->log->record($request->method, $request->path, $status, $startedAt, $error->class, $error->sefazCode);
|
|
70
|
+
return new Response($status, $error->toBody());
|
|
71
|
+
} catch (Throwable $unexpected) {
|
|
72
|
+
// The exception's message can quote input, so only its type is logged.
|
|
73
|
+
$this->log->record(
|
|
74
|
+
$request->method,
|
|
75
|
+
$request->path,
|
|
76
|
+
500,
|
|
77
|
+
$startedAt,
|
|
78
|
+
ErrorClass::INTERNAL,
|
|
79
|
+
null,
|
|
80
|
+
(new \ReflectionClass($unexpected))->getShortName(),
|
|
81
|
+
);
|
|
82
|
+
// INTERNAL, not RETRYABLE: a defect answers the same way every time,
|
|
83
|
+
// and a retry loop would only repeat it.
|
|
84
|
+
$error = new ServiceError(ErrorClass::INTERNAL, 'The service failed unexpectedly.');
|
|
85
|
+
return new Response(500, $error->toBody());
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private function health(): Response
|
|
90
|
+
{
|
|
91
|
+
$libraries = [];
|
|
92
|
+
$facts = [];
|
|
93
|
+
foreach ($this->modules as $module) {
|
|
94
|
+
$libraries += $module->libraries();
|
|
95
|
+
$facts += $module->health();
|
|
96
|
+
}
|
|
97
|
+
return new Response(200, ['status' => 'ok', 'libraries' => $libraries] + $facts);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar;
|
|
6
|
+
|
|
7
|
+
use Fiscal\Sidecar\Http\Router;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* One document library behind the service. sped-nfe (models 55 and 65) is the
|
|
11
|
+
* first; an NFS-e library is a second module with its own `/nfse/...` paths,
|
|
12
|
+
* added beside it in `Kernel::modules()`.
|
|
13
|
+
*/
|
|
14
|
+
interface Module
|
|
15
|
+
{
|
|
16
|
+
public function register(Router $router): void;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The libraries this module runs, by name, with their installed version.
|
|
20
|
+
*
|
|
21
|
+
* @return array<string, string>
|
|
22
|
+
*/
|
|
23
|
+
public function libraries(): array;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What this module adds to `/health`.
|
|
27
|
+
*
|
|
28
|
+
* @return array<string, scalar>
|
|
29
|
+
*/
|
|
30
|
+
public function health(): array;
|
|
31
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar\Nfe;
|
|
6
|
+
|
|
7
|
+
use Fiscal\Sidecar\ErrorClass;
|
|
8
|
+
use Fiscal\Sidecar\Nfe\Transport\TransportFailure;
|
|
9
|
+
use Fiscal\Sidecar\ServiceError;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* SEFAZ's status codes and the transport's failures, sorted into the issuer
|
|
13
|
+
* port's classes. Everything not listed is a REJECTED with its code: the
|
|
14
|
+
* layout's rejection table is open-ended, and a code the service does not know
|
|
15
|
+
* is still SEFAZ saying no to this document.
|
|
16
|
+
*
|
|
17
|
+
* The codes and their meanings are the MOC table as sped-nfe carries it,
|
|
18
|
+
* `vendor/nfephp-org/sped-nfe/storage/cstat.json`.
|
|
19
|
+
*/
|
|
20
|
+
final class Classifier
|
|
21
|
+
{
|
|
22
|
+
/**
|
|
23
|
+
* The certificate itself refused: the transmitter's (280 invalid, 281
|
|
24
|
+
* validity, 282 no CNPJ, 283 chain, 284 revoked, 285 not ICP-Brasil), the
|
|
25
|
+
* signature's (290–295, the same six), and a CNPJ-base mismatch (213).
|
|
26
|
+
*/
|
|
27
|
+
private const AUTH = [
|
|
28
|
+
'213', '280', '281', '282', '283', '284', '285', '290', '291', '292', '293', '294', '295',
|
|
29
|
+
];
|
|
30
|
+
/** Service stopped, momentarily or with no forecast. */
|
|
31
|
+
private const STOPPED = ['108', '109'];
|
|
32
|
+
/**
|
|
33
|
+
* Ask again: a receipt only (103), a batch still processing (105), SEFAZ
|
|
34
|
+
* failing to reach a revocation list for the transmitter's or the signing
|
|
35
|
+
* certificate (286, 296 — SEFAZ's trouble, not the certificate's), rate
|
|
36
|
+
* limiting (656), an uncatalogued error (999).
|
|
37
|
+
*/
|
|
38
|
+
private const RETRYABLE = ['103', '105', '286', '296', '656', '999'];
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param bool $issuing an authorisation request: SEFAZ stopped (108, 109)
|
|
42
|
+
* means contingency there, and only "try again" anywhere else
|
|
43
|
+
*/
|
|
44
|
+
public static function fromStatus(string $status, string $reason, SefazReply $reply, bool $issuing): ServiceError
|
|
45
|
+
{
|
|
46
|
+
$class = match (true) {
|
|
47
|
+
in_array($status, self::AUTH, true) => ErrorClass::AUTH,
|
|
48
|
+
in_array($status, self::STOPPED, true) => $issuing ? ErrorClass::CONTINGENCY : ErrorClass::RETRYABLE,
|
|
49
|
+
in_array($status, self::RETRYABLE, true) => ErrorClass::RETRYABLE,
|
|
50
|
+
default => ErrorClass::REJECTED,
|
|
51
|
+
};
|
|
52
|
+
return new ServiceError($class, "SEFAZ [$status] $reason", $status, [], null, null, $reply->raw);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param bool $offlineAllowed issuing an NFC-e, the one call that can go
|
|
57
|
+
* offline (`tpEmis = 9`) when nothing reached SEFAZ
|
|
58
|
+
*/
|
|
59
|
+
public static function fromTransport(TransportFailure $failure, bool $offlineAllowed): ServiceError
|
|
60
|
+
{
|
|
61
|
+
return match ($failure->kind) {
|
|
62
|
+
TransportFailure::TLS_REFUSED => new ServiceError(
|
|
63
|
+
ErrorClass::AUTH,
|
|
64
|
+
'SEFAZ refused the client certificate (' . $failure->getMessage() . ').',
|
|
65
|
+
),
|
|
66
|
+
TransportFailure::NOT_SENT => new ServiceError(
|
|
67
|
+
$offlineAllowed ? ErrorClass::CONTINGENCY : ErrorClass::RETRYABLE,
|
|
68
|
+
'The request never reached SEFAZ (' . $failure->getMessage() . ').',
|
|
69
|
+
),
|
|
70
|
+
TransportFailure::NO_ANSWER => new ServiceError(
|
|
71
|
+
ErrorClass::RETRYABLE,
|
|
72
|
+
'The request went out and SEFAZ did not answer (' . $failure->getMessage()
|
|
73
|
+
. '); the outcome is unknown, so look the key up before sending it again.',
|
|
74
|
+
outcomeUnknown: true,
|
|
75
|
+
),
|
|
76
|
+
// INTERNAL rather than a new class: the issuer port's four classes plus
|
|
77
|
+
// INVALID (the caller's input) and INTERNAL (this side's defect) cover it,
|
|
78
|
+
// and a wrong web-service address is this side's defect.
|
|
79
|
+
TransportFailure::SEFAZ_HTTP => new ServiceError(
|
|
80
|
+
ErrorClass::INTERNAL,
|
|
81
|
+
'SEFAZ refused the request itself (' . $failure->getMessage() . '); sending it again gets the same answer.',
|
|
82
|
+
),
|
|
83
|
+
default => new ServiceError(
|
|
84
|
+
ErrorClass::RETRYABLE,
|
|
85
|
+
'An answer that is not SEFAZ\'s (' . $failure->getMessage() . '); nothing was processed.',
|
|
86
|
+
),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar\Nfe;
|
|
6
|
+
|
|
7
|
+
use Fiscal\Sidecar\ErrorClass;
|
|
8
|
+
use Fiscal\Sidecar\ServiceError;
|
|
9
|
+
use NFePHP\Common\Certificate;
|
|
10
|
+
use Throwable;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Opens the A1 handed in with the call, in memory. A wrong password, a file
|
|
14
|
+
* that is not PKCS#12 or an expired certificate is AUTH, and the answer says
|
|
15
|
+
* which without quoting anything it was given.
|
|
16
|
+
*/
|
|
17
|
+
final class Credentials
|
|
18
|
+
{
|
|
19
|
+
/**
|
|
20
|
+
* @param array{pfx: string, password: string} $certificate
|
|
21
|
+
* @param \DateTimeImmutable|null $now the moment the validity is judged at;
|
|
22
|
+
* the current time unless a test asks for another (PHP cannot backdate a
|
|
23
|
+
* certificate, so an expired one is judged at a later moment instead)
|
|
24
|
+
*/
|
|
25
|
+
public static function open(array $certificate, ?\DateTimeImmutable $now = null): Certificate
|
|
26
|
+
{
|
|
27
|
+
try {
|
|
28
|
+
$opened = Certificate::readPfx($certificate['pfx'], $certificate['password']);
|
|
29
|
+
} catch (Throwable) {
|
|
30
|
+
self::drainOpensslErrors();
|
|
31
|
+
throw new ServiceError(
|
|
32
|
+
ErrorClass::AUTH,
|
|
33
|
+
'The certificate could not be opened: the password is wrong or the file is not a PKCS#12 (.pfx).',
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
if ($opened->getValidTo() < ($now ?? new \DateTimeImmutable())) {
|
|
37
|
+
throw new ServiceError(
|
|
38
|
+
ErrorClass::AUTH,
|
|
39
|
+
'The certificate expired on ' . $opened->getValidTo()->format('Y-m-d') . '.',
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
return $opened;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** OpenSSL keeps a per-process error queue; a failed read must not leave one for the next call. */
|
|
46
|
+
private static function drainOpensslErrors(): void
|
|
47
|
+
{
|
|
48
|
+
while (openssl_error_string() !== false) {
|
|
49
|
+
// drain
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar\Nfe;
|
|
6
|
+
|
|
7
|
+
use Fiscal\Sidecar\ServiceError;
|
|
8
|
+
use NFePHP\Common\UFList;
|
|
9
|
+
use NFePHP\NFe\Make;
|
|
10
|
+
use Throwable;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* From the neutral `SaleForDocument` (already schema-valid) to sped-nfe's
|
|
14
|
+
* `Make`, tag by tag, and on to the unsigned XML and its access key.
|
|
15
|
+
*
|
|
16
|
+
* Money arrives in cents and leaves in reais; rates arrive in basis points and
|
|
17
|
+
* leave as percentages with four decimals; a code arrives as a name and leaves
|
|
18
|
+
* as the layout's number. Nothing here computes a tax: the figures are the
|
|
19
|
+
* caller's (the engine's), written as given.
|
|
20
|
+
*/
|
|
21
|
+
final class DocumentMapper
|
|
22
|
+
{
|
|
23
|
+
private const PURPOSE = ['NORMAL' => 1, 'COMPLEMENTARY' => 2, 'ADJUSTMENT' => 3, 'RETURN' => 4];
|
|
24
|
+
private const DESTINATION = ['INTERNAL' => 1, 'INTERSTATE' => 2, 'FOREIGN' => 3];
|
|
25
|
+
private const PRESENCE = [
|
|
26
|
+
'IN_PERSON' => 1,
|
|
27
|
+
'INTERNET' => 2,
|
|
28
|
+
'TELEPHONE' => 3,
|
|
29
|
+
'HOME_DELIVERY' => 4,
|
|
30
|
+
'IN_PERSON_OFF_PREMISES' => 5,
|
|
31
|
+
'OTHER' => 9,
|
|
32
|
+
];
|
|
33
|
+
private const CRT = ['SIMPLES' => 1, 'SIMPLES_EXCESS' => 2, 'NORMAL' => 3, 'MEI' => 4];
|
|
34
|
+
private const IE_STATUS = ['CONTRIBUTOR' => 1, 'EXEMPT' => 2, 'NON_CONTRIBUTOR' => 9];
|
|
35
|
+
private const FREIGHT = [
|
|
36
|
+
'BY_ISSUER' => 0,
|
|
37
|
+
'BY_RECIPIENT' => 1,
|
|
38
|
+
'BY_THIRD_PARTY' => 2,
|
|
39
|
+
'OWN_BY_ISSUER' => 3,
|
|
40
|
+
'OWN_BY_RECIPIENT' => 4,
|
|
41
|
+
'NONE' => 9,
|
|
42
|
+
];
|
|
43
|
+
private const PAYMENT = [
|
|
44
|
+
'CASH' => '01',
|
|
45
|
+
'CHECK' => '02',
|
|
46
|
+
'CREDIT_CARD' => '03',
|
|
47
|
+
'DEBIT_CARD' => '04',
|
|
48
|
+
'STORE_CREDIT' => '05',
|
|
49
|
+
'FOOD_VOUCHER' => '10',
|
|
50
|
+
'MEAL_VOUCHER' => '11',
|
|
51
|
+
'GIFT_VOUCHER' => '12',
|
|
52
|
+
'FUEL_VOUCHER' => '13',
|
|
53
|
+
'BANK_SLIP' => '15',
|
|
54
|
+
'BANK_DEPOSIT' => '16',
|
|
55
|
+
'PIX_DYNAMIC' => '17',
|
|
56
|
+
'TRANSFER' => '18',
|
|
57
|
+
'LOYALTY' => '19',
|
|
58
|
+
'PIX_STATIC' => '20',
|
|
59
|
+
'NO_PAYMENT' => '90',
|
|
60
|
+
'OTHER' => '99',
|
|
61
|
+
];
|
|
62
|
+
/** `indIntermed` is written only where the buyer was not at the counter (NT 2020.006). */
|
|
63
|
+
private const REMOTE_PRESENCE = [2, 3, 4, 9];
|
|
64
|
+
|
|
65
|
+
public const PROCESS_VERSION = 'fiscal-sidecar-1';
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* From 2027 the IBS/CBS go INSIDE `vProd`, and the price without tax
|
|
69
|
+
* travels in NT 2026.008's `vProdLiq`/`vUnComLiq`/`vProdLiqTot` (source: NT
|
|
70
|
+
* 2026.008 v1.00 itself: from 2027 the IBS, CBS and IS values "deverão ser
|
|
71
|
+
* acrescidos ao valor do produto ou serviço, compondo o valor informado no
|
|
72
|
+
* campo vProd"). sped-nfe 5.2.9 cannot write those fields, and document
|
|
73
|
+
* version 1 does not carry them, so a document issued on or after this day
|
|
74
|
+
* is refused rather than emitted wrong. Lifted by the sped-nfe bump that
|
|
75
|
+
* brings NT 2026.008, with document version 2.
|
|
76
|
+
*/
|
|
77
|
+
public const LAYOUT_LIMIT = '2027-01-01';
|
|
78
|
+
public const LAYOUT_LIMIT_CODE = 'NT_2026_008_NOT_SUPPORTED';
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @param array<string, mixed> $document
|
|
82
|
+
* @param array{since: string, reason: string}|null $contingency an NFC-e signed offline (`tpEmis = 9`)
|
|
83
|
+
* @return array{xml: string, accessKey: string}
|
|
84
|
+
* @throws ServiceError INVALID when sped-nfe refuses to build it
|
|
85
|
+
*/
|
|
86
|
+
public function build(array $document, Model $model, int $environment, ?array $contingency = null): array
|
|
87
|
+
{
|
|
88
|
+
self::refuseWhatThisLayoutCannotSay($document);
|
|
89
|
+
$make = new Make(NfeModule::SCHEMES);
|
|
90
|
+
$make->setOnlyAscii(false);
|
|
91
|
+
$make->setCheckGtin(true);
|
|
92
|
+
try {
|
|
93
|
+
$this->header($make, $document, $model, $environment, $contingency);
|
|
94
|
+
$this->parties($make, $document);
|
|
95
|
+
foreach (array_values($document['lines']) as $index => $line) {
|
|
96
|
+
$this->line($make, $index + 1, $line);
|
|
97
|
+
}
|
|
98
|
+
$this->closing($make, $document);
|
|
99
|
+
$xml = $make->render();
|
|
100
|
+
} catch (ServiceError $error) {
|
|
101
|
+
throw $error;
|
|
102
|
+
} catch (Throwable $failure) {
|
|
103
|
+
throw ServiceError::invalid('The document could not be built.', array_merge(
|
|
104
|
+
[$failure->getMessage()],
|
|
105
|
+
array_values(array_map('strval', $make->getErrors())),
|
|
106
|
+
));
|
|
107
|
+
}
|
|
108
|
+
$errors = array_values(array_map('strval', $make->getErrors()));
|
|
109
|
+
if ($errors !== []) {
|
|
110
|
+
throw ServiceError::invalid('The document could not be built.', $errors);
|
|
111
|
+
}
|
|
112
|
+
return ['xml' => $xml, 'accessKey' => $make->getChave()];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** @param array<string, mixed> $document */
|
|
116
|
+
private static function refuseWhatThisLayoutCannotSay(array $document): void
|
|
117
|
+
{
|
|
118
|
+
if (substr((string) $document['issuedAt'], 0, 10) >= self::LAYOUT_LIMIT) {
|
|
119
|
+
throw new ServiceError(
|
|
120
|
+
\Fiscal\Sidecar\ErrorClass::INVALID,
|
|
121
|
+
'A document issued on or after ' . self::LAYOUT_LIMIT . ' needs NT 2026.008 (vProdLiq), '
|
|
122
|
+
. 'which this service\'s sped-nfe does not write yet.',
|
|
123
|
+
self::LAYOUT_LIMIT_CODE,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
$details = [];
|
|
127
|
+
foreach (array_values($document['lines']) as $index => $line) {
|
|
128
|
+
$quantity = (float) $line['quantity'];
|
|
129
|
+
if (abs(round($quantity, 4) - $quantity) > 1e-9) {
|
|
130
|
+
$details[] = "lines[$index].quantity: at most four decimals (qCom)";
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if ($details !== []) {
|
|
134
|
+
throw ServiceError::invalid('The document does not fit the NF-e layout.', $details);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** @param array<string, mixed> $d */
|
|
139
|
+
private function header(Make $make, array $d, Model $model, int $environment, ?array $contingency): void
|
|
140
|
+
{
|
|
141
|
+
$make->taginfNFe((object) ['Id' => null, 'versao' => '4.00']);
|
|
142
|
+
$presence = self::PRESENCE[$d['presence']];
|
|
143
|
+
$make->tagide((object) [
|
|
144
|
+
'cUF' => UFList::getCodeByUF($d['issuer']['address']['uf']),
|
|
145
|
+
'cNF' => $d['keyCode'],
|
|
146
|
+
'natOp' => $d['operationNature'],
|
|
147
|
+
'mod' => $model->code(),
|
|
148
|
+
'serie' => $d['series'],
|
|
149
|
+
'nNF' => $d['number'],
|
|
150
|
+
'dhEmi' => $d['issuedAt'],
|
|
151
|
+
'dhSaiEnt' => null,
|
|
152
|
+
'tpNF' => 1,
|
|
153
|
+
'idDest' => self::DESTINATION[$d['destination']],
|
|
154
|
+
'cMunFG' => $d['issuer']['address']['municipalityIbge'],
|
|
155
|
+
'tpImp' => $model === Model::NFCE ? 4 : 1,
|
|
156
|
+
'tpEmis' => $contingency === null ? 1 : 9,
|
|
157
|
+
'cDV' => null,
|
|
158
|
+
'tpAmb' => $environment,
|
|
159
|
+
'finNFe' => self::PURPOSE[$d['purpose']],
|
|
160
|
+
'indFinal' => $d['finalConsumer'] ? 1 : 0,
|
|
161
|
+
'indPres' => $presence,
|
|
162
|
+
'indIntermed' => in_array($presence, self::REMOTE_PRESENCE, true)
|
|
163
|
+
? ($d['intermediary'] === null ? 0 : 1)
|
|
164
|
+
: null,
|
|
165
|
+
'procEmi' => 0,
|
|
166
|
+
'verProc' => self::PROCESS_VERSION,
|
|
167
|
+
'dhCont' => $contingency['since'] ?? null,
|
|
168
|
+
'xJust' => $contingency['reason'] ?? null,
|
|
169
|
+
]);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** @param array<string, mixed> $d */
|
|
173
|
+
private function parties(Make $make, array $d): void
|
|
174
|
+
{
|
|
175
|
+
$issuer = $d['issuer'];
|
|
176
|
+
$make->tagEmit((object) [
|
|
177
|
+
'xNome' => $issuer['legalName'],
|
|
178
|
+
'xFant' => $issuer['tradeName'],
|
|
179
|
+
'IE' => $issuer['stateRegistration'],
|
|
180
|
+
'CRT' => self::CRT[$issuer['taxRegime']],
|
|
181
|
+
'CNPJ' => $issuer['cnpj'],
|
|
182
|
+
]);
|
|
183
|
+
$make->tagenderEmit(self::address($issuer['address']));
|
|
184
|
+
$buyer = $d['buyer'];
|
|
185
|
+
if ($buyer === null) {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
$document = $buyer['document'];
|
|
189
|
+
$make->tagdest((object) [
|
|
190
|
+
'xNome' => $buyer['name'],
|
|
191
|
+
'CNPJ' => $document['kind'] === 'CNPJ' ? $document['number'] : null,
|
|
192
|
+
'CPF' => $document['kind'] === 'CPF' ? $document['number'] : null,
|
|
193
|
+
'idEstrangeiro' => $document['kind'] === 'FOREIGN' ? $document['number'] : null,
|
|
194
|
+
'indIEDest' => self::IE_STATUS[$buyer['stateRegistrationStatus']],
|
|
195
|
+
'IE' => $buyer['stateRegistration'],
|
|
196
|
+
'email' => $buyer['email'],
|
|
197
|
+
]);
|
|
198
|
+
if ($buyer['address'] !== null) {
|
|
199
|
+
$make->tagenderDest(self::address($buyer['address']));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** @param array<string, mixed> $address */
|
|
204
|
+
private static function address(array $address): object
|
|
205
|
+
{
|
|
206
|
+
return (object) [
|
|
207
|
+
'xLgr' => $address['street'],
|
|
208
|
+
'nro' => $address['number'],
|
|
209
|
+
'xCpl' => $address['complement'],
|
|
210
|
+
'xBairro' => $address['district'],
|
|
211
|
+
'cMun' => $address['municipalityIbge'],
|
|
212
|
+
'xMun' => $address['municipalityName'],
|
|
213
|
+
'UF' => $address['uf'],
|
|
214
|
+
'CEP' => $address['postalCode'],
|
|
215
|
+
'cPais' => 1058,
|
|
216
|
+
'xPais' => 'Brasil',
|
|
217
|
+
'fone' => $address['phone'],
|
|
218
|
+
];
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** @param array<string, mixed> $line */
|
|
222
|
+
private function line(Make $make, int $item, array $line): void
|
|
223
|
+
{
|
|
224
|
+
$gtin = $line['gtin'] ?? 'SEM GTIN';
|
|
225
|
+
$make->tagprod((object) [
|
|
226
|
+
'item' => $item,
|
|
227
|
+
'cProd' => $line['code'],
|
|
228
|
+
'cEAN' => $gtin,
|
|
229
|
+
'xProd' => $line['description'],
|
|
230
|
+
'NCM' => $line['ncm'],
|
|
231
|
+
'CEST' => $line['cest'],
|
|
232
|
+
'CFOP' => $line['cfop'],
|
|
233
|
+
'uCom' => $line['unit'],
|
|
234
|
+
'qCom' => self::quantity($line['quantity']),
|
|
235
|
+
'vUnCom' => self::unitValue($line['valueCents'], $line['quantity']),
|
|
236
|
+
'vProd' => self::reais($line['valueCents']),
|
|
237
|
+
'cEANTrib' => $gtin,
|
|
238
|
+
'uTrib' => $line['unit'],
|
|
239
|
+
'qTrib' => self::quantity($line['quantity']),
|
|
240
|
+
'vUnTrib' => self::unitValue($line['valueCents'], $line['quantity']),
|
|
241
|
+
'vDesc' => $line['discountCents'] > 0 ? self::reais($line['discountCents']) : null,
|
|
242
|
+
'indTot' => 1,
|
|
243
|
+
]);
|
|
244
|
+
if ($line['additionalInfo'] !== null) {
|
|
245
|
+
$make->taginfAdProd((object) ['item' => $item, 'infAdProd' => $line['additionalInfo']]);
|
|
246
|
+
}
|
|
247
|
+
$make->tagimposto((object) [
|
|
248
|
+
'item' => $item,
|
|
249
|
+
'vTotTrib' => $line['approximateTaxCents'] === null ? null : self::reais($line['approximateTaxCents']),
|
|
250
|
+
]);
|
|
251
|
+
$this->icms($make, $item, $line['icms']);
|
|
252
|
+
$make->tagPIS(self::contribution($item, $line['pis'], 'PIS'));
|
|
253
|
+
$make->tagCOFINS(self::contribution($item, $line['cofins'], 'COFINS'));
|
|
254
|
+
if ($line['ibsCbs'] !== null) {
|
|
255
|
+
$make->tagIBSCBS(self::ibsCbs($item, $line['ibsCbs']));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** @param array<string, mixed> $icms */
|
|
260
|
+
private function icms(Make $make, int $item, array $icms): void
|
|
261
|
+
{
|
|
262
|
+
if ($icms['regime'] === 'SIMPLES') {
|
|
263
|
+
$make->tagICMSSN((object) [
|
|
264
|
+
'item' => $item,
|
|
265
|
+
'orig' => $icms['origin'],
|
|
266
|
+
'CSOSN' => $icms['csosn'],
|
|
267
|
+
'pCredSN' => isset($icms['creditRateBp']) ? self::percent($icms['creditRateBp']) : null,
|
|
268
|
+
'vCredICMSSN' => isset($icms['creditCents']) ? self::reais($icms['creditCents']) : null,
|
|
269
|
+
]);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
$taxed = $icms['cst'] === '00';
|
|
273
|
+
$make->tagICMS((object) [
|
|
274
|
+
'item' => $item,
|
|
275
|
+
'orig' => $icms['origin'],
|
|
276
|
+
'CST' => $icms['cst'],
|
|
277
|
+
'modBC' => $taxed ? 3 : null,
|
|
278
|
+
'vBC' => $taxed ? self::reais($icms['baseCents']) : null,
|
|
279
|
+
'pICMS' => $taxed ? self::percent($icms['rateBp']) : null,
|
|
280
|
+
'vICMS' => $taxed ? self::reais($icms['amountCents']) : null,
|
|
281
|
+
]);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** @param array<string, mixed> $c */
|
|
285
|
+
private static function contribution(int $item, array $c, string $tax): object
|
|
286
|
+
{
|
|
287
|
+
$carriesFigures = !in_array($c['cst'], ['04', '05', '06', '07', '08', '09'], true);
|
|
288
|
+
return (object) [
|
|
289
|
+
'item' => $item,
|
|
290
|
+
'CST' => $c['cst'],
|
|
291
|
+
'vBC' => $carriesFigures ? self::reais($c['baseCents']) : null,
|
|
292
|
+
"p$tax" => $carriesFigures ? self::percent($c['rateBp']) : null,
|
|
293
|
+
"v$tax" => $carriesFigures ? self::reais($c['amountCents']) : null,
|
|
294
|
+
];
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** @param array<string, mixed> $group */
|
|
298
|
+
private static function ibsCbs(int $item, array $group): object
|
|
299
|
+
{
|
|
300
|
+
$std = ['item' => $item, 'CST' => $group['cst'], 'cClassTrib' => $group['classCode']];
|
|
301
|
+
$f = $group['figures'];
|
|
302
|
+
if ($f === null) {
|
|
303
|
+
return (object) $std;
|
|
304
|
+
}
|
|
305
|
+
$std['vBC'] = self::reais($f['baseCents']);
|
|
306
|
+
$std['vIBS'] = self::reais($f['ibsUfCents'] + $f['ibsMunCents']);
|
|
307
|
+
foreach (['gIBSUF' => ['IBSUF', 'ibsUf'], 'gIBSMun' => ['IBSMun', 'ibsMun'], 'gCBS' => ['CBS', 'cbs']]
|
|
308
|
+
as $prefix => [$tag, $key]) {
|
|
309
|
+
$std["{$prefix}_p$tag"] = self::percent($f["{$key}RateBp"]);
|
|
310
|
+
$std["{$prefix}_v$tag"] = self::reais($f["{$key}Cents"]);
|
|
311
|
+
if ($f['reductionBp'] > 0) {
|
|
312
|
+
$std["{$prefix}_pRedAliq"] = self::percent($f['reductionBp']);
|
|
313
|
+
$std["{$prefix}_pAliqEfet"] = self::effectiveRate($f["{$key}RateBp"], $f['reductionBp']);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return (object) $std;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** @param array<string, mixed> $d */
|
|
320
|
+
private function closing(Make $make, array $d): void
|
|
321
|
+
{
|
|
322
|
+
$make->tagtransp((object) ['modFrete' => self::FREIGHT[$d['freight']]]);
|
|
323
|
+
$make->tagpag((object) ['vTroco' => $d['changeCents'] > 0 ? self::reais($d['changeCents']) : null]);
|
|
324
|
+
foreach ($d['payments'] as $payment) {
|
|
325
|
+
$card = $payment['card'];
|
|
326
|
+
$make->tagdetPag((object) [
|
|
327
|
+
'indPag' => null,
|
|
328
|
+
'tPag' => self::PAYMENT[$payment['method']],
|
|
329
|
+
'xPag' => $payment['description'],
|
|
330
|
+
'vPag' => self::reais($payment['amountCents']),
|
|
331
|
+
'CNPJ' => $card['acquirerCnpj'] ?? null,
|
|
332
|
+
'tBand' => $card['brand'] ?? null,
|
|
333
|
+
'cAut' => $card['authorizationCode'] ?? null,
|
|
334
|
+
'tpIntegra' => $card === null ? null : ($card['integrated'] ? 1 : 2),
|
|
335
|
+
]);
|
|
336
|
+
}
|
|
337
|
+
if ($d['intermediary'] !== null) {
|
|
338
|
+
$make->tagIntermed((object) [
|
|
339
|
+
'CNPJ' => $d['intermediary']['cnpj'],
|
|
340
|
+
'idCadIntTran' => $d['intermediary']['userId'],
|
|
341
|
+
]);
|
|
342
|
+
}
|
|
343
|
+
$info = $d['additionalInfo'];
|
|
344
|
+
if ($info['forTaxpayer'] !== null || $info['forTaxAuthority'] !== null) {
|
|
345
|
+
$make->taginfAdic((object) ['infAdFisco' => $info['forTaxAuthority'], 'infCpl' => $info['forTaxpayer']]);
|
|
346
|
+
}
|
|
347
|
+
$tech = $d['technicalResponsible'];
|
|
348
|
+
if ($tech !== null) {
|
|
349
|
+
$make->taginfRespTec((object) [
|
|
350
|
+
'CNPJ' => $tech['cnpj'],
|
|
351
|
+
'xContato' => $tech['contactName'],
|
|
352
|
+
'email' => $tech['email'],
|
|
353
|
+
'fone' => $tech['phone'],
|
|
354
|
+
]);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private static function reais(int $cents): string
|
|
359
|
+
{
|
|
360
|
+
return number_format($cents / 100, 2, '.', '');
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
private static function percent(int $basisPoints): string
|
|
364
|
+
{
|
|
365
|
+
return number_format($basisPoints / 100, 4, '.', '');
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
private static function effectiveRate(int $rateBp, int $reductionBp): string
|
|
369
|
+
{
|
|
370
|
+
return number_format($rateBp * (10000 - $reductionBp) / 1000000, 4, '.', '');
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private static function quantity(int|float $quantity): string
|
|
374
|
+
{
|
|
375
|
+
return number_format((float) $quantity, 4, '.', '');
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** `vUnCom`: the line's value over its quantity, ten decimals, as the layout writes it. */
|
|
379
|
+
private static function unitValue(int $cents, int|float $quantity): string
|
|
380
|
+
{
|
|
381
|
+
return number_format($cents / 100 / (float) $quantity, 10, '.', '');
|
|
382
|
+
}
|
|
383
|
+
}
|