@12-apps/fiscal 1.4.0 → 1.6.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 +46 -4
- package/dist/{chunk-EDEGIADD.js → chunk-2JVTHJAU.js} +3 -3
- package/dist/{chunk-2ISYBTCE.js → chunk-CEK2GDRY.js} +15 -6
- package/dist/chunk-CEK2GDRY.js.map +1 -0
- package/dist/{chunk-GF3DXCD2.js → chunk-GH452ITO.js} +1 -1
- package/dist/{chunk-GF3DXCD2.js.map → chunk-GH452ITO.js.map} +1 -1
- package/dist/{chunk-MGTROA7K.js → chunk-OAQSGDZ7.js} +11 -7
- package/dist/chunk-OAQSGDZ7.js.map +1 -0
- package/dist/{chunk-OSYB7CVT.js → chunk-P7CRGZGO.js} +2 -2
- package/dist/{chunk-H33BK623.js → chunk-WRYCYXRA.js} +1 -1
- package/dist/{chunk-H33BK623.js.map → chunk-WRYCYXRA.js.map} +1 -1
- package/dist/{chunk-F2PGQVWL.js → chunk-YHSO3476.js} +7 -6
- package/dist/chunk-YHSO3476.js.map +1 -0
- package/dist/{chunk-JVQKJNOC.js → chunk-ZKWVKCGJ.js} +1 -1
- package/dist/chunk-ZKWVKCGJ.js.map +1 -0
- package/dist/{context-CLSMOSuf.d.ts → context-Cyvfr2YB.d.ts} +167 -20
- package/dist/danfe/index.d.ts +7 -0
- package/dist/danfe/index.js +2 -2
- package/dist/documents/index.d.ts +154 -34
- package/dist/documents/index.js +1193 -306
- package/dist/documents/index.js.map +1 -1
- package/dist/engine/index.d.ts +2 -2
- package/dist/http.d.ts +6 -5
- package/dist/http.js +5 -5
- package/dist/issuer/index.d.ts +10 -3
- package/dist/issuer/index.js +27 -4
- package/dist/issuer/index.js.map +1 -1
- package/dist/jobs.d.ts +5 -5
- package/dist/jobs.js +4 -4
- package/dist/manifest/index.d.ts +6 -4
- package/dist/manifest/index.js.map +1 -1
- package/dist/manifest/server.d.ts +5 -5
- package/dist/manifest/server.js +7 -7
- package/dist/notifications.d.ts +4 -4
- package/dist/notifications.js +3 -3
- package/dist/sale/index.d.ts +29 -1
- package/dist/sale/index.js +7 -0
- package/dist/sale/index.js.map +1 -1
- package/dist/{service-hR3tgLpO.d.ts → service-BCK9aXop.d.ts} +99 -6
- package/dist/sidecar/index.d.ts +35 -210
- package/dist/sidecar/index.js +30 -2
- package/dist/sidecar/index.js.map +1 -1
- package/dist/{types-B1b8LIWX.d.ts → types-BLdkww6G.d.ts} +1 -1
- package/dist/{types-BIJqm5GM.d.ts → types-Sk010Em2.d.ts} +25 -4
- package/dist/types-Z5E14EPw.d.ts +254 -0
- package/package.json +2 -1
- package/prisma/fiscal.prisma +50 -1
- package/prisma/migrations/20261118120000_fiscal_link_payment_event/migration.sql +9 -0
- package/prisma/migrations/20261118180000_fiscal_contingency_blocks/migration.sql +64 -0
- package/sidecar/README.md +53 -1
- package/sidecar/bin/check-platform.php +29 -0
- package/sidecar/composer.json +1 -1
- package/sidecar/composer.lock +7 -7
- package/sidecar/extensions.json +12 -0
- package/sidecar/schema/sale-for-document.schema.json +18 -1
- package/sidecar/src/Http/Request.php +6 -1
- package/sidecar/src/Kernel.php +39 -1
- package/sidecar/src/Nfe/DocumentMapper.php +27 -0
- package/sidecar/src/Nfe/Input.php +10 -0
- package/sidecar/src/Nfe/NfeModule.php +1 -0
- package/sidecar/src/Nfe/NfeService.php +120 -0
- package/sidecar/src/Nfe/SefazReply.php +21 -0
- package/sidecar/src/Platform.php +84 -0
- package/src/danfe/render.ts +16 -5
- package/src/documents/contingency-gaps.ts +88 -0
- package/src/documents/contingency-pass.ts +157 -0
- package/src/documents/contingency-xml.ts +136 -0
- package/src/documents/contingency.ts +257 -0
- package/src/documents/errors.ts +8 -1
- package/src/documents/helpers.ts +5 -0
- package/src/documents/index.ts +25 -2
- package/src/documents/machine-steps.ts +12 -2
- package/src/documents/machine.ts +7 -0
- package/src/documents/memory-blocks.ts +118 -0
- package/src/documents/memory.ts +6 -2
- package/src/documents/payment-link.ts +156 -0
- package/src/documents/ports.ts +163 -13
- package/src/documents/service.ts +14 -0
- package/src/documents/sql-blocks.ts +202 -0
- package/src/documents/sql-store.ts +4 -3
- package/src/documents/types.ts +2 -1
- package/src/http.ts +1 -0
- package/src/issuer/port.ts +24 -1
- package/src/issuer/sidecar.ts +37 -3
- package/src/manifest/index.ts +6 -4
- package/src/sale/index.ts +1 -0
- package/src/sale/types.ts +30 -0
- package/src/sidecar/index.ts +2 -0
- package/src/sidecar/platform.ts +55 -0
- package/src/sidecar/types.ts +38 -0
- package/dist/chunk-2ISYBTCE.js.map +0 -1
- package/dist/chunk-F2PGQVWL.js.map +0 -1
- package/dist/chunk-JVQKJNOC.js.map +0 -1
- package/dist/chunk-MGTROA7K.js.map +0 -1
- /package/dist/{chunk-EDEGIADD.js.map → chunk-2JVTHJAU.js.map} +0 -0
- /package/dist/{chunk-OSYB7CVT.js.map → chunk-P7CRGZGO.js.map} +0 -0
|
@@ -68,6 +68,27 @@ final class SefazReply
|
|
|
68
68
|
return $node === null ? null : (string) $this->dom->saveXML($node);
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Every `$tag` element, serialised, in document order.
|
|
73
|
+
*
|
|
74
|
+
* @return list<string>
|
|
75
|
+
*/
|
|
76
|
+
public function all(string $tag): array
|
|
77
|
+
{
|
|
78
|
+
$found = [];
|
|
79
|
+
foreach ($this->dom->getElementsByTagName($tag) as $node) {
|
|
80
|
+
$found[] = (string) $this->dom->saveXML($node);
|
|
81
|
+
}
|
|
82
|
+
return $found;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The attribute `$name` of the first `$tag` element, or null. */
|
|
86
|
+
public function attribute(string $tag, string $name): ?string
|
|
87
|
+
{
|
|
88
|
+
$node = $this->group($tag);
|
|
89
|
+
return $node === null || !$node->hasAttribute($name) ? null : $node->getAttribute($name);
|
|
90
|
+
}
|
|
91
|
+
|
|
71
92
|
public function has(string $group): bool
|
|
72
93
|
{
|
|
73
94
|
return $this->group($group) !== null;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Fiscal\Sidecar;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* What a PHP must carry to run the service (FUT-4717): the minor version and
|
|
9
|
+
* the extensions `extensions.json` lists — every `ext-*` the service and its
|
|
10
|
+
* locked libraries require. A bundled static PHP (a desktop install, no
|
|
11
|
+
* Docker) is checked against it at build time with `bin/check-platform.php`,
|
|
12
|
+
* so a library bump that needs a new extension fails that build, not a sale.
|
|
13
|
+
*
|
|
14
|
+
* `ini` is what the image's `docker/php.ini` guarantees and a bundled PHP is
|
|
15
|
+
* launched with as `-d` flags: no error printed into a response, a stack
|
|
16
|
+
* trace with no arguments (a password, a certificate, the launch token), no
|
|
17
|
+
* upload spooled to disk.
|
|
18
|
+
*/
|
|
19
|
+
final class Platform
|
|
20
|
+
{
|
|
21
|
+
/** @return array{php: string, extensions: list<string>, sapi: list<string>, ini: array<string, string>} */
|
|
22
|
+
public static function required(?string $file = null): array
|
|
23
|
+
{
|
|
24
|
+
$raw = (string) file_get_contents($file ?? dirname(__DIR__) . '/extensions.json');
|
|
25
|
+
/** @var array{php: string, extensions: list<string>, sapi: list<string>, ini: array<string, string>} $decoded */
|
|
26
|
+
$decoded = json_decode($raw, true, 8, JSON_THROW_ON_ERROR);
|
|
27
|
+
return $decoded;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* What this PHP lacks, as readable lines; empty when it can run the service.
|
|
32
|
+
*
|
|
33
|
+
* @param list<string> $loaded extension names, as `get_loaded_extensions()` answers them
|
|
34
|
+
* @return list<string>
|
|
35
|
+
*/
|
|
36
|
+
public static function missing(array $loaded, string $phpVersion, ?array $required = null): array
|
|
37
|
+
{
|
|
38
|
+
$required ??= self::required();
|
|
39
|
+
$have = array_map('strtolower', $loaded);
|
|
40
|
+
$problems = [];
|
|
41
|
+
if (!str_starts_with($phpVersion . '.', $required['php'] . '.')) {
|
|
42
|
+
$problems[] = "PHP {$required['php']} is required, this is $phpVersion";
|
|
43
|
+
}
|
|
44
|
+
foreach ($required['extensions'] as $extension) {
|
|
45
|
+
if (!in_array($extension, $have, true)) {
|
|
46
|
+
$problems[] = "the extension $extension is missing";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return $problems;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The launch settings this PHP runs without, as readable lines; empty when
|
|
54
|
+
* it was launched with every one of `ini` (the `-d` flags of the README).
|
|
55
|
+
*
|
|
56
|
+
* @param callable(string): (string|false) $iniGet `ini_get`, or a stand-in
|
|
57
|
+
* @param array<string, string>|null $settings
|
|
58
|
+
* @return list<string>
|
|
59
|
+
*/
|
|
60
|
+
public static function unsafeSettings(callable $iniGet, ?array $settings = null): array
|
|
61
|
+
{
|
|
62
|
+
$settings ??= self::required()['ini'];
|
|
63
|
+
$problems = [];
|
|
64
|
+
foreach ($settings as $name => $wanted) {
|
|
65
|
+
$value = $iniGet($name);
|
|
66
|
+
if ($value === false || self::normalised($value) !== $wanted) {
|
|
67
|
+
$shown = $value === false ? 'unknown' : "'$value'";
|
|
68
|
+
$problems[] = "the setting $name must be $wanted (launch with -d $name=$wanted), this is $shown";
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return $problems;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** An ini value as `-d` writes it: on/true/yes as 1, off/false/no/empty as 0. */
|
|
75
|
+
private static function normalised(string $value): string
|
|
76
|
+
{
|
|
77
|
+
$lower = strtolower(trim($value));
|
|
78
|
+
return match ($lower) {
|
|
79
|
+
'on', 'true', 'yes' => '1',
|
|
80
|
+
'off', 'false', 'no', '' => '0',
|
|
81
|
+
default => $lower,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
}
|
package/src/danfe/render.ts
CHANGED
|
@@ -46,6 +46,13 @@ export interface DanfeNfceInput {
|
|
|
46
46
|
readonly xml: string;
|
|
47
47
|
readonly paperWidth: PaperWidth;
|
|
48
48
|
readonly labels: DanfeNfceLabels;
|
|
49
|
+
/**
|
|
50
|
+
* Frame the contingency notice of a note signed offline and not yet
|
|
51
|
+
* authorised in a box (a `=` rule above and below it), the paper a register
|
|
52
|
+
* signing on its own prints (FUT-4717). Off by default: the paper is as it
|
|
53
|
+
* always was.
|
|
54
|
+
*/
|
|
55
|
+
readonly contingencyBox?: boolean;
|
|
49
56
|
}
|
|
50
57
|
|
|
51
58
|
/** `1234` cents → `12,34`; thousands with a dot, as the DANFE prints money. */
|
|
@@ -119,8 +126,8 @@ class Paper {
|
|
|
119
126
|
for (const piece of closing) this.lines.push({ division, text: piece, align: "left", emphasis });
|
|
120
127
|
}
|
|
121
128
|
|
|
122
|
-
rule(division: DanfeDivision): void {
|
|
123
|
-
this.lines.push({ division, text:
|
|
129
|
+
rule(division: DanfeDivision, char = "-"): void {
|
|
130
|
+
this.lines.push({ division, text: char.repeat(this.width), align: "left", emphasis: "normal" });
|
|
124
131
|
}
|
|
125
132
|
}
|
|
126
133
|
|
|
@@ -199,14 +206,18 @@ function totalsPart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels, count: n
|
|
|
199
206
|
paper.rule("IV");
|
|
200
207
|
}
|
|
201
208
|
|
|
202
|
-
function fiscalMessagePart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels): void {
|
|
209
|
+
function fiscalMessagePart(paper: Paper, doc: Parsed, labels: DanfeNfceLabels, box: boolean): void {
|
|
203
210
|
if (doc.homologation) paper.add("V", labels.homologation, "center", "bold");
|
|
211
|
+
const pending = doc.contingency && doc.infProt === null;
|
|
212
|
+
const framed = box && pending;
|
|
213
|
+
if (framed) paper.rule("V", "=");
|
|
204
214
|
if (doc.contingency) paper.add("V", labels.contingency, "center", "bold");
|
|
205
215
|
// Offline and not yet authorised: ONE copy, the consumer's (reprints are the same paper).
|
|
206
|
-
if (
|
|
216
|
+
if (pending) {
|
|
207
217
|
paper.add("V", labels.pendingAuthorization, "center", "bold");
|
|
208
218
|
paper.add("V", labels.consumerCopy, "center", "bold");
|
|
209
219
|
}
|
|
220
|
+
if (framed) paper.rule("V", "=");
|
|
210
221
|
paper.add("V", labels.lookupByKey, "center");
|
|
211
222
|
paper.add("V", text(doc.supl, "urlChave") ?? "", "center");
|
|
212
223
|
paper.add("V", groupKey(doc.accessKey), "center");
|
|
@@ -257,7 +268,7 @@ export function renderDanfeNfce(input: DanfeNfceInput): DanfeLine[] {
|
|
|
257
268
|
issuerPart(paper, doc, input.labels);
|
|
258
269
|
const count = itemsPart(paper, doc, input.labels);
|
|
259
270
|
totalsPart(paper, doc, input.labels, count);
|
|
260
|
-
fiscalMessagePart(paper, doc, input.labels);
|
|
271
|
+
fiscalMessagePart(paper, doc, input.labels, input.contingencyBox === true);
|
|
261
272
|
consumerPart(paper, doc, input.labels);
|
|
262
273
|
identificationPart(paper, doc, input.labels);
|
|
263
274
|
qrPart(paper, doc, input.labels);
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which numbers of a contingency block are KNOWN unused and which are
|
|
3
|
+
* UNKNOWN — pure, from the block's state (FUT-4717). A holder signs its block
|
|
4
|
+
* in order and hands its notes in, in order, so:
|
|
5
|
+
*
|
|
6
|
+
* - below the highest number it handed in, a number with no document was
|
|
7
|
+
* never signed: KNOWN;
|
|
8
|
+
* - a CLOSED block's numbers above what the holder said it used are KNOWN;
|
|
9
|
+
* between the highest handed in and `usedUpTo` they were signed and are
|
|
10
|
+
* still to come: UNKNOWN until they arrive;
|
|
11
|
+
* - an ABANDONED block (its holder is gone) above the highest handed in may
|
|
12
|
+
* be on paper a buyer holds: UNKNOWN, flagged, never voided;
|
|
13
|
+
* - an OPEN block above the highest handed in is still in use: neither.
|
|
14
|
+
*
|
|
15
|
+
* A range already voided is neither.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { ContingencyBlockState, ContingencyGap, NumberRange } from "./ports";
|
|
19
|
+
|
|
20
|
+
/** Consecutive numbers as ranges, ascending. */
|
|
21
|
+
function rangesOf(numbers: readonly number[]): NumberRange[] {
|
|
22
|
+
const sorted = [...new Set(numbers)].sort((a, b) => a - b);
|
|
23
|
+
const ranges: NumberRange[] = [];
|
|
24
|
+
for (const number of sorted) {
|
|
25
|
+
const last = ranges[ranges.length - 1];
|
|
26
|
+
if (last !== undefined && last.to === number - 1) ranges[ranges.length - 1] = { from: last.from, to: number };
|
|
27
|
+
else ranges.push({ from: number, to: number });
|
|
28
|
+
}
|
|
29
|
+
return ranges;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function between(from: number, to: number, keep: (n: number) => boolean): number[] {
|
|
33
|
+
const out: number[] = [];
|
|
34
|
+
for (let n = from; n <= to; n += 1) if (keep(n)) out.push(n);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The highest number of the block a document was recorded on (`from - 1`: none). */
|
|
39
|
+
function highestRecorded(block: ContingencyBlockState): number {
|
|
40
|
+
const inside = block.documented.filter((n) => n >= block.from && n <= block.to);
|
|
41
|
+
return inside.length === 0 ? block.from - 1 : Math.max(...inside);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface BlockAccount {
|
|
45
|
+
readonly known: NumberRange[];
|
|
46
|
+
readonly unknown: NumberRange[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The block's known and unknown ranges (see the module doc). */
|
|
50
|
+
export function accountFor(block: ContingencyBlockState): BlockAccount {
|
|
51
|
+
const documented = new Set(block.documented);
|
|
52
|
+
const voided = (n: number) => block.voided.some((range) => n >= range.from && n <= range.to);
|
|
53
|
+
const open = (n: number) => !documented.has(n) && !voided(n);
|
|
54
|
+
const highest = highestRecorded(block);
|
|
55
|
+
const known = between(block.from, highest, open);
|
|
56
|
+
let unknown: number[] = [];
|
|
57
|
+
if (block.fate === "CLOSED") {
|
|
58
|
+
const used = Math.max(highest, block.usedUpTo ?? block.from - 1);
|
|
59
|
+
known.push(...between(used + 1, block.to, open));
|
|
60
|
+
unknown = between(highest + 1, used, open);
|
|
61
|
+
} else if (block.fate === "ABANDONED") {
|
|
62
|
+
unknown = between(highest + 1, block.to, open);
|
|
63
|
+
}
|
|
64
|
+
return { known: rangesOf(known), unknown: rangesOf(unknown) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A range of a block, as the gap the service reports. */
|
|
68
|
+
export function gapOf(block: ContingencyBlockState, range: NumberRange): ContingencyGap {
|
|
69
|
+
return {
|
|
70
|
+
blockId: block.id,
|
|
71
|
+
ownerId: block.ownerId,
|
|
72
|
+
issuingPointId: block.issuingPointId,
|
|
73
|
+
issuerCnpj: block.issuerCnpj,
|
|
74
|
+
environment: block.environment,
|
|
75
|
+
series: block.series,
|
|
76
|
+
holder: block.holder,
|
|
77
|
+
reservedAt: block.reservedAt,
|
|
78
|
+
from: range.from,
|
|
79
|
+
to: range.to,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Whether every number is a document or voided, with nothing left to come: the block needs no more work. */
|
|
84
|
+
export function isSettled(block: ContingencyBlockState): boolean {
|
|
85
|
+
if (block.fate === "OPEN") return false;
|
|
86
|
+
const { known, unknown } = accountFor(block);
|
|
87
|
+
return known.length === 0 && unknown.length === 0;
|
|
88
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The gap pass over contingency blocks (FUT-4717): every block read in keyset
|
|
3
|
+
* pages to the end (a block that never settles — an OPEN one, an ABANDONED
|
|
4
|
+
* one with an unknown rest — must not hide the ones reserved after it), its
|
|
5
|
+
* KNOWN unused ranges voided at SEFAZ once, its UNKNOWN ones only reported.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { FiscalDocumentError } from "./errors";
|
|
9
|
+
import { xmlKeys } from "./helpers";
|
|
10
|
+
import { accountFor, gapOf, isSettled } from "./contingency-gaps";
|
|
11
|
+
import type { Deps } from "./service-profile";
|
|
12
|
+
import type { ContingencyBlockState, ContingencyBlockStore, ContingencyGap, FiscalStore } from "./ports";
|
|
13
|
+
|
|
14
|
+
/** How many blocks one read of a pass asks for; the pass reads pages until one comes back empty. */
|
|
15
|
+
const BLOCK_PAGE_SIZE = 1_000;
|
|
16
|
+
|
|
17
|
+
const BLOCK_METHODS = [
|
|
18
|
+
"reserveContingencyBlock",
|
|
19
|
+
"findContingencyBlock",
|
|
20
|
+
"listContingencyBlocks",
|
|
21
|
+
"closeContingencyBlock",
|
|
22
|
+
"settleContingencyBlock",
|
|
23
|
+
"recordContingencyVoid",
|
|
24
|
+
"getDocumentByAccessKey",
|
|
25
|
+
"recordSignedDocument",
|
|
26
|
+
] as const;
|
|
27
|
+
|
|
28
|
+
export function blockStore(store: FiscalStore): FiscalStore & ContingencyBlockStore {
|
|
29
|
+
const candidate = store as FiscalStore & Partial<ContingencyBlockStore>;
|
|
30
|
+
if (BLOCK_METHODS.some((name) => typeof candidate[name] !== "function")) {
|
|
31
|
+
throw new FiscalDocumentError("NOT_SUPPORTED", "this FiscalStore does not keep contingency blocks (ContingencyBlockStore).");
|
|
32
|
+
}
|
|
33
|
+
return candidate as FiscalStore & ContingencyBlockStore;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type BlockFilter = Omit<Parameters<ContingencyBlockStore["listContingencyBlocks"]>[0], "limit" | "after">;
|
|
37
|
+
|
|
38
|
+
/** Every page of the blocks a filter selects, in `(reservedAt, id)` order, to exhaustion. */
|
|
39
|
+
async function* blockPages(store: ContingencyBlockStore, filter: BlockFilter): AsyncGenerator<ContingencyBlockState[]> {
|
|
40
|
+
let after: { reservedAt: string; id: string } | undefined;
|
|
41
|
+
for (;;) {
|
|
42
|
+
const page = await store.listContingencyBlocks({ ...filter, ...(after === undefined ? {} : { after }), limit: BLOCK_PAGE_SIZE });
|
|
43
|
+
const last = page[page.length - 1];
|
|
44
|
+
// An empty page ends the read; a page that does not move the cursor would loop for ever.
|
|
45
|
+
if (last === undefined || (after !== undefined && last.id === after.id)) return;
|
|
46
|
+
yield page;
|
|
47
|
+
after = { reservedAt: last.reservedAt, id: last.id };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The blocks of the pages, one by one. */
|
|
52
|
+
async function* eachBlock(pages: AsyncGenerator<ContingencyBlockState[]>): AsyncGenerator<ContingencyBlockState> {
|
|
53
|
+
for await (const page of pages) yield* page;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function allBlocks(store: ContingencyBlockStore, filter: BlockFilter): Promise<ContingencyBlockState[]> {
|
|
57
|
+
const blocks: ContingencyBlockState[] = [];
|
|
58
|
+
for await (const page of blockPages(store, filter)) blocks.push(...page);
|
|
59
|
+
return blocks;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const ownerFilter = (ownerId: string | undefined) => (ownerId === undefined ? {} : { ownerId });
|
|
63
|
+
|
|
64
|
+
/** Known unused ranges of blocks reserved before `before` (ISO 8601), across owners unless one is named. */
|
|
65
|
+
export async function listKnownGaps(deps: Deps, input: { before: string; ownerId?: string }): Promise<ContingencyGap[]> {
|
|
66
|
+
const blocks = await allBlocks(blockStore(deps.config.store), { ...ownerFilter(input.ownerId), reservedBefore: input.before, unsettledOnly: true });
|
|
67
|
+
return blocks.flatMap((block) => accountFor(block).known.map((range) => gapOf(block, range)));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Ranges whose fate is unknown — flagged for the store, never voided. */
|
|
71
|
+
export async function listUnknownRanges(deps: Deps, input: { ownerId?: string }): Promise<ContingencyGap[]> {
|
|
72
|
+
const blocks = await allBlocks(blockStore(deps.config.store), { ...ownerFilter(input.ownerId), fates: ["CLOSED", "ABANDONED"], unsettledOnly: true });
|
|
73
|
+
return blocks.flatMap((block) => accountFor(block).unknown.map((range) => gapOf(block, range)));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface GapVoidReport {
|
|
77
|
+
readonly voided: ReadonlyArray<ContingencyGap & { readonly protocol: string | null }>;
|
|
78
|
+
readonly failures: ReadonlyArray<ContingencyGap & { readonly class: string; readonly code: string | null; readonly message: string }>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const NOTHING: GapVoidReport = { voided: [], failures: [] };
|
|
82
|
+
|
|
83
|
+
/** Whether the gap is still unused right now: no note recorded and nothing voided inside it since the pass read it. */
|
|
84
|
+
async function stillUnused(store: ContingencyBlockStore, gap: ContingencyGap): Promise<boolean> {
|
|
85
|
+
const fresh = await store.findContingencyBlock({
|
|
86
|
+
ownerId: gap.ownerId, issuerCnpj: gap.issuerCnpj, environment: gap.environment, series: gap.series, number: gap.from,
|
|
87
|
+
});
|
|
88
|
+
if (fresh === null || fresh.id !== gap.blockId) return false;
|
|
89
|
+
const inside = (n: number) => n >= gap.from && n <= gap.to;
|
|
90
|
+
return !fresh.documented.some(inside) && !fresh.voided.some((range) => range.from <= gap.to && range.to >= gap.from);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function voidGap(deps: Deps, store: ContingencyBlockStore, gap: ContingencyGap): Promise<GapVoidReport> {
|
|
94
|
+
// A note handed in late since the page was read takes its number: leave the range for the next pass.
|
|
95
|
+
if (!(await stillUnused(store, gap))) return NOTHING;
|
|
96
|
+
const profile = await deps.ctx.requireProfile(gap.ownerId);
|
|
97
|
+
const outcome = await deps.config.issuer.inutilize({
|
|
98
|
+
model: "NFCE",
|
|
99
|
+
environment: gap.environment,
|
|
100
|
+
signing: await deps.ctx.material(profile),
|
|
101
|
+
uf: profile.address.uf,
|
|
102
|
+
cnpj: gap.issuerCnpj,
|
|
103
|
+
year: Number(gap.reservedAt.slice(0, 4)),
|
|
104
|
+
series: gap.series,
|
|
105
|
+
from: gap.from,
|
|
106
|
+
to: gap.to,
|
|
107
|
+
reason: deps.config.reasons.inutilization,
|
|
108
|
+
});
|
|
109
|
+
if (!outcome.ok) {
|
|
110
|
+
return { voided: [], failures: [{ ...gap, class: outcome.error.class, code: outcome.error.code, message: outcome.error.message }] };
|
|
111
|
+
}
|
|
112
|
+
const xml = outcome.answer.inutilizationXml;
|
|
113
|
+
const eventXmlKey = xml === null ? null : xmlKeys.inutilizedRange(gap);
|
|
114
|
+
if (eventXmlKey !== null) await deps.config.storage.put(eventXmlKey, xml ?? "", "application/xml");
|
|
115
|
+
await store.recordContingencyVoid({
|
|
116
|
+
id: deps.config.newId(),
|
|
117
|
+
blockId: gap.blockId,
|
|
118
|
+
range: { from: gap.from, to: gap.to },
|
|
119
|
+
protocol: outcome.answer.protocol,
|
|
120
|
+
eventXmlKey,
|
|
121
|
+
at: deps.ctx.nowIso(),
|
|
122
|
+
});
|
|
123
|
+
return { voided: [{ ...gap, protocol: outcome.answer.protocol }], failures: [] };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Void one block's known ranges; settle it when nothing is left to account for. */
|
|
127
|
+
async function voidBlock(deps: Deps, store: ContingencyBlockStore, block: ContingencyBlockState): Promise<GapVoidReport> {
|
|
128
|
+
const voided: GapVoidReport["voided"][number][] = [];
|
|
129
|
+
const failures: GapVoidReport["failures"][number][] = [];
|
|
130
|
+
for (const range of accountFor(block).known) {
|
|
131
|
+
const one = await voidGap(deps, store, gapOf(block, range));
|
|
132
|
+
voided.push(...one.voided);
|
|
133
|
+
failures.push(...one.failures);
|
|
134
|
+
}
|
|
135
|
+
const done = voided.map(({ from, to }) => ({ from, to }));
|
|
136
|
+
if (isSettled({ ...block, voided: [...block.voided, ...done] })) await store.settleContingencyBlock({ id: block.id, at: deps.ctx.nowIso() });
|
|
137
|
+
return { voided, failures };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* One pass of the gap job: every KNOWN unused range of a block reserved
|
|
142
|
+
* before `before` is inutilized once (one call per range); a failure is
|
|
143
|
+
* reported and tried again on the next pass. A block left with nothing to
|
|
144
|
+
* account for is settled and read no more. Unknown ranges are never voided.
|
|
145
|
+
* Every unsettled block is read, page after page.
|
|
146
|
+
*/
|
|
147
|
+
export async function voidKnownGaps(deps: Deps, input: { before: string; ownerId?: string }): Promise<GapVoidReport> {
|
|
148
|
+
const store = blockStore(deps.config.store);
|
|
149
|
+
const report = { voided: [] as GapVoidReport["voided"][number][], failures: [] as GapVoidReport["failures"][number][] };
|
|
150
|
+
const pages = blockPages(store, { ...ownerFilter(input.ownerId), reservedBefore: input.before, unsettledOnly: true });
|
|
151
|
+
for await (const block of eachBlock(pages)) {
|
|
152
|
+
const one = await voidBlock(deps, store, block);
|
|
153
|
+
report.voided.push(...one.voided);
|
|
154
|
+
report.failures.push(...one.failures);
|
|
155
|
+
}
|
|
156
|
+
return report;
|
|
157
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading an NFC-e a holder signed offline (`tpEmis = 9`, no `nfeProc`) for
|
|
3
|
+
* `recordSigned`: the fields the document record keeps, each read from the
|
|
4
|
+
* XML, and every reason to refuse it. The XML is the fiscal service's own
|
|
5
|
+
* layout, so the DANFE's reader (`../danfe/xml`) reads it.
|
|
6
|
+
*
|
|
7
|
+
* The access key is checked against the fields it encodes, not only its
|
|
8
|
+
* check digit: a key whose number or series disagrees with `ide` would let a
|
|
9
|
+
* holder record a number outside its block under a key inside it.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { SefazEnvironment } from "../sidecar/types";
|
|
13
|
+
import { accessKeyOf, element, text } from "../danfe/xml";
|
|
14
|
+
import { FiscalDocumentError } from "./errors";
|
|
15
|
+
import { isValidAccessKey } from "./helpers";
|
|
16
|
+
|
|
17
|
+
/** What a station-signed NFC-e says about itself. */
|
|
18
|
+
export interface SignedContingencyNote {
|
|
19
|
+
readonly accessKey: string;
|
|
20
|
+
readonly issuerCnpj: string;
|
|
21
|
+
readonly environment: SefazEnvironment;
|
|
22
|
+
readonly series: number;
|
|
23
|
+
readonly number: number;
|
|
24
|
+
/** `cNF`. */
|
|
25
|
+
readonly keyCode: string;
|
|
26
|
+
/** `dhEmi`. */
|
|
27
|
+
readonly issuedAt: string;
|
|
28
|
+
/** `dhCont` and `xJust`. */
|
|
29
|
+
readonly contingency: { readonly since: string; readonly reason: string };
|
|
30
|
+
readonly totalCents: number;
|
|
31
|
+
readonly discountCents: number;
|
|
32
|
+
/** The consumer's CPF/CNPJ (or foreign id), or `null`. */
|
|
33
|
+
readonly buyerTaxId: string | null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function refuse(why: string): never {
|
|
37
|
+
throw new FiscalDocumentError("CONTINGENCY_XML_REFUSED", why);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function cents(value: string | null): number {
|
|
41
|
+
return Math.round(Number(value ?? "0") * 100);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function required(scope: string | null, tag: string): string {
|
|
45
|
+
const value = text(scope, tag);
|
|
46
|
+
if (value === null || value.trim() === "") refuse(`the XML has no ${tag}.`);
|
|
47
|
+
return value.trim();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The key's own fields: cUF(2) AAMM(4) CNPJ(14) mod(2) serie(3) nNF(9) tpEmis(1) cNF(8) cDV(1). */
|
|
51
|
+
function assertKeyMatches(key: string, ide: string, cnpj: string): void {
|
|
52
|
+
const expected = [
|
|
53
|
+
required(ide, "cUF"),
|
|
54
|
+
required(ide, "dhEmi").slice(2, 4) + required(ide, "dhEmi").slice(5, 7),
|
|
55
|
+
cnpj,
|
|
56
|
+
required(ide, "mod"),
|
|
57
|
+
required(ide, "serie").padStart(3, "0"),
|
|
58
|
+
required(ide, "nNF").padStart(9, "0"),
|
|
59
|
+
required(ide, "tpEmis"),
|
|
60
|
+
required(ide, "cNF"),
|
|
61
|
+
required(ide, "cDV"),
|
|
62
|
+
].join("");
|
|
63
|
+
if (expected !== key) refuse("the access key does not match the fields it encodes.");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Parse and check a station-signed NFC-e. Refuses (`CONTINGENCY_XML_REFUSED`)
|
|
68
|
+
* anything but a model 65 signed in offline contingency (`tpEmis = 9`, with
|
|
69
|
+
* `dhCont` and `xJust`), a key whose check digit or fields are wrong, and an
|
|
70
|
+
* XML with no signature. The issuer's CNPJ and the block are the caller's to
|
|
71
|
+
* check against its profile and its blocks.
|
|
72
|
+
*/
|
|
73
|
+
interface Parts {
|
|
74
|
+
readonly infNFe: string;
|
|
75
|
+
readonly ide: string;
|
|
76
|
+
readonly emit: string;
|
|
77
|
+
readonly accessKey: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The blocks every check reads, or a refusal naming what is missing. */
|
|
81
|
+
function assertSignedNote(signedXml: string): void {
|
|
82
|
+
if (typeof signedXml !== "string" || signedXml.trim() === "") refuse("signedXml is empty.");
|
|
83
|
+
if (element(signedXml, "nfeProc") !== null || element(signedXml, "protNFe") !== null) refuse("the XML is authorised already, not a signed note.");
|
|
84
|
+
if (element(signedXml, "Signature") === null) refuse("the XML is not signed.");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function partsOf(signedXml: string): Parts {
|
|
88
|
+
assertSignedNote(signedXml);
|
|
89
|
+
const infNFe = element(signedXml, "infNFe");
|
|
90
|
+
const ide = infNFe === null ? null : element(infNFe, "ide");
|
|
91
|
+
const emit = infNFe === null ? null : element(infNFe, "emit");
|
|
92
|
+
const accessKey = accessKeyOf(signedXml);
|
|
93
|
+
if (infNFe === null || ide === null || emit === null || accessKey === null) refuse("the XML is not an NF-e: no infNFe, ide, emit or access key.");
|
|
94
|
+
return { infNFe, ide, emit, accessKey };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** An NFC-e (65) signed offline (`tpEmis` 9) under a key whose check digit and fields hold. */
|
|
98
|
+
function assertOfflineNfce({ ide, accessKey }: Parts, issuerCnpj: string): void {
|
|
99
|
+
if (required(ide, "mod") !== "65") refuse("the XML is not an NFC-e (model 65).");
|
|
100
|
+
if (required(ide, "tpEmis") !== "9") refuse("the XML is not signed in offline contingency (tpEmis 9).");
|
|
101
|
+
if (!isValidAccessKey(accessKey)) refuse("the access key's check digit is wrong.");
|
|
102
|
+
assertKeyMatches(accessKey, ide, issuerCnpj);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function buyerOf(infNFe: string): string | null {
|
|
106
|
+
const dest = element(infNFe, "dest");
|
|
107
|
+
return text(dest, "CPF") ?? text(dest, "CNPJ") ?? text(dest, "idEstrangeiro");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Parse and check a station-signed NFC-e. Refuses (`CONTINGENCY_XML_REFUSED`)
|
|
112
|
+
* anything but a model 65 signed in offline contingency (`tpEmis = 9`, with
|
|
113
|
+
* `dhCont` and `xJust`), a key whose check digit or fields are wrong, and an
|
|
114
|
+
* XML with no signature. The issuer's CNPJ and the block are the caller's to
|
|
115
|
+
* check against its profile and its blocks.
|
|
116
|
+
*/
|
|
117
|
+
export function parseSignedContingencyNote(signedXml: string): SignedContingencyNote {
|
|
118
|
+
const parts = partsOf(signedXml);
|
|
119
|
+
const { infNFe, ide, emit, accessKey } = parts;
|
|
120
|
+
const issuerCnpj = required(emit, "CNPJ");
|
|
121
|
+
assertOfflineNfce(parts, issuerCnpj);
|
|
122
|
+
const total = element(infNFe, "ICMSTot");
|
|
123
|
+
return {
|
|
124
|
+
accessKey,
|
|
125
|
+
issuerCnpj,
|
|
126
|
+
environment: required(ide, "tpAmb") === "1" ? "producao" : "homologacao",
|
|
127
|
+
series: Number(required(ide, "serie")),
|
|
128
|
+
number: Number(required(ide, "nNF")),
|
|
129
|
+
keyCode: required(ide, "cNF"),
|
|
130
|
+
issuedAt: required(ide, "dhEmi"),
|
|
131
|
+
contingency: { since: required(ide, "dhCont"), reason: required(ide, "xJust") },
|
|
132
|
+
totalCents: cents(text(total, "vNF")),
|
|
133
|
+
discountCents: cents(text(total, "vDesc")),
|
|
134
|
+
buyerTaxId: buyerOf(infNFe),
|
|
135
|
+
};
|
|
136
|
+
}
|