@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.
- package/README.md +164 -7
- package/dist/chunk-2LBQRYPV.js +21 -0
- package/dist/chunk-2LBQRYPV.js.map +1 -0
- package/dist/chunk-3SDXLSG4.js +24 -0
- package/dist/chunk-3SDXLSG4.js.map +1 -0
- package/dist/chunk-5S2PJHAE.js +85 -0
- package/dist/chunk-5S2PJHAE.js.map +1 -0
- package/dist/chunk-G3V7IYNF.js +192 -0
- package/dist/chunk-G3V7IYNF.js.map +1 -0
- package/dist/chunk-JVQKJNOC.js +14 -0
- package/dist/chunk-JVQKJNOC.js.map +1 -0
- package/dist/chunk-N5DCKYFR.js +610 -0
- package/dist/chunk-N5DCKYFR.js.map +1 -0
- package/dist/chunk-NVRYAAQ4.js +212 -0
- package/dist/chunk-NVRYAAQ4.js.map +1 -0
- package/dist/chunk-PNTKG3DZ.js +47 -0
- package/dist/chunk-PNTKG3DZ.js.map +1 -0
- package/dist/chunk-WTGASIZE.js +247 -0
- package/dist/chunk-WTGASIZE.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 +181 -0
- package/dist/documents/index.js +1234 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/engine/index.d.ts +3 -246
- package/dist/http.d.ts +75 -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 +30 -16
- package/dist/manifest/index.js +11 -17
- package/dist/manifest/index.js.map +1 -1
- 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 +269 -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 +218 -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 +63 -5
- 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 +162 -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 +422 -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 +428 -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 +48 -0
- package/src/documents/helpers.ts +177 -0
- package/src/documents/index.ts +40 -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 +299 -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/http.ts +266 -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 +25 -16
- 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 +318 -0
- package/src/sidecar/index.ts +9 -0
- package/src/sidecar/types.ts +245 -0
|
@@ -0,0 +1,428 @@
|
|
|
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
|
+
/** `tpNF`. An absent `operation` is `OUT`: a document built before the field existed is unchanged. */
|
|
25
|
+
private const OPERATION = ['IN' => 0, 'OUT' => 1];
|
|
26
|
+
private const DESTINATION = ['INTERNAL' => 1, 'INTERSTATE' => 2, 'FOREIGN' => 3];
|
|
27
|
+
private const PRESENCE = [
|
|
28
|
+
'IN_PERSON' => 1,
|
|
29
|
+
'INTERNET' => 2,
|
|
30
|
+
'TELEPHONE' => 3,
|
|
31
|
+
'HOME_DELIVERY' => 4,
|
|
32
|
+
'IN_PERSON_OFF_PREMISES' => 5,
|
|
33
|
+
'OTHER' => 9,
|
|
34
|
+
];
|
|
35
|
+
private const CRT = ['SIMPLES' => 1, 'SIMPLES_EXCESS' => 2, 'NORMAL' => 3, 'MEI' => 4];
|
|
36
|
+
private const IE_STATUS = ['CONTRIBUTOR' => 1, 'EXEMPT' => 2, 'NON_CONTRIBUTOR' => 9];
|
|
37
|
+
private const FREIGHT = [
|
|
38
|
+
'BY_ISSUER' => 0,
|
|
39
|
+
'BY_RECIPIENT' => 1,
|
|
40
|
+
'BY_THIRD_PARTY' => 2,
|
|
41
|
+
'OWN_BY_ISSUER' => 3,
|
|
42
|
+
'OWN_BY_RECIPIENT' => 4,
|
|
43
|
+
'NONE' => 9,
|
|
44
|
+
];
|
|
45
|
+
private const PAYMENT = [
|
|
46
|
+
'CASH' => '01',
|
|
47
|
+
'CHECK' => '02',
|
|
48
|
+
'CREDIT_CARD' => '03',
|
|
49
|
+
'DEBIT_CARD' => '04',
|
|
50
|
+
'STORE_CREDIT' => '05',
|
|
51
|
+
'FOOD_VOUCHER' => '10',
|
|
52
|
+
'MEAL_VOUCHER' => '11',
|
|
53
|
+
'GIFT_VOUCHER' => '12',
|
|
54
|
+
'FUEL_VOUCHER' => '13',
|
|
55
|
+
'BANK_SLIP' => '15',
|
|
56
|
+
'BANK_DEPOSIT' => '16',
|
|
57
|
+
'PIX_DYNAMIC' => '17',
|
|
58
|
+
'TRANSFER' => '18',
|
|
59
|
+
'LOYALTY' => '19',
|
|
60
|
+
'PIX_STATIC' => '20',
|
|
61
|
+
'NO_PAYMENT' => '90',
|
|
62
|
+
'OTHER' => '99',
|
|
63
|
+
];
|
|
64
|
+
/** `indIntermed` is written only where the buyer was not at the counter (NT 2020.006). */
|
|
65
|
+
private const REMOTE_PRESENCE = [2, 3, 4, 9];
|
|
66
|
+
|
|
67
|
+
public const PROCESS_VERSION = 'fiscal-sidecar-1';
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* From 2027 the IBS/CBS go INSIDE `vProd`, and the price without tax
|
|
71
|
+
* travels in NT 2026.008's `vProdLiq`/`vUnComLiq`/`vProdLiqTot` (source: NT
|
|
72
|
+
* 2026.008 v1.00 itself: from 2027 the IBS, CBS and IS values "deverão ser
|
|
73
|
+
* acrescidos ao valor do produto ou serviço, compondo o valor informado no
|
|
74
|
+
* campo vProd"). sped-nfe 5.2.9 cannot write those fields, and document
|
|
75
|
+
* version 1 does not carry them, so a document issued on or after this day
|
|
76
|
+
* is refused rather than emitted wrong. Lifted by the sped-nfe bump that
|
|
77
|
+
* brings NT 2026.008, with document version 2.
|
|
78
|
+
*/
|
|
79
|
+
public const LAYOUT_LIMIT = '2027-01-01';
|
|
80
|
+
public const LAYOUT_LIMIT_CODE = 'NT_2026_008_NOT_SUPPORTED';
|
|
81
|
+
|
|
82
|
+
/** A return (`finNFe` 4) quotes the document it returns (`NFref`); one without a reference is refused. */
|
|
83
|
+
public const RETURN_NEEDS_REFERENCE_CODE = 'RETURN_NEEDS_REFERENCE';
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* An NFC-e has no return purpose: a buyer's goods come back on an NF-e
|
|
87
|
+
* (model 55) of entry that references the NFC-e's key.
|
|
88
|
+
*/
|
|
89
|
+
public const RETURN_ON_NFCE_CODE = 'RETURN_ON_NFCE';
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* @param array<string, mixed> $document
|
|
93
|
+
* @param array{since: string, reason: string}|null $contingency an NFC-e signed offline (`tpEmis = 9`)
|
|
94
|
+
* @return array{xml: string, accessKey: string}
|
|
95
|
+
* @throws ServiceError INVALID when sped-nfe refuses to build it
|
|
96
|
+
*/
|
|
97
|
+
public function build(array $document, Model $model, int $environment, ?array $contingency = null): array
|
|
98
|
+
{
|
|
99
|
+
self::refuseWhatThisLayoutCannotSay($document);
|
|
100
|
+
self::refuseAReturnItCannotBe($document, $model);
|
|
101
|
+
$make = new Make(NfeModule::SCHEMES);
|
|
102
|
+
$make->setOnlyAscii(false);
|
|
103
|
+
$make->setCheckGtin(true);
|
|
104
|
+
try {
|
|
105
|
+
$this->header($make, $document, $model, $environment, $contingency);
|
|
106
|
+
$this->parties($make, $document);
|
|
107
|
+
foreach (array_values($document['lines']) as $index => $line) {
|
|
108
|
+
$this->line($make, $index + 1, $line);
|
|
109
|
+
}
|
|
110
|
+
$this->closing($make, $document);
|
|
111
|
+
$xml = $make->render();
|
|
112
|
+
} catch (ServiceError $error) {
|
|
113
|
+
throw $error;
|
|
114
|
+
} catch (Throwable $failure) {
|
|
115
|
+
throw ServiceError::invalid('The document could not be built.', array_merge(
|
|
116
|
+
[$failure->getMessage()],
|
|
117
|
+
array_values(array_map('strval', $make->getErrors())),
|
|
118
|
+
));
|
|
119
|
+
}
|
|
120
|
+
$errors = array_values(array_map('strval', $make->getErrors()));
|
|
121
|
+
if ($errors !== []) {
|
|
122
|
+
throw ServiceError::invalid('The document could not be built.', $errors);
|
|
123
|
+
}
|
|
124
|
+
return ['xml' => $xml, 'accessKey' => $make->getChave()];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** @param array<string, mixed> $document */
|
|
128
|
+
private static function refuseWhatThisLayoutCannotSay(array $document): void
|
|
129
|
+
{
|
|
130
|
+
if (substr((string) $document['issuedAt'], 0, 10) >= self::LAYOUT_LIMIT) {
|
|
131
|
+
throw new ServiceError(
|
|
132
|
+
\Fiscal\Sidecar\ErrorClass::INVALID,
|
|
133
|
+
'A document issued on or after ' . self::LAYOUT_LIMIT . ' needs NT 2026.008 (vProdLiq), '
|
|
134
|
+
. 'which this service\'s sped-nfe does not write yet.',
|
|
135
|
+
self::LAYOUT_LIMIT_CODE,
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
$details = [];
|
|
139
|
+
foreach (array_values($document['lines']) as $index => $line) {
|
|
140
|
+
$quantity = (float) $line['quantity'];
|
|
141
|
+
if (abs(round($quantity, 4) - $quantity) > 1e-9) {
|
|
142
|
+
$details[] = "lines[$index].quantity: at most four decimals (qCom)";
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if ($details !== []) {
|
|
146
|
+
throw ServiceError::invalid('The document does not fit the NF-e layout.', $details);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* @param array<string, mixed> $document
|
|
152
|
+
* @throws ServiceError INVALID, coded, when the purpose and the model or the references disagree
|
|
153
|
+
*/
|
|
154
|
+
private static function refuseAReturnItCannotBe(array $document, Model $model): void
|
|
155
|
+
{
|
|
156
|
+
$isReturn = $document['purpose'] === 'RETURN';
|
|
157
|
+
if ($model === Model::NFCE && $isReturn) {
|
|
158
|
+
throw new ServiceError(
|
|
159
|
+
\Fiscal\Sidecar\ErrorClass::INVALID,
|
|
160
|
+
'An NFC-e has no return purpose: a return is an NF-e (model 55) of entry referencing the NFC-e.',
|
|
161
|
+
self::RETURN_ON_NFCE_CODE,
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
if ($model === Model::NFCE && ($document['operation'] ?? 'OUT') === 'IN') {
|
|
165
|
+
throw ServiceError::invalid('An NFC-e is an outgoing document.', ['operation: an NFC-e takes "OUT" (tpNF 1)']);
|
|
166
|
+
}
|
|
167
|
+
if ($model === Model::NFCE && ($document['referencedDocuments'] ?? []) !== []) {
|
|
168
|
+
// SEFAZ rejects NFref on a model 65 with 708, after the number is spent.
|
|
169
|
+
throw ServiceError::invalid('An NFC-e references no document.', ['referencedDocuments: an NFC-e takes none (708)']);
|
|
170
|
+
}
|
|
171
|
+
if ($isReturn && ($document['referencedDocuments'] ?? []) === []) {
|
|
172
|
+
throw new ServiceError(
|
|
173
|
+
\Fiscal\Sidecar\ErrorClass::INVALID,
|
|
174
|
+
'A return must reference the document it returns (referencedDocuments).',
|
|
175
|
+
self::RETURN_NEEDS_REFERENCE_CODE,
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** @param array<string, mixed> $d */
|
|
181
|
+
private function header(Make $make, array $d, Model $model, int $environment, ?array $contingency): void
|
|
182
|
+
{
|
|
183
|
+
$make->taginfNFe((object) ['Id' => null, 'versao' => '4.00']);
|
|
184
|
+
$presence = self::PRESENCE[$d['presence']];
|
|
185
|
+
$make->tagide((object) [
|
|
186
|
+
'cUF' => UFList::getCodeByUF($d['issuer']['address']['uf']),
|
|
187
|
+
'cNF' => $d['keyCode'],
|
|
188
|
+
'natOp' => $d['operationNature'],
|
|
189
|
+
'mod' => $model->code(),
|
|
190
|
+
'serie' => $d['series'],
|
|
191
|
+
'nNF' => $d['number'],
|
|
192
|
+
'dhEmi' => $d['issuedAt'],
|
|
193
|
+
'dhSaiEnt' => null,
|
|
194
|
+
'tpNF' => self::OPERATION[$d['operation'] ?? 'OUT'],
|
|
195
|
+
'idDest' => self::DESTINATION[$d['destination']],
|
|
196
|
+
'cMunFG' => $d['issuer']['address']['municipalityIbge'],
|
|
197
|
+
'tpImp' => $model === Model::NFCE ? 4 : 1,
|
|
198
|
+
'tpEmis' => $contingency === null ? 1 : 9,
|
|
199
|
+
'cDV' => null,
|
|
200
|
+
'tpAmb' => $environment,
|
|
201
|
+
'finNFe' => self::PURPOSE[$d['purpose']],
|
|
202
|
+
'indFinal' => $d['finalConsumer'] ? 1 : 0,
|
|
203
|
+
'indPres' => $presence,
|
|
204
|
+
'indIntermed' => in_array($presence, self::REMOTE_PRESENCE, true)
|
|
205
|
+
? ($d['intermediary'] === null ? 0 : 1)
|
|
206
|
+
: null,
|
|
207
|
+
'procEmi' => 0,
|
|
208
|
+
'verProc' => self::PROCESS_VERSION,
|
|
209
|
+
'dhCont' => $contingency['since'] ?? null,
|
|
210
|
+
'xJust' => $contingency['reason'] ?? null,
|
|
211
|
+
]);
|
|
212
|
+
foreach ($d['referencedDocuments'] ?? [] as $referenced) {
|
|
213
|
+
$make->tagrefNFe((object) ['refNFe' => $referenced['accessKey']]);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** @param array<string, mixed> $d */
|
|
218
|
+
private function parties(Make $make, array $d): void
|
|
219
|
+
{
|
|
220
|
+
$issuer = $d['issuer'];
|
|
221
|
+
$make->tagEmit((object) [
|
|
222
|
+
'xNome' => $issuer['legalName'],
|
|
223
|
+
'xFant' => $issuer['tradeName'],
|
|
224
|
+
'IE' => $issuer['stateRegistration'],
|
|
225
|
+
'CRT' => self::CRT[$issuer['taxRegime']],
|
|
226
|
+
'CNPJ' => $issuer['cnpj'],
|
|
227
|
+
]);
|
|
228
|
+
$make->tagenderEmit(self::address($issuer['address']));
|
|
229
|
+
$buyer = $d['buyer'];
|
|
230
|
+
if ($buyer === null) {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
$document = $buyer['document'];
|
|
234
|
+
$make->tagdest((object) [
|
|
235
|
+
'xNome' => $buyer['name'],
|
|
236
|
+
'CNPJ' => $document['kind'] === 'CNPJ' ? $document['number'] : null,
|
|
237
|
+
'CPF' => $document['kind'] === 'CPF' ? $document['number'] : null,
|
|
238
|
+
'idEstrangeiro' => $document['kind'] === 'FOREIGN' ? $document['number'] : null,
|
|
239
|
+
'indIEDest' => self::IE_STATUS[$buyer['stateRegistrationStatus']],
|
|
240
|
+
'IE' => $buyer['stateRegistration'],
|
|
241
|
+
'email' => $buyer['email'],
|
|
242
|
+
]);
|
|
243
|
+
if ($buyer['address'] !== null) {
|
|
244
|
+
$make->tagenderDest(self::address($buyer['address']));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** @param array<string, mixed> $address */
|
|
249
|
+
private static function address(array $address): object
|
|
250
|
+
{
|
|
251
|
+
return (object) [
|
|
252
|
+
'xLgr' => $address['street'],
|
|
253
|
+
'nro' => $address['number'],
|
|
254
|
+
'xCpl' => $address['complement'],
|
|
255
|
+
'xBairro' => $address['district'],
|
|
256
|
+
'cMun' => $address['municipalityIbge'],
|
|
257
|
+
'xMun' => $address['municipalityName'],
|
|
258
|
+
'UF' => $address['uf'],
|
|
259
|
+
'CEP' => $address['postalCode'],
|
|
260
|
+
'cPais' => 1058,
|
|
261
|
+
'xPais' => 'Brasil',
|
|
262
|
+
'fone' => $address['phone'],
|
|
263
|
+
];
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** @param array<string, mixed> $line */
|
|
267
|
+
private function line(Make $make, int $item, array $line): void
|
|
268
|
+
{
|
|
269
|
+
$gtin = $line['gtin'] ?? 'SEM GTIN';
|
|
270
|
+
$make->tagprod((object) [
|
|
271
|
+
'item' => $item,
|
|
272
|
+
'cProd' => $line['code'],
|
|
273
|
+
'cEAN' => $gtin,
|
|
274
|
+
'xProd' => $line['description'],
|
|
275
|
+
'NCM' => $line['ncm'],
|
|
276
|
+
'CEST' => $line['cest'],
|
|
277
|
+
'CFOP' => $line['cfop'],
|
|
278
|
+
'uCom' => $line['unit'],
|
|
279
|
+
'qCom' => self::quantity($line['quantity']),
|
|
280
|
+
'vUnCom' => self::unitValue($line['valueCents'], $line['quantity']),
|
|
281
|
+
'vProd' => self::reais($line['valueCents']),
|
|
282
|
+
'cEANTrib' => $gtin,
|
|
283
|
+
'uTrib' => $line['unit'],
|
|
284
|
+
'qTrib' => self::quantity($line['quantity']),
|
|
285
|
+
'vUnTrib' => self::unitValue($line['valueCents'], $line['quantity']),
|
|
286
|
+
'vDesc' => $line['discountCents'] > 0 ? self::reais($line['discountCents']) : null,
|
|
287
|
+
'indTot' => 1,
|
|
288
|
+
]);
|
|
289
|
+
if ($line['additionalInfo'] !== null) {
|
|
290
|
+
$make->taginfAdProd((object) ['item' => $item, 'infAdProd' => $line['additionalInfo']]);
|
|
291
|
+
}
|
|
292
|
+
$make->tagimposto((object) [
|
|
293
|
+
'item' => $item,
|
|
294
|
+
'vTotTrib' => $line['approximateTaxCents'] === null ? null : self::reais($line['approximateTaxCents']),
|
|
295
|
+
]);
|
|
296
|
+
$this->icms($make, $item, $line['icms']);
|
|
297
|
+
$make->tagPIS(self::contribution($item, $line['pis'], 'PIS'));
|
|
298
|
+
$make->tagCOFINS(self::contribution($item, $line['cofins'], 'COFINS'));
|
|
299
|
+
if ($line['ibsCbs'] !== null) {
|
|
300
|
+
$make->tagIBSCBS(self::ibsCbs($item, $line['ibsCbs']));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** @param array<string, mixed> $icms */
|
|
305
|
+
private function icms(Make $make, int $item, array $icms): void
|
|
306
|
+
{
|
|
307
|
+
if ($icms['regime'] === 'SIMPLES') {
|
|
308
|
+
$make->tagICMSSN((object) [
|
|
309
|
+
'item' => $item,
|
|
310
|
+
'orig' => $icms['origin'],
|
|
311
|
+
'CSOSN' => $icms['csosn'],
|
|
312
|
+
'pCredSN' => isset($icms['creditRateBp']) ? self::percent($icms['creditRateBp']) : null,
|
|
313
|
+
'vCredICMSSN' => isset($icms['creditCents']) ? self::reais($icms['creditCents']) : null,
|
|
314
|
+
]);
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
$taxed = $icms['cst'] === '00';
|
|
318
|
+
$make->tagICMS((object) [
|
|
319
|
+
'item' => $item,
|
|
320
|
+
'orig' => $icms['origin'],
|
|
321
|
+
'CST' => $icms['cst'],
|
|
322
|
+
'modBC' => $taxed ? 3 : null,
|
|
323
|
+
'vBC' => $taxed ? self::reais($icms['baseCents']) : null,
|
|
324
|
+
'pICMS' => $taxed ? self::percent($icms['rateBp']) : null,
|
|
325
|
+
'vICMS' => $taxed ? self::reais($icms['amountCents']) : null,
|
|
326
|
+
]);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** @param array<string, mixed> $c */
|
|
330
|
+
private static function contribution(int $item, array $c, string $tax): object
|
|
331
|
+
{
|
|
332
|
+
$carriesFigures = !in_array($c['cst'], ['04', '05', '06', '07', '08', '09'], true);
|
|
333
|
+
return (object) [
|
|
334
|
+
'item' => $item,
|
|
335
|
+
'CST' => $c['cst'],
|
|
336
|
+
'vBC' => $carriesFigures ? self::reais($c['baseCents']) : null,
|
|
337
|
+
"p$tax" => $carriesFigures ? self::percent($c['rateBp']) : null,
|
|
338
|
+
"v$tax" => $carriesFigures ? self::reais($c['amountCents']) : null,
|
|
339
|
+
];
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** @param array<string, mixed> $group */
|
|
343
|
+
private static function ibsCbs(int $item, array $group): object
|
|
344
|
+
{
|
|
345
|
+
$std = ['item' => $item, 'CST' => $group['cst'], 'cClassTrib' => $group['classCode']];
|
|
346
|
+
$f = $group['figures'];
|
|
347
|
+
if ($f === null) {
|
|
348
|
+
return (object) $std;
|
|
349
|
+
}
|
|
350
|
+
$std['vBC'] = self::reais($f['baseCents']);
|
|
351
|
+
$std['vIBS'] = self::reais($f['ibsUfCents'] + $f['ibsMunCents']);
|
|
352
|
+
foreach (['gIBSUF' => ['IBSUF', 'ibsUf'], 'gIBSMun' => ['IBSMun', 'ibsMun'], 'gCBS' => ['CBS', 'cbs']]
|
|
353
|
+
as $prefix => [$tag, $key]) {
|
|
354
|
+
$std["{$prefix}_p$tag"] = self::percent($f["{$key}RateBp"]);
|
|
355
|
+
$std["{$prefix}_v$tag"] = self::reais($f["{$key}Cents"]);
|
|
356
|
+
if ($f['reductionBp'] > 0) {
|
|
357
|
+
$std["{$prefix}_pRedAliq"] = self::percent($f['reductionBp']);
|
|
358
|
+
$std["{$prefix}_pAliqEfet"] = self::effectiveRate($f["{$key}RateBp"], $f['reductionBp']);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return (object) $std;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** @param array<string, mixed> $d */
|
|
365
|
+
private function closing(Make $make, array $d): void
|
|
366
|
+
{
|
|
367
|
+
$make->tagtransp((object) ['modFrete' => self::FREIGHT[$d['freight']]]);
|
|
368
|
+
$make->tagpag((object) ['vTroco' => $d['changeCents'] > 0 ? self::reais($d['changeCents']) : null]);
|
|
369
|
+
foreach ($d['payments'] as $payment) {
|
|
370
|
+
$card = $payment['card'];
|
|
371
|
+
$make->tagdetPag((object) [
|
|
372
|
+
'indPag' => null,
|
|
373
|
+
'tPag' => self::PAYMENT[$payment['method']],
|
|
374
|
+
'xPag' => $payment['description'],
|
|
375
|
+
'vPag' => self::reais($payment['amountCents']),
|
|
376
|
+
'CNPJ' => $card['acquirerCnpj'] ?? null,
|
|
377
|
+
'tBand' => $card['brand'] ?? null,
|
|
378
|
+
'cAut' => $card['authorizationCode'] ?? null,
|
|
379
|
+
'tpIntegra' => $card === null ? null : ($card['integrated'] ? 1 : 2),
|
|
380
|
+
]);
|
|
381
|
+
}
|
|
382
|
+
if ($d['intermediary'] !== null) {
|
|
383
|
+
$make->tagIntermed((object) [
|
|
384
|
+
'CNPJ' => $d['intermediary']['cnpj'],
|
|
385
|
+
'idCadIntTran' => $d['intermediary']['userId'],
|
|
386
|
+
]);
|
|
387
|
+
}
|
|
388
|
+
$info = $d['additionalInfo'];
|
|
389
|
+
if ($info['forTaxpayer'] !== null || $info['forTaxAuthority'] !== null) {
|
|
390
|
+
$make->taginfAdic((object) ['infAdFisco' => $info['forTaxAuthority'], 'infCpl' => $info['forTaxpayer']]);
|
|
391
|
+
}
|
|
392
|
+
$tech = $d['technicalResponsible'];
|
|
393
|
+
if ($tech !== null) {
|
|
394
|
+
$make->taginfRespTec((object) [
|
|
395
|
+
'CNPJ' => $tech['cnpj'],
|
|
396
|
+
'xContato' => $tech['contactName'],
|
|
397
|
+
'email' => $tech['email'],
|
|
398
|
+
'fone' => $tech['phone'],
|
|
399
|
+
]);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private static function reais(int $cents): string
|
|
404
|
+
{
|
|
405
|
+
return number_format($cents / 100, 2, '.', '');
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
private static function percent(int $basisPoints): string
|
|
409
|
+
{
|
|
410
|
+
return number_format($basisPoints / 100, 4, '.', '');
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
private static function effectiveRate(int $rateBp, int $reductionBp): string
|
|
414
|
+
{
|
|
415
|
+
return number_format($rateBp * (10000 - $reductionBp) / 1000000, 4, '.', '');
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
private static function quantity(int|float $quantity): string
|
|
419
|
+
{
|
|
420
|
+
return number_format((float) $quantity, 4, '.', '');
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** `vUnCom`: the line's value over its quantity, ten decimals, as the layout writes it. */
|
|
424
|
+
private static function unitValue(int $cents, int|float $quantity): string
|
|
425
|
+
{
|
|
426
|
+
return number_format($cents / 100 / (float) $quantity, 10, '.', '');
|
|
427
|
+
}
|
|
428
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar\Nfe;
|
|
6
|
+
|
|
7
|
+
use Fiscal\Sidecar\ServiceError;
|
|
8
|
+
use JsonSchema\Constraints\Constraint;
|
|
9
|
+
use JsonSchema\Validator;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The neutral document's JSON schema — the very file `@12-apps/fiscal`
|
|
13
|
+
* publishes beside its `SaleForDocument` type.
|
|
14
|
+
*/
|
|
15
|
+
final class DocumentSchema
|
|
16
|
+
{
|
|
17
|
+
public const PATH = __DIR__ . '/../../schema/sale-for-document.schema.json';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param mixed $document the decoded JSON (arrays)
|
|
21
|
+
* @throws ServiceError INVALID, one detail per violation
|
|
22
|
+
*/
|
|
23
|
+
public static function assertValid(mixed $document): void
|
|
24
|
+
{
|
|
25
|
+
$schema = json_decode((string) file_get_contents(self::PATH));
|
|
26
|
+
$data = json_decode((string) json_encode($document));
|
|
27
|
+
$validator = new Validator();
|
|
28
|
+
$validator->validate($data, $schema, Constraint::CHECK_MODE_NORMAL);
|
|
29
|
+
if ($validator->isValid()) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
$details = [];
|
|
33
|
+
foreach ($validator->getErrors() as $error) {
|
|
34
|
+
$where = $error['property'] !== '' ? $error['property'] : '(document)';
|
|
35
|
+
$details[] = "$where: {$error['message']}";
|
|
36
|
+
}
|
|
37
|
+
throw ServiceError::invalid('The document does not match the SaleForDocument schema.', $details);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar\Nfe;
|
|
6
|
+
|
|
7
|
+
use Fiscal\Sidecar\ServiceError;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The envelope fields of a request, read with their rules. A field that breaks
|
|
11
|
+
* one is INVALID, named, and its value is never quoted back (it may be the
|
|
12
|
+
* password).
|
|
13
|
+
*/
|
|
14
|
+
final class Input
|
|
15
|
+
{
|
|
16
|
+
/** @param array<string, mixed> $body */
|
|
17
|
+
public function __construct(private readonly array $body)
|
|
18
|
+
{
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** `tpAmb`: 1 production, 2 homologação. */
|
|
22
|
+
public function environment(): int
|
|
23
|
+
{
|
|
24
|
+
return match ($this->body['environment'] ?? null) {
|
|
25
|
+
'producao' => 1,
|
|
26
|
+
'homologacao' => 2,
|
|
27
|
+
default => throw ServiceError::invalid('environment must be "homologacao" or "producao".'),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @return array{pfx: string, password: string} */
|
|
32
|
+
public function certificate(): array
|
|
33
|
+
{
|
|
34
|
+
$certificate = $this->body['certificate'] ?? null;
|
|
35
|
+
if (!is_array($certificate) || !is_string($certificate['pfxBase64'] ?? null)
|
|
36
|
+
|| !is_string($certificate['password'] ?? null)) {
|
|
37
|
+
throw ServiceError::invalid('certificate must be { pfxBase64, password }.');
|
|
38
|
+
}
|
|
39
|
+
$pfx = base64_decode($certificate['pfxBase64'], true);
|
|
40
|
+
if ($pfx === false || $pfx === '') {
|
|
41
|
+
throw ServiceError::invalid('certificate.pfxBase64 is not base64.');
|
|
42
|
+
}
|
|
43
|
+
return ['pfx' => $pfx, 'password' => $certificate['password']];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** @return array{id: string, token: string}|null */
|
|
47
|
+
public function csc(Model $model): ?array
|
|
48
|
+
{
|
|
49
|
+
$csc = $this->body['csc'] ?? null;
|
|
50
|
+
if ($model === Model::NFE) {
|
|
51
|
+
if ($csc !== null) {
|
|
52
|
+
throw ServiceError::invalid('csc belongs to an NFC-e; an NF-e takes null.');
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
if (!is_array($csc) || !is_string($csc['id'] ?? null) || !is_string($csc['token'] ?? null)
|
|
57
|
+
|| preg_match('/^[0-9]{1,6}$/', $csc['id']) !== 1 || strlen($csc['token']) < 16
|
|
58
|
+
|| strlen($csc['token']) > 36) {
|
|
59
|
+
throw ServiceError::invalid('An NFC-e needs csc: { id: up to 6 digits, token: 16 to 36 characters }.');
|
|
60
|
+
}
|
|
61
|
+
return ['id' => $csc['id'], 'token' => $csc['token']];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @return array<string, mixed> */
|
|
65
|
+
public function document(): array
|
|
66
|
+
{
|
|
67
|
+
$document = $this->body['document'] ?? null;
|
|
68
|
+
if (!is_array($document)) {
|
|
69
|
+
throw ServiceError::invalid('document must be a SaleForDocument object.');
|
|
70
|
+
}
|
|
71
|
+
DocumentSchema::assertValid($document);
|
|
72
|
+
return $document;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @return array{since: string, reason: string} */
|
|
76
|
+
public function contingency(): array
|
|
77
|
+
{
|
|
78
|
+
$contingency = $this->body['contingency'] ?? null;
|
|
79
|
+
$since = is_array($contingency) ? ($contingency['since'] ?? null) : null;
|
|
80
|
+
$reason = is_array($contingency) ? ($contingency['reason'] ?? null) : null;
|
|
81
|
+
if (!is_string($since) || \DateTimeImmutable::createFromFormat(DATE_ATOM, $since) === false
|
|
82
|
+
|| !is_string($reason) || mb_strlen(trim($reason)) < 15 || mb_strlen($reason) > 256) {
|
|
83
|
+
throw ServiceError::invalid(
|
|
84
|
+
'contingency must be { since: ISO 8601 with offset, reason: 15 to 256 characters }.',
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
return ['since' => $since, 'reason' => trim($reason)];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
public function accessKey(string $field = 'accessKey'): string
|
|
91
|
+
{
|
|
92
|
+
$key = $this->body[$field] ?? null;
|
|
93
|
+
if (!is_string($key) || preg_match('/^[0-9]{6}[A-Z0-9]{12}[0-9]{26}$/', $key) !== 1) {
|
|
94
|
+
throw ServiceError::invalid("$field must be the 44-character access key.");
|
|
95
|
+
}
|
|
96
|
+
return $key;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
public function digits(string $field, int $min, int $max): int
|
|
100
|
+
{
|
|
101
|
+
$value = $this->body[$field] ?? null;
|
|
102
|
+
if (!is_int($value) || $value < $min || $value > $max) {
|
|
103
|
+
throw ServiceError::invalid("$field must be an integer from $min to $max.");
|
|
104
|
+
}
|
|
105
|
+
return $value;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
public function text(string $field, int $min, int $max): string
|
|
109
|
+
{
|
|
110
|
+
$value = $this->body[$field] ?? null;
|
|
111
|
+
if (!is_string($value) || mb_strlen(trim($value)) < $min || mb_strlen($value) > $max) {
|
|
112
|
+
throw ServiceError::invalid("$field must be text of $min to $max characters.");
|
|
113
|
+
}
|
|
114
|
+
return trim($value);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
public function pattern(string $field, string $regex, string $rule): string
|
|
118
|
+
{
|
|
119
|
+
$value = $this->body[$field] ?? null;
|
|
120
|
+
if (!is_string($value) || preg_match($regex, $value) !== 1) {
|
|
121
|
+
throw ServiceError::invalid("$field must be $rule.");
|
|
122
|
+
}
|
|
123
|
+
return $value;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar\Nfe;
|
|
6
|
+
|
|
7
|
+
/** The two document models sped-nfe issues, by their path segment. */
|
|
8
|
+
enum Model: string
|
|
9
|
+
{
|
|
10
|
+
case NFE = 'nfe';
|
|
11
|
+
case NFCE = 'nfce';
|
|
12
|
+
|
|
13
|
+
public function code(): int
|
|
14
|
+
{
|
|
15
|
+
return $this === self::NFE ? 55 : 65;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar\Nfe;
|
|
6
|
+
|
|
7
|
+
use Composer\InstalledVersions;
|
|
8
|
+
use Fiscal\Sidecar\Http\Request;
|
|
9
|
+
use Fiscal\Sidecar\Http\Response;
|
|
10
|
+
use Fiscal\Sidecar\Http\Router;
|
|
11
|
+
use Fiscal\Sidecar\Module;
|
|
12
|
+
use Fiscal\Sidecar\Nfe\Transport\Transport;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* sped-nfe behind the service: models 55 (`/nfe/...`) and 65 (`/nfce/...`),
|
|
16
|
+
* and `/inutilize`, which names its model in the body.
|
|
17
|
+
*/
|
|
18
|
+
final class NfeModule implements Module
|
|
19
|
+
{
|
|
20
|
+
/** The schema package the layout is built and validated against (Pacote de Liberação 010f). */
|
|
21
|
+
public const SCHEMES = 'PL_010_V1.30';
|
|
22
|
+
public const LIBRARY = 'nfephp-org/sped-nfe';
|
|
23
|
+
|
|
24
|
+
public function __construct(private readonly Transport $transport)
|
|
25
|
+
{
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
public function register(Router $router): void
|
|
29
|
+
{
|
|
30
|
+
foreach (Model::cases() as $model) {
|
|
31
|
+
$prefix = '/' . $model->value;
|
|
32
|
+
$router->add('POST', "$prefix/issue", fn (Request $r): Response => $this->service()->issue($model, self::in($r)));
|
|
33
|
+
$router->add('POST', "$prefix/transmit", fn (Request $r): Response => $this->service()->transmit($model, self::in($r)));
|
|
34
|
+
$router->add('POST', "$prefix/cancel", fn (Request $r): Response => $this->service()->cancel($model, self::in($r)));
|
|
35
|
+
$router->add('POST', "$prefix/lookup", fn (Request $r): Response => $this->service()->lookup($model, self::in($r)));
|
|
36
|
+
}
|
|
37
|
+
$router->add('POST', '/nfce/cancel-substitution', fn (Request $r): Response => $this->service()->cancelBySubstitution(self::in($r)));
|
|
38
|
+
$router->add('POST', '/nfce/sign-contingency', fn (Request $r): Response => $this->service()->signContingency(self::in($r)));
|
|
39
|
+
$router->add('POST', '/inutilize', fn (Request $r): Response => $this->service()->inutilize(self::in($r)));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
public function libraries(): array
|
|
43
|
+
{
|
|
44
|
+
return [self::LIBRARY => (string) InstalledVersions::getPrettyVersion(self::LIBRARY)];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
public function health(): array
|
|
48
|
+
{
|
|
49
|
+
return ['nfeSchemas' => self::SCHEMES, 'sefazTlsVerify' => $this->transport->verifiesServer()];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A fresh service per call: nothing one call opens is reachable from the next. */
|
|
53
|
+
private function service(): NfeService
|
|
54
|
+
{
|
|
55
|
+
return new NfeService($this->transport);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private static function in(Request $request): Input
|
|
59
|
+
{
|
|
60
|
+
return new Input($request->json());
|
|
61
|
+
}
|
|
62
|
+
}
|