@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,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pure helpers the document service builds a document with: the local
|
|
3
|
+
* clock, the key code, the access key, the issuer block, the totals, the
|
|
4
|
+
* storage keys. No port, no state.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { DocumentIssuer, SaleForDocument, Uf } from "../sale/types";
|
|
8
|
+
import { FiscalDocumentError } from "./errors";
|
|
9
|
+
import type { SaleDraft } from "./ports";
|
|
10
|
+
import type { EmitterProfile } from "./profile";
|
|
11
|
+
import type { DocumentTotals, FiscalDocument, FiscalDocumentModel, SeriesKind } from "./types";
|
|
12
|
+
|
|
13
|
+
/** `2026-11-20T12:30:00-03:00`: the instant as the owner's wall clock. */
|
|
14
|
+
export function localIso(at: Date, offset: string): string {
|
|
15
|
+
const match = /^([+-])(\d{2}):(\d{2})$/.exec(offset);
|
|
16
|
+
if (match === null) throw new FiscalDocumentError("INVALID_INPUT", `utcOffset answered "${offset}", not ±HH:MM.`);
|
|
17
|
+
const minutes = (match[1] === "-" ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3]));
|
|
18
|
+
return `${new Date(at.getTime() + minutes * 60_000).toISOString().slice(0, 19)}${offset}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const UNBIASED_LIMIT = Math.floor(2 ** 32 / 100_000_000) * 100_000_000;
|
|
22
|
+
|
|
23
|
+
/** `cNF`: eight random digits, never equal to the number's own eight (the layout's rule). */
|
|
24
|
+
export function drawKeyCode(number: number): string {
|
|
25
|
+
const own = String(number % 100_000_000).padStart(8, "0");
|
|
26
|
+
for (;;) {
|
|
27
|
+
const [value] = globalThis.crypto.getRandomValues(new Uint32Array(1));
|
|
28
|
+
// Rejection sampling: values at or above the last whole multiple of 10^8 would bias the low codes.
|
|
29
|
+
if (value === undefined || value >= UNBIASED_LIMIT) continue;
|
|
30
|
+
const code = String(value % 100_000_000).padStart(8, "0");
|
|
31
|
+
if (code !== own) return code;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const FILLED_BY_THE_PACKAGE = new Set(["series", "number", "keyCode", "issuer", "issuedAt"]);
|
|
36
|
+
|
|
37
|
+
/** A stored sale back to the draft it was built from (for a second document of the same sale). */
|
|
38
|
+
export function draftOf(sale: SaleForDocument): SaleDraft {
|
|
39
|
+
return Object.fromEntries(Object.entries(sale).filter(([key]) => !FILLED_BY_THE_PACKAGE.has(key))) as unknown as SaleDraft;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function issuerOf(profile: EmitterProfile): DocumentIssuer {
|
|
43
|
+
return {
|
|
44
|
+
cnpj: profile.cnpj,
|
|
45
|
+
stateRegistration: profile.stateRegistration,
|
|
46
|
+
legalName: profile.legalName,
|
|
47
|
+
tradeName: profile.tradeName,
|
|
48
|
+
taxRegime: profile.taxRegime,
|
|
49
|
+
address: profile.address,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function totalsOf(sale: SaleDraft): DocumentTotals {
|
|
54
|
+
const sum = (pick: (line: SaleDraft["lines"][number]) => number) => sale.lines.reduce((total, line) => total + pick(line), 0);
|
|
55
|
+
const discountCents = sum((line) => line.discountCents);
|
|
56
|
+
return {
|
|
57
|
+
totalCents: sum((line) => line.valueCents) - discountCents,
|
|
58
|
+
discountCents,
|
|
59
|
+
cbsCents: sum((line) => line.ibsCbs?.figures?.cbsCents ?? 0),
|
|
60
|
+
ibsUfCents: sum((line) => line.ibsCbs?.figures?.ibsUfCents ?? 0),
|
|
61
|
+
ibsMunCents: sum((line) => line.ibsCbs?.figures?.ibsMunCents ?? 0),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** `text` without any trailing run of `char`, in linear time (no regex backtracking). */
|
|
66
|
+
export function trimEnd(text: string, char: string): string {
|
|
67
|
+
let end = text.length;
|
|
68
|
+
while (end > 0 && text[end - 1] === char) end -= 1;
|
|
69
|
+
return text.slice(0, end);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Storage keys, by access key: one folder per document, whatever its owner. */
|
|
73
|
+
export const xmlKeys = {
|
|
74
|
+
signed: (accessKey: string) => `fiscal/${accessKey}/signed.xml`,
|
|
75
|
+
/** One signed XML per digest: every XML a failed call returned under a key is kept, none overwritten. */
|
|
76
|
+
signedByDigest: (accessKey: string, digest: string) =>
|
|
77
|
+
`fiscal/${accessKey}/signed-${trimEnd(digest.replace(/\+/g, "-").replace(/\//g, "_"), "=")}.xml`,
|
|
78
|
+
authorized: (accessKey: string) => `fiscal/${accessKey}/authorized.xml`,
|
|
79
|
+
cancel: (accessKey: string) => `fiscal/${accessKey}/cancel.xml`,
|
|
80
|
+
inutilization: (document: FiscalDocument) =>
|
|
81
|
+
`fiscal/inutilization/${document.environment}/${document.model}/${document.ownerId}/${document.series}-${document.number}.xml`,
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/** The IBGE code of each federative unit: the access key's first two digits. */
|
|
85
|
+
const UF_CODES: Readonly<Record<Uf, string>> = {
|
|
86
|
+
RO: "11", AC: "12", AM: "13", RR: "14", PA: "15", AP: "16", TO: "17", MA: "21", PI: "22", CE: "23", RN: "24", PB: "25",
|
|
87
|
+
PE: "26", AL: "27", SE: "28", BA: "29", MG: "31", ES: "32", RJ: "33", SP: "35", PR: "41", SC: "42", RS: "43", MS: "50",
|
|
88
|
+
MT: "51", GO: "52", DF: "53",
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** The access key's modulo-11 check digit (weights 2–9 from the right). */
|
|
92
|
+
function keyCheckDigit(body: string): number {
|
|
93
|
+
let sum = 0;
|
|
94
|
+
let weight = 2;
|
|
95
|
+
for (let i = body.length - 1; i >= 0; i -= 1) {
|
|
96
|
+
sum += (body.charCodeAt(i) - 48) * weight;
|
|
97
|
+
weight = weight === 9 ? 2 : weight + 1;
|
|
98
|
+
}
|
|
99
|
+
const rest = sum % 11;
|
|
100
|
+
return rest < 2 ? 0 : 11 - rest;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The 44-character access key a document will carry, computed as the layout
|
|
105
|
+
* does: cUF, AAMM of `dhEmi`, CNPJ, model, series, number, `tpEmis` (1 online,
|
|
106
|
+
* 9 offline NFC-e), `cNF` and the check digit. The package knows a document's
|
|
107
|
+
* key before any call, so an unanswered send can always be looked up.
|
|
108
|
+
*/
|
|
109
|
+
export function computeAccessKey(input: {
|
|
110
|
+
readonly sale: Pick<SaleForDocument, "issuer" | "issuedAt" | "series" | "number" | "keyCode">;
|
|
111
|
+
readonly model: FiscalDocumentModel;
|
|
112
|
+
readonly seriesKind: SeriesKind;
|
|
113
|
+
}): string {
|
|
114
|
+
const { sale } = input;
|
|
115
|
+
const body = [
|
|
116
|
+
UF_CODES[sale.issuer.address.uf],
|
|
117
|
+
sale.issuedAt.slice(2, 4),
|
|
118
|
+
sale.issuedAt.slice(5, 7),
|
|
119
|
+
sale.issuer.cnpj,
|
|
120
|
+
input.model === "NFE" ? "55" : "65",
|
|
121
|
+
String(sale.series).padStart(3, "0"),
|
|
122
|
+
String(sale.number).padStart(9, "0"),
|
|
123
|
+
input.seriesKind === "CONTINGENCY" ? "9" : "1",
|
|
124
|
+
sale.keyCode,
|
|
125
|
+
].join("");
|
|
126
|
+
return `${body}${keyCheckDigit(body)}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/fiscal/documents` — the fiscal document record, its state machine,
|
|
3
|
+
* the ports a host implements (store, storage, cipher, signing identity, sale
|
|
4
|
+
* source; the issuer is `@12-apps/fiscal/issuer`) and the service that drives
|
|
5
|
+
* them.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export * from "./types";
|
|
9
|
+
export * from "./profile";
|
|
10
|
+
export { DOCUMENT_TRANSITIONS, FINAL_STATUSES, MAX_FAILURES, canTransition, scrubSecrets, transition } from "./machine";
|
|
11
|
+
export type { DocumentInput, Transition } from "./machine";
|
|
12
|
+
export { FiscalDocumentError } from "./errors";
|
|
13
|
+
export type { FiscalDocumentErrorCode } from "./errors";
|
|
14
|
+
export type { Cipher, ContingencyBlockSource, DocumentStorage, FiscalStore, NumberRequest, SaleDraft, SaleSource } from "./ports";
|
|
15
|
+
export { createPlatformIdentity, createSigningIdentities, createStoreCertificateIdentity } from "./signing";
|
|
16
|
+
export type { SigningIdentities, SigningIdentity } from "./signing";
|
|
17
|
+
export { parseCertificateUpload, parseIssuingPointInput, parseProfileInput } from "./profile-input";
|
|
18
|
+
export type { CertificateUpload, EmitterProfileInput, IssuingPointInput } from "./profile-input";
|
|
19
|
+
export {
|
|
20
|
+
FISCAL_CERTIFICATE_EXPIRING,
|
|
21
|
+
FISCAL_CONTINGENCY_DEADLINE,
|
|
22
|
+
FISCAL_DOCUMENT_NEEDS_ATTENTION,
|
|
23
|
+
FISCAL_DOCUMENT_REJECTED,
|
|
24
|
+
computeAccessKey,
|
|
25
|
+
draftOf,
|
|
26
|
+
drawKeyCode,
|
|
27
|
+
localIso,
|
|
28
|
+
xmlKeys,
|
|
29
|
+
} from "./context";
|
|
30
|
+
export type { FiscalDocumentsConfig, FiscalNotifyPort, FiscalReasons } from "./context";
|
|
31
|
+
export { CONTINGENCY_WARNING_AFTER_MS, createFiscalDocuments } from "./service";
|
|
32
|
+
export type { CertificateFacts, FiscalDocuments, FiscalDocumentsServiceConfig, IssueInput, SweepReport } from "./service";
|
|
33
|
+
export { createMemoryFiscalStore } from "./memory";
|
|
34
|
+
export type { MemoryFiscalStore } from "./memory";
|
|
35
|
+
export { FISCAL_NEXT_NUMBER_SQL } from "./sql";
|
|
36
|
+
export { createPrismaFiscalStore } from "./sql-store";
|
|
37
|
+
export type { FiscalPrismaClient, FiscalSqlClient } from "./sql-store";
|
|
38
|
+
export { documentLines } from "./lines";
|
|
39
|
+
export type { LineDetails } from "./lines";
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The document mapping's tax half: the engine's breakdown (`computeTax`)
|
|
3
|
+
* onto the `SaleForDocument` lines a host's `SaleSource` answers. The engine
|
|
4
|
+
* decides; this writes what it decided:
|
|
5
|
+
*
|
|
6
|
+
* - one document line per breakdown line, in the breakdown's order — so an
|
|
7
|
+
* exclusion the engine segregated (the service charge passed to the staff
|
|
8
|
+
* at most 15% of the food and drink, class 410019; a platform's retained
|
|
9
|
+
* intermediation, 410020) IS its own item, with its class and no tax
|
|
10
|
+
* (RCBS art. 399 §2), and a service charge the engine did not exclude is a
|
|
11
|
+
* taxed item under the class the host passed;
|
|
12
|
+
* - the IBS/CBS group from the line's figures (`vBC`, the nominal rates, the
|
|
13
|
+
* reduction, the amounts), or no group at all where the engine answered
|
|
14
|
+
* `NONE` (MEI, não contribuinte).
|
|
15
|
+
*
|
|
16
|
+
* What the engine does not know — the product code, NCM, CFOP, unit, the
|
|
17
|
+
* ICMS, PIS and COFINS — arrives per line id from the host. A breakdown line
|
|
18
|
+
* with no details is refused, never invented.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { LineTax, TaxBreakdown } from "../engine/types";
|
|
22
|
+
import type { LineIbsCbs, SaleLine } from "../sale/types";
|
|
23
|
+
import { FiscalDocumentError } from "./errors";
|
|
24
|
+
|
|
25
|
+
/** Everything a document line needs that the breakdown does not carry. */
|
|
26
|
+
export type LineDetails = Omit<SaleLine, "id" | "quantity" | "valueCents" | "ibsCbs">;
|
|
27
|
+
|
|
28
|
+
const SEGREGATED = new Set<LineTax["source"]>(["GORJETA_EXCLUDED", "INTERMEDIATION_EXCLUDED"]);
|
|
29
|
+
|
|
30
|
+
function ibsCbsOf(line: LineTax, breakdown: TaxBreakdown): LineIbsCbs | null {
|
|
31
|
+
if (breakdown.treatment === "NONE") return null;
|
|
32
|
+
const code = { cst: line.taxClass.cstIbsCbs, classCode: line.taxClass.cClassTrib };
|
|
33
|
+
if (SEGREGATED.has(line.source)) return { ...code, figures: null };
|
|
34
|
+
return {
|
|
35
|
+
...code,
|
|
36
|
+
figures: {
|
|
37
|
+
baseCents: line.taxBaseCents,
|
|
38
|
+
reductionBp: line.reductionBp,
|
|
39
|
+
cbsRateBp: line.cbsRateBp,
|
|
40
|
+
cbsCents: line.cbsCents,
|
|
41
|
+
ibsUfRateBp: line.ibsUfRateBp,
|
|
42
|
+
ibsUfCents: line.ibsUfCents,
|
|
43
|
+
ibsMunRateBp: line.ibsMunRateBp,
|
|
44
|
+
ibsMunCents: line.ibsMunCents,
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function documentLines(breakdown: TaxBreakdown, details: Readonly<Record<string, LineDetails>>): SaleLine[] {
|
|
50
|
+
return breakdown.lines.map((line) => {
|
|
51
|
+
const detail = details[line.lineId];
|
|
52
|
+
if (detail === undefined) {
|
|
53
|
+
throw new FiscalDocumentError("INVALID_INPUT", `breakdown line ${line.lineId} has no document details.`);
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
...detail,
|
|
57
|
+
id: line.lineId,
|
|
58
|
+
quantity: line.quantity,
|
|
59
|
+
valueCents: line.valueCents,
|
|
60
|
+
ibsCbs: ibsCbsOf(line, breakdown),
|
|
61
|
+
};
|
|
62
|
+
});
|
|
63
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What each input does to a document's fields — the state machine's body
|
|
3
|
+
* (`./machine` holds its table and its one entry point). Pure functions; a
|
|
4
|
+
* refusal throws `TRANSITION_REFUSED`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type {
|
|
8
|
+
CancelledDocument,
|
|
9
|
+
ContingencyEntry,
|
|
10
|
+
ContingencySignedDocument,
|
|
11
|
+
InutilizedRange,
|
|
12
|
+
IssuedDocument,
|
|
13
|
+
LookedUpDocument,
|
|
14
|
+
SidecarErrorBody,
|
|
15
|
+
} from "../sidecar/types";
|
|
16
|
+
import type { SaleForDocument } from "../sale/types";
|
|
17
|
+
import { FiscalDocumentError } from "./errors";
|
|
18
|
+
import { type DocumentEventKind, type DocumentTotals, type FiscalDocument, type NumberVoid, isLive } from "./types";
|
|
19
|
+
|
|
20
|
+
export type SidecarError = SidecarErrorBody["error"];
|
|
21
|
+
|
|
22
|
+
/** Failures in a row after which a document waits for a person. */
|
|
23
|
+
export const MAX_FAILURES = 8;
|
|
24
|
+
|
|
25
|
+
/** What the machine is fed. Each carries the service's answer, which the event keeps. */
|
|
26
|
+
export type DocumentInput =
|
|
27
|
+
| { readonly kind: "SUBMIT" }
|
|
28
|
+
| { readonly kind: "AUTHORIZE"; readonly answer: IssuedDocument; readonly xmlKey: string }
|
|
29
|
+
| { readonly kind: "DENY"; readonly answer: IssuedDocument; readonly xmlKey: string }
|
|
30
|
+
| { readonly kind: "REJECT"; readonly error: SidecarError }
|
|
31
|
+
/** `xmlKey`: where the signed XML the failed call returned was stored, when it returned one. */
|
|
32
|
+
| { readonly kind: "RETRY"; readonly error: SidecarError; readonly xmlKey?: string }
|
|
33
|
+
| {
|
|
34
|
+
readonly kind: "SIGN_OFFLINE";
|
|
35
|
+
readonly answer: ContingencySignedDocument;
|
|
36
|
+
readonly contingency: ContingencyEntry;
|
|
37
|
+
readonly xmlKey: string;
|
|
38
|
+
}
|
|
39
|
+
| { readonly kind: "REPLACE"; readonly replacedById: string }
|
|
40
|
+
| { readonly kind: "CANCEL"; readonly answer: CancelledDocument; readonly reason: string; readonly eventXmlKey: string | null }
|
|
41
|
+
/**
|
|
42
|
+
* `xmlKey`: the `nfeProc` assembled from the stored signed XML and the
|
|
43
|
+
* lookup's protocol. Without it a lookup never makes a SUBMITTED document
|
|
44
|
+
* final: an authorised document always has its XML.
|
|
45
|
+
*/
|
|
46
|
+
| { readonly kind: "LOOKUP"; readonly answer: LookedUpDocument; readonly xmlKey?: string }
|
|
47
|
+
| { readonly kind: "INUTILIZE"; readonly answer: InutilizedRange; readonly eventXmlKey: string | null }
|
|
48
|
+
/**
|
|
49
|
+
* A step that made no progress (a settlement refused or unanswered, a step
|
|
50
|
+
* that threw). It counts a failure; `attention` hands the document to a
|
|
51
|
+
* person at once (SEFAZ refused it: retrying would only repeat the refusal).
|
|
52
|
+
*/
|
|
53
|
+
| { readonly kind: "DEFER"; readonly reason: string; readonly error: SidecarError | null; readonly attention: boolean }
|
|
54
|
+
/** A rejected contingency NFC-e, corrected by the store and signed again under the same number. */
|
|
55
|
+
| {
|
|
56
|
+
readonly kind: "RESIGN";
|
|
57
|
+
readonly answer: ContingencySignedDocument;
|
|
58
|
+
readonly sale: SaleForDocument;
|
|
59
|
+
readonly totals: DocumentTotals;
|
|
60
|
+
readonly buyerTaxId: string | null;
|
|
61
|
+
readonly xmlKey: string;
|
|
62
|
+
}
|
|
63
|
+
/** A person took a document back from `attention`: the sweep may try again. */
|
|
64
|
+
| { readonly kind: "RELEASE" }
|
|
65
|
+
/** The 24-hour contingency deadline warning went out. */
|
|
66
|
+
| { readonly kind: "WARN" };
|
|
67
|
+
|
|
68
|
+
type InputOf<K extends DocumentEventKind> = Extract<DocumentInput, { kind: K }>;
|
|
69
|
+
type Step = { readonly [K in DocumentEventKind]: (document: FiscalDocument, input: InputOf<K>) => Partial<FiscalDocument> };
|
|
70
|
+
|
|
71
|
+
export function refuse(document: FiscalDocument, kind: DocumentEventKind, why: string): never {
|
|
72
|
+
throw new FiscalDocumentError(
|
|
73
|
+
"TRANSITION_REFUSED",
|
|
74
|
+
`${kind} is refused on document ${document.id} in ${document.status}: ${why}.`,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Progress: the failure count, the person's flag and the unknown outcome are settled. */
|
|
79
|
+
const SETTLED = { failures: 0, attention: false } as const;
|
|
80
|
+
|
|
81
|
+
function issuedFields(answer: IssuedDocument, xmlKey: string): Partial<FiscalDocument> {
|
|
82
|
+
return {
|
|
83
|
+
...SETTLED,
|
|
84
|
+
accessKey: answer.accessKey,
|
|
85
|
+
protocol: answer.protocol,
|
|
86
|
+
authorizedAt: answer.authorizedAt,
|
|
87
|
+
statusCode: answer.statusCode,
|
|
88
|
+
statusReason: answer.statusReason,
|
|
89
|
+
lastErrorClass: null,
|
|
90
|
+
outcomeUnknown: false,
|
|
91
|
+
xmlKey,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A failed call. `outcomeUnknown` is STICKY: once a request may have reached
|
|
97
|
+
* SEFAZ unanswered, only a definitive answer or a lookup clears it — a later
|
|
98
|
+
* "nothing was sent this time" says nothing about the first send.
|
|
99
|
+
*/
|
|
100
|
+
function failedFields(document: FiscalDocument, error: SidecarError): Partial<FiscalDocument> {
|
|
101
|
+
return {
|
|
102
|
+
accessKey: document.accessKey ?? error.accessKey,
|
|
103
|
+
statusCode: error.code,
|
|
104
|
+
statusReason: error.message,
|
|
105
|
+
lastErrorClass: error.class,
|
|
106
|
+
outcomeUnknown: document.outcomeUnknown || error.outcomeUnknown,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function failure(document: FiscalDocument, attention: boolean): Partial<FiscalDocument> {
|
|
111
|
+
const failures = document.failures + 1;
|
|
112
|
+
return { failures, attention: attention || failures >= MAX_FAILURES };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** What a lookup says is owed on a number SEFAZ may hold. */
|
|
116
|
+
function voidAfterLookup(answer: LookedUpDocument): NumberVoid {
|
|
117
|
+
if (answer.status === "AUTHORIZED") return "CANCEL";
|
|
118
|
+
if (answer.status === "CANCELLED") return "CANCELLED";
|
|
119
|
+
if (answer.status === "DENIED") return "DENIED";
|
|
120
|
+
return "INUTILIZE";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function lookupOfSettledNumber(document: FiscalDocument, answer: LookedUpDocument): Partial<FiscalDocument> {
|
|
124
|
+
if (document.numberVoid !== "LOOKUP_FIRST") refuse(document, "LOOKUP", "its number is already settled");
|
|
125
|
+
if (isLive(document) && (answer.status === "AUTHORIZED" || answer.status === "DENIED")) {
|
|
126
|
+
// The sale's own document, still SEFAZ's: never cancelled, never voided,
|
|
127
|
+
// never left REJECTED. It goes back to SUBMITTED, owing work, with the
|
|
128
|
+
// protocol kept — the next step settles it with its XML (the service does
|
|
129
|
+
// at once when it holds the XML the protocol certifies; otherwise the
|
|
130
|
+
// sweep sends the same call again, which the fiscal service settles).
|
|
131
|
+
// Its failures keep counting, so a loop of refusals reaches a person.
|
|
132
|
+
return {
|
|
133
|
+
status: "SUBMITTED",
|
|
134
|
+
numberVoid: null,
|
|
135
|
+
outcomeUnknown: false,
|
|
136
|
+
protocol: answer.protocol ?? document.protocol,
|
|
137
|
+
statusCode: answer.statusCode,
|
|
138
|
+
statusReason: answer.statusReason,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
...SETTLED,
|
|
143
|
+
numberVoid: voidAfterLookup(answer),
|
|
144
|
+
outcomeUnknown: false,
|
|
145
|
+
// The protocol SEFAZ answered is what a cancel of this number must quote.
|
|
146
|
+
protocol: answer.protocol ?? document.protocol,
|
|
147
|
+
statusCode: answer.statusCode,
|
|
148
|
+
statusReason: answer.statusReason,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* A lookup of a SUBMITTED document. It settles it as AUTHORIZED or DENIED
|
|
154
|
+
* only with the XML in hand (`xmlKey`); otherwise it keeps what SEFAZ said —
|
|
155
|
+
* the protocol marks the number as SEFAZ's — and the document stays
|
|
156
|
+
* SUBMITTED, for the sweep to fetch the XML by sending the same call again.
|
|
157
|
+
*/
|
|
158
|
+
function lookupOfSubmitted(document: FiscalDocument, answer: LookedUpDocument, xmlKey: string | undefined): Partial<FiscalDocument> {
|
|
159
|
+
const known = { statusCode: answer.statusCode, statusReason: answer.statusReason, outcomeUnknown: false };
|
|
160
|
+
// A key found cancelled elsewhere is left to the next issue call, which the service settles: CANCELLED is entered only from AUTHORIZED.
|
|
161
|
+
const settles = answer.status === "AUTHORIZED" || answer.status === "DENIED";
|
|
162
|
+
if (!settles || answer.protocol === null || document.accessKey === null) return known;
|
|
163
|
+
if (xmlKey === undefined) return { ...known, protocol: answer.protocol };
|
|
164
|
+
return { ...known, ...SETTLED, status: answer.status, protocol: answer.protocol, lastErrorClass: null, xmlKey };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function lookupFields(document: FiscalDocument, answer: LookedUpDocument, xmlKey?: string): Partial<FiscalDocument> {
|
|
168
|
+
if (document.status === "REPLACED" || document.status === "REJECTED") return lookupOfSettledNumber(document, answer);
|
|
169
|
+
if (document.status === "SUBMITTED") return lookupOfSubmitted(document, answer, xmlKey);
|
|
170
|
+
if (answer.status === "CANCELLED") return { status: "CANCELLED", statusCode: answer.statusCode, statusReason: answer.statusReason };
|
|
171
|
+
return { statusCode: answer.statusCode, statusReason: answer.statusReason };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function cancelFields(document: FiscalDocument, input: InputOf<"CANCEL">): Partial<FiscalDocument> {
|
|
175
|
+
const recorded = {
|
|
176
|
+
...SETTLED,
|
|
177
|
+
cancelledAt: input.answer.registeredAt,
|
|
178
|
+
cancelReason: input.reason,
|
|
179
|
+
cancelProtocol: input.answer.protocol,
|
|
180
|
+
eventXmlKey: input.eventXmlKey,
|
|
181
|
+
};
|
|
182
|
+
if (document.status === "AUTHORIZED") {
|
|
183
|
+
return { ...recorded, status: "CANCELLED", statusCode: input.answer.statusCode, statusReason: input.answer.statusReason };
|
|
184
|
+
}
|
|
185
|
+
if (document.numberVoid !== "CANCEL") refuse(document, "CANCEL", "a voided number is cancelled only when found authorised");
|
|
186
|
+
return { ...recorded, numberVoid: "CANCELLED" };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A rejected online number may have been authorised by an unanswered first send: look it up first. */
|
|
190
|
+
/**
|
|
191
|
+
* A rejected online number may have been authorised by an unanswered first
|
|
192
|
+
* send — or a lookup already found it authorised (its protocol is kept, and
|
|
193
|
+
* a re-send for the XML met a 704 or a different XML under the key): either
|
|
194
|
+
* way it is looked up, never voided blindly.
|
|
195
|
+
*/
|
|
196
|
+
function rejectFields(document: FiscalDocument, error: SidecarError): Partial<FiscalDocument> {
|
|
197
|
+
const failed = failedFields(document, error);
|
|
198
|
+
if (document.seriesKind === "CONTINGENCY") return { status: "REJECTED", ...failed, ...SETTLED, numberVoid: null };
|
|
199
|
+
// Known to be SEFAZ's: a refused re-send is one more failure of the same document, not a settlement.
|
|
200
|
+
if (document.protocol !== null) return { status: "REJECTED", ...failed, ...failure(document, false), numberVoid: "LOOKUP_FIRST" };
|
|
201
|
+
return { status: "REJECTED", ...failed, ...SETTLED, numberVoid: failed.outcomeUnknown === true ? "LOOKUP_FIRST" : "INUTILIZE" };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export const STEPS: Step = {
|
|
205
|
+
SUBMIT: () => ({ status: "SUBMITTED" }),
|
|
206
|
+
AUTHORIZE: (_document, input) => ({ status: "AUTHORIZED", ...issuedFields(input.answer, input.xmlKey) }),
|
|
207
|
+
DENY: (_document, input) => ({ status: "DENIED", ...issuedFields(input.answer, input.xmlKey) }),
|
|
208
|
+
REJECT: (document, input) => rejectFields(document, input.error),
|
|
209
|
+
RETRY: (document, input) => ({
|
|
210
|
+
...failedFields(document, input.error),
|
|
211
|
+
...failure(document, false),
|
|
212
|
+
...(input.xmlKey === undefined ? {} : { xmlKey: input.xmlKey }),
|
|
213
|
+
}),
|
|
214
|
+
SIGN_OFFLINE: (document, input) => {
|
|
215
|
+
if (document.seriesKind !== "CONTINGENCY") refuse(document, input.kind, "only a contingency-series number is signed offline");
|
|
216
|
+
return { ...SETTLED, status: "CONTINGENCY", accessKey: input.answer.accessKey, contingency: input.contingency, xmlKey: input.xmlKey };
|
|
217
|
+
},
|
|
218
|
+
REPLACE: (document, input) => ({
|
|
219
|
+
...SETTLED,
|
|
220
|
+
status: "REPLACED",
|
|
221
|
+
replacedById: input.replacedById,
|
|
222
|
+
// A SUBMITTED document may have reached SEFAZ whatever was recorded (a process
|
|
223
|
+
// that died mid-call, a receipt with no protocol yet): its key is always
|
|
224
|
+
// known, so it is looked up before its number is voided. Only a PENDING one
|
|
225
|
+
// was never sent.
|
|
226
|
+
numberVoid: document.status === "SUBMITTED" ? "LOOKUP_FIRST" : "INUTILIZE",
|
|
227
|
+
}),
|
|
228
|
+
CANCEL: cancelFields,
|
|
229
|
+
LOOKUP: (document, input) => lookupFields(document, input.answer, input.xmlKey),
|
|
230
|
+
INUTILIZE: (document, input) => {
|
|
231
|
+
if (document.numberVoid !== "INUTILIZE") refuse(document, input.kind, "its number is not owed an inutilization");
|
|
232
|
+
return { ...SETTLED, numberVoid: "INUTILIZED", eventXmlKey: input.eventXmlKey };
|
|
233
|
+
},
|
|
234
|
+
DEFER: (document, input) => ({
|
|
235
|
+
...failure(document, input.attention),
|
|
236
|
+
...(input.error === null ? {} : { lastErrorClass: input.error.class, statusCode: input.error.code }),
|
|
237
|
+
statusReason: input.error?.message ?? input.reason,
|
|
238
|
+
}),
|
|
239
|
+
RESIGN: (document, input) => {
|
|
240
|
+
if (document.seriesKind !== "CONTINGENCY") refuse(document, input.kind, "only a rejected contingency NFC-e is resent");
|
|
241
|
+
return {
|
|
242
|
+
...SETTLED,
|
|
243
|
+
status: "CONTINGENCY",
|
|
244
|
+
sale: input.sale,
|
|
245
|
+
totals: input.totals,
|
|
246
|
+
buyerTaxId: input.buyerTaxId,
|
|
247
|
+
accessKey: input.answer.accessKey,
|
|
248
|
+
xmlKey: input.xmlKey,
|
|
249
|
+
statusCode: null,
|
|
250
|
+
statusReason: null,
|
|
251
|
+
lastErrorClass: null,
|
|
252
|
+
};
|
|
253
|
+
},
|
|
254
|
+
RELEASE: (document) => {
|
|
255
|
+
if (!document.attention) refuse(document, "RELEASE", "it is not waiting for a person");
|
|
256
|
+
return SETTLED;
|
|
257
|
+
},
|
|
258
|
+
// `deadlineWarnedAt` is the transition's own time, set by `transition`.
|
|
259
|
+
WARN: () => ({}),
|
|
260
|
+
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fiscal document state machine: pure functions from a document and one
|
|
3
|
+
* input to the next document and the event that records the step.
|
|
4
|
+
*
|
|
5
|
+
* ```
|
|
6
|
+
* PENDING ──SUBMIT──▶ SUBMITTED ──AUTHORIZE──▶ AUTHORIZED ──CANCEL──▶ CANCELLED
|
|
7
|
+
* │ │ ├──DENY─────▶ DENIED
|
|
8
|
+
* │ │ ├──REJECT───▶ REJECTED
|
|
9
|
+
* │ │ └──RETRY────▶ SUBMITTED
|
|
10
|
+
* │ └──REPLACE──▶ REPLACED
|
|
11
|
+
* ├──REPLACE──▶ REPLACED
|
|
12
|
+
* └──SIGN_OFFLINE──▶ CONTINGENCY ──AUTHORIZE | DENY | REJECT | RETRY──▶ …
|
|
13
|
+
* ▲ REJECTED (contingency) ──RESIGN──┘
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* A document is one number, so going offline is a SECOND document on the
|
|
17
|
+
* issuing point's contingency series (`PENDING → CONTINGENCY`), and the first
|
|
18
|
+
* one is `REPLACED`. Every input yields an event; a refused one throws
|
|
19
|
+
* {@link FiscalDocumentError} `TRANSITION_REFUSED` and changes nothing:
|
|
20
|
+
* `CANCELLED` is entered only from `AUTHORIZED`, and `AUTHORIZED` never from a
|
|
21
|
+
* final state. A rejected contingency NFC-e is the one way back: the store
|
|
22
|
+
* corrects it and it is signed again under the same number (`RESIGN`).
|
|
23
|
+
*
|
|
24
|
+
* `DEFER`, `RELEASE` and `WARN` record what the sweep and a person did without
|
|
25
|
+
* changing the state: a failed step counts toward {@link MAX_FAILURES}, after
|
|
26
|
+
* which the document waits for a person (`attention`).
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { type DocumentInput, STEPS, refuse } from "./machine-steps";
|
|
30
|
+
import type { DocumentEventKind, FiscalDocument, FiscalDocumentEvent, FiscalDocumentStatus } from "./types";
|
|
31
|
+
|
|
32
|
+
export { MAX_FAILURES } from "./machine-steps";
|
|
33
|
+
export type { DocumentInput } from "./machine-steps";
|
|
34
|
+
|
|
35
|
+
const ANY: readonly FiscalDocumentStatus[] = [
|
|
36
|
+
"PENDING", "SUBMITTED", "AUTHORIZED", "REJECTED", "DENIED", "CONTINGENCY", "CANCELLED", "REPLACED",
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
/** From which states each input is accepted. */
|
|
40
|
+
export const DOCUMENT_TRANSITIONS: Readonly<Record<DocumentEventKind, readonly FiscalDocumentStatus[]>> = {
|
|
41
|
+
SUBMIT: ["PENDING"],
|
|
42
|
+
AUTHORIZE: ["SUBMITTED", "CONTINGENCY"],
|
|
43
|
+
DENY: ["SUBMITTED", "CONTINGENCY"],
|
|
44
|
+
REJECT: ["SUBMITTED", "CONTINGENCY"],
|
|
45
|
+
RETRY: ["SUBMITTED", "CONTINGENCY"],
|
|
46
|
+
SIGN_OFFLINE: ["PENDING"],
|
|
47
|
+
REPLACE: ["PENDING", "SUBMITTED"],
|
|
48
|
+
CANCEL: ["AUTHORIZED", "REPLACED", "REJECTED"],
|
|
49
|
+
LOOKUP: ["SUBMITTED", "AUTHORIZED", "REPLACED", "REJECTED"],
|
|
50
|
+
INUTILIZE: ["REJECTED", "REPLACED"],
|
|
51
|
+
DEFER: ANY,
|
|
52
|
+
RESIGN: ["REJECTED"],
|
|
53
|
+
RELEASE: ANY,
|
|
54
|
+
WARN: ["CONTINGENCY"],
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** The states nothing but a lookup, a cancel or an inutilization of the number may follow. */
|
|
58
|
+
export const FINAL_STATUSES: readonly FiscalDocumentStatus[] = ["REJECTED", "DENIED", "CANCELLED", "REPLACED"];
|
|
59
|
+
|
|
60
|
+
export interface Transition {
|
|
61
|
+
readonly document: FiscalDocument;
|
|
62
|
+
readonly event: FiscalDocumentEvent;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const SECRET_KEY = /^(pfx|pfxBase64|password|passphrase|certificate|csc|token|privateKey)$/i;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A copy of an answer with every secret-named key dropped. The service never
|
|
69
|
+
* echoes one; this is the second lock, so an event row can never hold one.
|
|
70
|
+
*/
|
|
71
|
+
export function scrubSecrets(value: unknown): unknown {
|
|
72
|
+
if (Array.isArray(value)) return value.map(scrubSecrets);
|
|
73
|
+
if (value === null || typeof value !== "object") return value;
|
|
74
|
+
const out: Record<string, unknown> = {};
|
|
75
|
+
for (const [key, inner] of Object.entries(value)) {
|
|
76
|
+
if (!SECRET_KEY.test(key)) out[key] = scrubSecrets(inner);
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function answerOf(input: DocumentInput): unknown {
|
|
82
|
+
if ("answer" in input) return input.answer;
|
|
83
|
+
if ("error" in input && input.error !== null) return { error: input.error };
|
|
84
|
+
if (input.kind === "DEFER") return { reason: input.reason };
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function eventOf(document: FiscalDocument, input: DocumentInput, toStatus: FiscalDocumentStatus, at: string): FiscalDocumentEvent {
|
|
89
|
+
const error = "error" in input ? input.error : null;
|
|
90
|
+
const answer = "answer" in input ? input.answer : null;
|
|
91
|
+
return {
|
|
92
|
+
documentId: document.id,
|
|
93
|
+
kind: input.kind,
|
|
94
|
+
fromStatus: document.status,
|
|
95
|
+
toStatus,
|
|
96
|
+
at,
|
|
97
|
+
errorClass: error?.class ?? null,
|
|
98
|
+
code: error?.code ?? (answer !== null && "statusCode" in answer ? answer.statusCode : null),
|
|
99
|
+
answer: scrubSecrets(answerOf(input)),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const COUNTED = new Set<DocumentEventKind>(["SUBMIT", "RETRY", "SIGN_OFFLINE", "RESIGN"]);
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Apply one input. Throws `TRANSITION_REFUSED` (and changes nothing) when the
|
|
107
|
+
* document's state does not accept it. `at` is the caller's clock, ISO 8601.
|
|
108
|
+
*/
|
|
109
|
+
export function transition(document: FiscalDocument, input: DocumentInput, at: string): Transition {
|
|
110
|
+
if (!DOCUMENT_TRANSITIONS[input.kind].includes(document.status)) {
|
|
111
|
+
refuse(document, input.kind, `accepted only from ${DOCUMENT_TRANSITIONS[input.kind].join(", ")}`);
|
|
112
|
+
}
|
|
113
|
+
const step = STEPS[input.kind] as (document: FiscalDocument, input: DocumentInput) => Partial<FiscalDocument>;
|
|
114
|
+
const updated: FiscalDocument = {
|
|
115
|
+
...document,
|
|
116
|
+
...step(document, input),
|
|
117
|
+
...(input.kind === "WARN" ? { deadlineWarnedAt: at } : {}),
|
|
118
|
+
attempts: document.attempts + (COUNTED.has(input.kind) ? 1 : 0),
|
|
119
|
+
updatedAt: at,
|
|
120
|
+
};
|
|
121
|
+
return { document: updated, event: eventOf(document, input, updated.status, at) };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Whether an input would be accepted, without applying it. */
|
|
125
|
+
export function canTransition(status: FiscalDocumentStatus, kind: DocumentEventKind): boolean {
|
|
126
|
+
return DOCUMENT_TRANSITIONS[kind].includes(status);
|
|
127
|
+
}
|
|
128
|
+
|