@substrat-run/connector-fortnox 0.11.0 → 0.12.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 +11 -7
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +6 -1
- package/dist/api.js.map +1 -1
- package/dist/call.d.ts +46 -0
- package/dist/call.d.ts.map +1 -0
- package/dist/call.js +88 -0
- package/dist/call.js.map +1 -0
- package/dist/connection.d.ts +56 -0
- package/dist/connection.d.ts.map +1 -0
- package/dist/connection.js +2 -0
- package/dist/connection.js.map +1 -0
- package/dist/consent.d.ts +15 -4
- package/dist/consent.d.ts.map +1 -1
- package/dist/consent.js +16 -5
- package/dist/consent.js.map +1 -1
- package/dist/index.d.ts +45 -29
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +213 -183
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { addDecimal, CONNECTOR_ATTACHMENT_BUFFERED_MAX_BYTES, connectionActivity, connectionId as connectionIdSchema, entityRef, instant, money, mulDecimal, scopeId as scopeIdSchema, tenantId as tenantIdSchema, } from '@substrat-run/contracts';
|
|
3
|
-
import { deadlineFetch,
|
|
3
|
+
import { deadlineFetch, ulid } from '@substrat-run/kernel';
|
|
4
4
|
import { FortnoxApi, FortnoxApiError, fortnoxErrorCode, FORTNOX_API_BASE, FORTNOX_OAUTH_BASE, fortnoxSecret, } from './api.js';
|
|
5
5
|
import { financialYearFor, summarizeLedger } from './aggregate.js';
|
|
6
6
|
import { parseSie4 } from './sie4.js';
|
|
@@ -10,7 +10,8 @@ export { parseSie4, splitSieLine, sieAmount, sieDate, } from './sie4.js';
|
|
|
10
10
|
export { COST_CENTRE_DIMENSION, financialYearFor, summarizeLedger, } from './aggregate.js';
|
|
11
11
|
export { FortnoxMock } from './mock.js';
|
|
12
12
|
export { completeFortnoxConsent } from './connect.js';
|
|
13
|
-
export { FORTNOX_CONSENT_SCOPES, FORTNOX_INVOICE_FILE_SCOPES, FORTNOX_INVOICE_SCOPES, FORTNOX_LEDGER_SCOPES, FortnoxConsentShortfall, readFortnoxConsent, } from './consent.js';
|
|
13
|
+
export { FORTNOX_CONSENT_SCOPES, FORTNOX_INVOICE_FILE_SCOPES, FORTNOX_INVOICE_SCOPES, FORTNOX_LEDGER_SCOPES, FortnoxConsentShortfall, FORTNOX_PROBE_WRITES, fortnoxConsentWrite, readFortnoxConsent, } from './consent.js';
|
|
14
|
+
export { FORTNOX_PROBE_TIMEOUT_MS, FORTNOX_SWEEP_TIMEOUT_MS, fortnoxCallOptionsOf, runFortnoxCall, } from './call.js';
|
|
14
15
|
/**
|
|
15
16
|
* The Fortnox connector — the INBOUND half of accounting integration.
|
|
16
17
|
*
|
|
@@ -22,9 +23,17 @@ export { FORTNOX_CONSENT_SCOPES, FORTNOX_INVOICE_FILE_SCOPES, FORTNOX_INVOICE_SC
|
|
|
22
23
|
* vertical does not *ask* for last month's bookkeeping the way it asks for a signature;
|
|
23
24
|
* the bookkeeping simply changes at Fortnox, and the platform finds out by looking.
|
|
24
25
|
*
|
|
25
|
-
* So there is no `registerFortnoxConnector`. `sweepFortnoxLedger` is
|
|
26
|
-
*
|
|
27
|
-
*
|
|
26
|
+
* So there is no `registerFortnoxConnector`. `sweepFortnoxLedger` is what the platform's
|
|
27
|
+
* sweeper calls for each connection, handed that one connection's door (#3377), and that is
|
|
28
|
+
* the whole trigger surface.
|
|
29
|
+
*
|
|
30
|
+
* ## One connection per call, and nothing past it (#3377)
|
|
31
|
+
*
|
|
32
|
+
* Every function here is handed one connection's worth of the platform ({@link FortnoxOpened},
|
|
33
|
+
* {@link FortnoxConnectionDoor}, {@link FortnoxBindingDoor}, or its state), never a `ScopeHost`
|
|
34
|
+
* or a `HostAdmin`. The probes are calls of the one connector call contract
|
|
35
|
+
* ({@link runFortnoxCall}); the bindings, the sweep and a poll on request are no role of it and
|
|
36
|
+
* are handed the connection's door, which the platform builds.
|
|
28
37
|
*
|
|
29
38
|
* ## Where the data lands, and why the connector does not decide
|
|
30
39
|
*
|
|
@@ -329,11 +338,26 @@ const lastModifiedFilter = (ms) => {
|
|
|
329
338
|
* Record what this consent covers (#2422) — what a console reads back as "needs re-consent".
|
|
330
339
|
* Costs no round trip: the mint it reads from is the one the pass needs anyway.
|
|
331
340
|
*/
|
|
332
|
-
async function noteConsent(
|
|
341
|
+
async function noteConsent(state, api, options) {
|
|
333
342
|
const at = new Date(options.now?.() ?? Date.now()).toISOString();
|
|
334
343
|
const consent = await fortnoxConsentOf(api, options.consentScopes ?? FORTNOX_CONSENT_SCOPES, at);
|
|
335
344
|
if (consent)
|
|
336
|
-
await recordFortnoxConsent(
|
|
345
|
+
await recordFortnoxConsent(state, consent);
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* The connection as the client reads it: the credential and the egress. The client reads nothing
|
|
349
|
+
* else, so a probe's connection, which the call carries without the rest, is built the same way.
|
|
350
|
+
*/
|
|
351
|
+
function apiConnection(conn) {
|
|
352
|
+
return {
|
|
353
|
+
id: conn.connection?.id ?? connectionIdSchema.parse('00000000000000000000000000'), // never read
|
|
354
|
+
tenantId: conn.connection?.tenantId ?? '',
|
|
355
|
+
vertical: conn.connection?.vertical ?? '',
|
|
356
|
+
provider: 'fortnox',
|
|
357
|
+
secret: conn.secret,
|
|
358
|
+
expiresAt: conn.connection?.expiresAt ?? null,
|
|
359
|
+
fetch: conn.fetch,
|
|
360
|
+
};
|
|
337
361
|
}
|
|
338
362
|
/** The client options a sync builds its `FortnoxApi` with. */
|
|
339
363
|
const apiOptions = (options) => ({
|
|
@@ -354,9 +378,9 @@ const apiOptions = (options) => ({
|
|
|
354
378
|
* nobody is watching, with a provider round trip already spent. Here it fails in the
|
|
355
379
|
* operator's hands, naming the permission to grant.
|
|
356
380
|
*/
|
|
357
|
-
export async function bindFortnoxScope(
|
|
358
|
-
|
|
359
|
-
|
|
381
|
+
export async function bindFortnoxScope(door, input) {
|
|
382
|
+
tenantIdSchema.parse(input.tenantId);
|
|
383
|
+
scopeIdSchema.parse(input.scopeId);
|
|
360
384
|
if (input.ownerScopeId && input.ownerScopeId !== input.scopeId) {
|
|
361
385
|
throw new Error(`connection ${input.connectionId} is scope ${input.ownerScopeId}'s own, and lands in that scope alone, not ${input.scopeId}`);
|
|
362
386
|
}
|
|
@@ -372,15 +396,15 @@ export async function bindFortnoxScope(host, input) {
|
|
|
372
396
|
if ((input.firstPass !== undefined || input.writeback !== undefined) && input.kind !== 'supplier-invoice') {
|
|
373
397
|
throw new Error(`firstPass and writeback apply to a supplier-invoice binding, not to '${input.kind ?? 'ledger'}'`);
|
|
374
398
|
}
|
|
375
|
-
const current = (await listFortnoxBindings(
|
|
399
|
+
const current = (await listFortnoxBindings(door.state)).find((b) => b.scopeId === input.scopeId);
|
|
376
400
|
if (current && (current.kind ?? 'ledger') !== (input.kind ?? 'ledger')) {
|
|
377
401
|
throw new Error(`one Fortnox landing kind per scope; use a separate scope for the other kind (${current.kind ?? 'ledger'} to ${input.kind ?? 'ledger'} on scope ${input.scopeId})`);
|
|
378
402
|
}
|
|
379
|
-
//
|
|
380
|
-
//
|
|
381
|
-
// not
|
|
382
|
-
const
|
|
383
|
-
|
|
403
|
+
// The door reads the same projection the permission checker reads, so a binding is verified
|
|
404
|
+
// against the tuples that will actually gate the invoke — not against a directory row that may
|
|
405
|
+
// not have reached the scope yet.
|
|
406
|
+
const held = input.grantPreflighted ||
|
|
407
|
+
(await door.holds({ tenantId: input.tenantId, scopeId: input.scopeId, permission: input.permission }));
|
|
384
408
|
if (!held) {
|
|
385
409
|
throw new Error(`connection ${input.connectionId} does not hold '${input.permission}' on scope ${input.scopeId} — ` +
|
|
386
410
|
`a sweep would fetch the ledger and then fail to land it. Grant it first ` +
|
|
@@ -417,12 +441,12 @@ export async function bindFortnoxScope(host, input) {
|
|
|
417
441
|
: {}),
|
|
418
442
|
boundAt: new Date(input.now?.() ?? Date.now()).toISOString(),
|
|
419
443
|
};
|
|
420
|
-
await
|
|
444
|
+
await door.state.put(bindingKey(input.scopeId), binding);
|
|
421
445
|
return binding;
|
|
422
446
|
}
|
|
423
447
|
/** Every scope this connection syncs into. */
|
|
424
|
-
export async function listFortnoxBindings(
|
|
425
|
-
const rows = await
|
|
448
|
+
export async function listFortnoxBindings(state) {
|
|
449
|
+
const rows = await state.list(BINDING_PREFIX);
|
|
426
450
|
// Tombstones filtered, exactly as the sweep and the activity projection do.
|
|
427
451
|
// `unbindFortnoxScope` writes `null` under the same key, and casting that to
|
|
428
452
|
// `FortnoxBinding` hands a caller a typed value that throws on the first property
|
|
@@ -437,8 +461,8 @@ export async function listFortnoxBindings(host, connectionId) {
|
|
|
437
461
|
* unbound scope that a later sweep silently re-adopts would be worse than a visible
|
|
438
462
|
* dead row.
|
|
439
463
|
*/
|
|
440
|
-
export async function unbindFortnoxScope(
|
|
441
|
-
await
|
|
464
|
+
export async function unbindFortnoxScope(state, scopeId) {
|
|
465
|
+
await state.put(bindingKey(scopeId), null);
|
|
442
466
|
}
|
|
443
467
|
const sha256Hex = async (text) => {
|
|
444
468
|
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
@@ -452,15 +476,15 @@ const sha256Hex = async (text) => {
|
|
|
452
476
|
* and an unchanged hash returns `changed: false` without a single `invoke` — which
|
|
453
477
|
* matters because a sweep runs on a timer and most passes find books nobody has touched.
|
|
454
478
|
*/
|
|
455
|
-
export async function syncFortnoxScope(
|
|
479
|
+
export async function syncFortnoxScope(conn, binding, options) {
|
|
456
480
|
if (binding.kind !== undefined && binding.kind !== 'ledger') {
|
|
457
481
|
throw new Error(`ledger sync cannot use Fortnox binding kind '${String(binding.kind)}'`);
|
|
458
482
|
}
|
|
459
|
-
const
|
|
460
|
-
|
|
461
|
-
const api = new FortnoxApi(conn, apiOptions(options));
|
|
483
|
+
const connectionId = conn.connection.id;
|
|
484
|
+
ownerOf(connectionId, binding);
|
|
485
|
+
const api = new FortnoxApi(apiConnection(conn), apiOptions(options));
|
|
462
486
|
// #2422: a consent without `bookkeeping` answers every read 403; say so before reading.
|
|
463
|
-
await noteConsent(
|
|
487
|
+
await noteConsent(conn.state, api, options);
|
|
464
488
|
await requireFortnoxScopes(api, FORTNOX_LEDGER_SCOPES, 'a ledger binding');
|
|
465
489
|
// The period defaults to the calendar year containing "now", which is the sane
|
|
466
490
|
// default for a recurring sync; a caller back-filling names its own.
|
|
@@ -516,7 +540,7 @@ export async function syncFortnoxScope(host, connectionId, binding, options) {
|
|
|
516
540
|
// The connection acting as itself (#97). Refuses a scope in another tenant or running
|
|
517
541
|
// another vertical by construction, and the invoke below is gated on the connection's
|
|
518
542
|
// own grant — the one `bindFortnoxScope` verified.
|
|
519
|
-
const scope = await
|
|
543
|
+
const scope = await conn.scope(scopeIdSchema.parse(binding.scopeId));
|
|
520
544
|
const pageCount = Math.max(1, Math.ceil(summary.balances.length / PAGE_SIZE));
|
|
521
545
|
for (let page = 0; page < pageCount; page += 1) {
|
|
522
546
|
const slice = summary.balances.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
|
|
@@ -553,7 +577,7 @@ export async function syncFortnoxScope(host, connectionId, binding, options) {
|
|
|
553
577
|
// Written only AFTER every page landed, so a failure mid-way leaves the cursor at the
|
|
554
578
|
// previous hash and the next sweep retries the whole year rather than resuming into a
|
|
555
579
|
// half-written ledger.
|
|
556
|
-
await
|
|
580
|
+
await conn.state.put(bindingKey(binding.scopeId), synced);
|
|
557
581
|
return {
|
|
558
582
|
scopeId: binding.scopeId,
|
|
559
583
|
changed: true,
|
|
@@ -576,10 +600,11 @@ export async function syncFortnoxScope(host, connectionId, binding, options) {
|
|
|
576
600
|
* Each year is written to the binding right after it lands, so a failure on one costs only that one,
|
|
577
601
|
* and the years that did land are answered beside the ones that failed.
|
|
578
602
|
*/
|
|
579
|
-
export async function syncFortnoxSieFiles(
|
|
580
|
-
const
|
|
581
|
-
|
|
582
|
-
|
|
603
|
+
export async function syncFortnoxSieFiles(conn, binding, options) {
|
|
604
|
+
const connectionId = conn.connection.id;
|
|
605
|
+
ownerOf(connectionId, binding);
|
|
606
|
+
const api = new FortnoxApi(apiConnection(conn), apiOptions(options));
|
|
607
|
+
await noteConsent(conn.state, api, options);
|
|
583
608
|
await requireFortnoxScopes(api, FORTNOX_LEDGER_SCOPES, 'a ledger binding');
|
|
584
609
|
const nowMs = options.now?.() ?? Date.now();
|
|
585
610
|
const year = new Date(nowMs).toISOString().slice(0, 4);
|
|
@@ -618,7 +643,7 @@ export async function syncFortnoxSieFiles(host, connectionId, binding, options)
|
|
|
618
643
|
// The file names its company (#FNAMN, #ORGNR), as the summary form reads it.
|
|
619
644
|
const ledger = parseSie4(sie);
|
|
620
645
|
// The connection acting as itself (#97), gated on the grant the binding was seated with.
|
|
621
|
-
const scope = await
|
|
646
|
+
const scope = await conn.scope(scopeIdSchema.parse(binding.scopeId));
|
|
622
647
|
await scope.invoke(binding.operation, fortnoxSieFile.parse({
|
|
623
648
|
syncId: contentHash,
|
|
624
649
|
connectionId,
|
|
@@ -630,12 +655,12 @@ export async function syncFortnoxSieFiles(host, connectionId, binding, options)
|
|
|
630
655
|
// A year is a long download, so the binding read at the start of the pass may be stale by now:
|
|
631
656
|
// the cursor goes onto the binding as it stands, and one unbound or re-bound meanwhile is left
|
|
632
657
|
// as the person left it rather than brought back from this pass's copy.
|
|
633
|
-
const now = (await
|
|
658
|
+
const now = (await conn.state.get(key));
|
|
634
659
|
if (!now || typeof now !== 'object' || now.boundAt !== binding.boundAt)
|
|
635
660
|
break;
|
|
636
661
|
const syncedAt = new Date(nowMs).toISOString();
|
|
637
662
|
const { [String(financialYear.Id)]: _landed, ...stillFailed } = now.yearFailedAt ?? {};
|
|
638
|
-
await
|
|
663
|
+
await conn.state.put(key, {
|
|
639
664
|
...now,
|
|
640
665
|
yearSync: { ...now.yearSync, [String(financialYear.Id)]: { syncedAt, contentHash } },
|
|
641
666
|
yearFailedAt: Object.keys(stillFailed).length > 0 ? stillFailed : undefined,
|
|
@@ -655,7 +680,7 @@ export async function syncFortnoxSieFiles(host, connectionId, binding, options)
|
|
|
655
680
|
failed.push({ financialYearId: financialYear.Id, error });
|
|
656
681
|
// The current year is tried every pass anyway; an older one is put back in the queue.
|
|
657
682
|
if (financialYear !== current)
|
|
658
|
-
await markYearFailed(
|
|
683
|
+
await markYearFailed(conn.state, key, binding, financialYear.Id, nowMs);
|
|
659
684
|
}
|
|
660
685
|
}
|
|
661
686
|
return { synced, failed };
|
|
@@ -665,12 +690,12 @@ export async function syncFortnoxSieFiles(host, connectionId, binding, options)
|
|
|
665
690
|
* year's error is already answered, so a failure to record it only means the year is tried again
|
|
666
691
|
* next pass, as it was before this was recorded.
|
|
667
692
|
*/
|
|
668
|
-
async function markYearFailed(
|
|
693
|
+
async function markYearFailed(state, key, binding, financialYearId, nowMs) {
|
|
669
694
|
try {
|
|
670
|
-
const now = (await
|
|
695
|
+
const now = (await state.get(key));
|
|
671
696
|
if (!now || typeof now !== 'object' || now.boundAt !== binding.boundAt)
|
|
672
697
|
return;
|
|
673
|
-
await
|
|
698
|
+
await state.put(key, {
|
|
674
699
|
...now,
|
|
675
700
|
yearFailedAt: { ...now.yearFailedAt, [String(financialYearId)]: new Date(nowMs).toISOString() },
|
|
676
701
|
});
|
|
@@ -693,15 +718,15 @@ async function markYearFailed(host, connectionId, key, binding, financialYearId,
|
|
|
693
718
|
* Files come after the cursor, because a file that cannot be read says nothing about the invoice:
|
|
694
719
|
* the invoices keep landing, and the file stays queued and fails the scope's row by its number.
|
|
695
720
|
*/
|
|
696
|
-
export async function syncFortnoxSupplierInvoices(
|
|
721
|
+
export async function syncFortnoxSupplierInvoices(conn, binding, options) {
|
|
697
722
|
if (binding.kind !== 'supplier-invoice') {
|
|
698
723
|
throw new Error(`supplier-invoice sync cannot use Fortnox binding kind '${String(binding.kind ?? 'ledger')}'`);
|
|
699
724
|
}
|
|
700
|
-
|
|
701
|
-
const api = new FortnoxApi(conn, apiOptions(options));
|
|
725
|
+
ownerOf(conn.connection.id, binding);
|
|
726
|
+
const api = new FortnoxApi(apiConnection(conn), apiOptions(options));
|
|
702
727
|
// #2422: without these nothing lands, so the binding fails saying so rather than on a 403. The
|
|
703
728
|
// files' scopes are checked by the file half, because the invoices land without them.
|
|
704
|
-
await noteConsent(
|
|
729
|
+
await noteConsent(conn.state, api, options);
|
|
705
730
|
await requireFortnoxScopes(api, FORTNOX_INVOICE_SCOPES, 'a supplier-invoice binding');
|
|
706
731
|
const nowMs = options.now?.() ?? Date.now();
|
|
707
732
|
const expired = () => (options.now?.() ?? Date.now()) - nowMs >= INVOICE_PASS_DEADLINE_MS;
|
|
@@ -710,7 +735,7 @@ export async function syncFortnoxSupplierInvoices(host, connectionId, binding, o
|
|
|
710
735
|
const scopeRef = scopeIdSchema.parse(binding.scopeId);
|
|
711
736
|
let companyRead;
|
|
712
737
|
const company = () => (companyRead ??= api.companyInformation());
|
|
713
|
-
const files = new InvoiceFiles(
|
|
738
|
+
const files = new InvoiceFiles(conn, binding.scopeId, scopeRef, api, budget, expired, binding.files);
|
|
714
739
|
const withFiles = (base) => {
|
|
715
740
|
const { files: _held, ...rest } = base;
|
|
716
741
|
return { ...rest, ...files.held() };
|
|
@@ -718,7 +743,7 @@ export async function syncFortnoxSupplierInvoices(host, connectionId, binding, o
|
|
|
718
743
|
const saveFiles = async (base) => {
|
|
719
744
|
if (!files.moved)
|
|
720
745
|
return;
|
|
721
|
-
await
|
|
746
|
+
await conn.state.put(bindingKey(binding.scopeId), withFiles(base));
|
|
722
747
|
files.moved = false;
|
|
723
748
|
};
|
|
724
749
|
// The queue goes first, so it never outgrows one pass's budget, and it is saved at once, so a
|
|
@@ -727,10 +752,10 @@ export async function syncFortnoxSupplierInvoices(host, connectionId, binding, o
|
|
|
727
752
|
await saveFiles(binding);
|
|
728
753
|
// A pass's parts are independent: a landing that throws says nothing about a decision waiting to be
|
|
729
754
|
// written, and an idle pass is when most decisions are. The first failure is thrown at the end.
|
|
730
|
-
const landing = await landChangedInvoices(
|
|
755
|
+
const landing = await landChangedInvoices(conn, binding, { api, company, files, budget, expired, nowMs, withFiles, saveFiles })
|
|
731
756
|
.catch((err) => ({ landed: 0, more: true, failure: asError(err) }));
|
|
732
757
|
const writes = binding.writeback
|
|
733
|
-
? await writeBackInvoices(
|
|
758
|
+
? await writeBackInvoices(conn, binding, binding.writeback, { api, company, budget, expired, nowMs })
|
|
734
759
|
.catch((err) => ({ held: 0, written: 0, more: true, failure: asError(err) }))
|
|
735
760
|
: { held: 0, written: 0, more: false, failure: null };
|
|
736
761
|
const failure = landing.failure ?? files.failed ?? writes.failure;
|
|
@@ -748,16 +773,17 @@ export async function syncFortnoxSupplierInvoices(host, connectionId, binding, o
|
|
|
748
773
|
}
|
|
749
774
|
const asError = (err) => (err instanceof Error ? err : new Error(String(err)));
|
|
750
775
|
/**
|
|
751
|
-
* A read that failed, with what the binding's tenant may be told about it (#3103
|
|
752
|
-
* staff's: it carries Fortnox's own answer. `said` is built only from what
|
|
753
|
-
* itself (the invoice number, the field our schema could not read,
|
|
754
|
-
* row can say why the binding did not land
|
|
776
|
+
* A read or a write-back that failed, with what the binding's tenant may be told about it (#3103,
|
|
777
|
+
* #3452). The message is staff's: it carries Fortnox's own answer. `said` is built only from what
|
|
778
|
+
* this connector names itself (the invoice number, the step, the field our schema could not read,
|
|
779
|
+
* the HTTP status, Fortnox's numeric code), so the sweep's row can say why the binding did not land
|
|
780
|
+
* without carrying a provider's text.
|
|
755
781
|
*/
|
|
756
|
-
class
|
|
782
|
+
class FortnoxSaidFailure extends Error {
|
|
757
783
|
said;
|
|
758
784
|
constructor(message, said) {
|
|
759
785
|
super(message);
|
|
760
|
-
this.name = '
|
|
786
|
+
this.name = 'FortnoxSaidFailure';
|
|
761
787
|
this.said = said;
|
|
762
788
|
}
|
|
763
789
|
}
|
|
@@ -775,9 +801,22 @@ function invoiceReadSaid(givenNumber, err) {
|
|
|
775
801
|
return `Fortnox answered ${err.status} for supplier invoice ${givenNumber}`;
|
|
776
802
|
return null;
|
|
777
803
|
}
|
|
804
|
+
/** `Fortnox answered 400 (code 2003576)`, from the status and the envelope's code alone, or null for a failure that is not Fortnox's. */
|
|
805
|
+
function fortnoxAnswered(err) {
|
|
806
|
+
if (!(err instanceof FortnoxApiError))
|
|
807
|
+
return null;
|
|
808
|
+
const code = fortnoxErrorCode(err);
|
|
809
|
+
return `Fortnox answered ${err.status}${code === null ? '' : ` (code ${code})`}`;
|
|
810
|
+
}
|
|
811
|
+
/** A write-back failure, staff's text and the tenant's line: `<what> <how>`, then why when Fortnox answered. */
|
|
812
|
+
function writeFailure(what, how, err) {
|
|
813
|
+
const answered = fortnoxAnswered(err);
|
|
814
|
+
return new FortnoxSaidFailure(`${what} ${how}: ${asError(err).message}`, `${what} ${how}${answered === null ? '' : `: ${answered}`}`);
|
|
815
|
+
}
|
|
778
816
|
/** Land what changed since the cursor, then read the files the landing asked for. */
|
|
779
|
-
async function landChangedInvoices(
|
|
817
|
+
async function landChangedInvoices(conn, binding, pass) {
|
|
780
818
|
const { api, company: companyOf, files, budget, expired, nowMs, withFiles, saveFiles } = pass;
|
|
819
|
+
const connectionId = conn.connection.id;
|
|
781
820
|
if (budget.details <= 0 || expired())
|
|
782
821
|
return { landed: 0, more: true, failure: null };
|
|
783
822
|
const cursor = binding.invoiceSync;
|
|
@@ -810,7 +849,7 @@ async function landChangedInvoices(host, connectionId, binding, pass) {
|
|
|
810
849
|
if (!(err instanceof FortnoxApiError && err.status === 404)) {
|
|
811
850
|
const text = `supplier invoice ${givenNumber}: ${err instanceof Error ? err.message : String(err)}`;
|
|
812
851
|
const said = invoiceReadSaid(givenNumber, err);
|
|
813
|
-
failure = said === null ? new Error(text) : new
|
|
852
|
+
failure = said === null ? new Error(text) : new FortnoxSaidFailure(text, said);
|
|
814
853
|
break;
|
|
815
854
|
}
|
|
816
855
|
}
|
|
@@ -829,7 +868,7 @@ async function landChangedInvoices(host, connectionId, binding, pass) {
|
|
|
829
868
|
invoices,
|
|
830
869
|
});
|
|
831
870
|
// The connection acting as itself (#97), gated on the grant the binding was seated with.
|
|
832
|
-
const scope = await
|
|
871
|
+
const scope = await conn.scope(scopeIdSchema.parse(binding.scopeId));
|
|
833
872
|
files.ask(await scope.invoke(binding.operation, payload));
|
|
834
873
|
}
|
|
835
874
|
const more = changed.length > handled;
|
|
@@ -843,7 +882,7 @@ async function landChangedInvoices(host, connectionId, binding, pass) {
|
|
|
843
882
|
...(more ? { pending: { startedAt, through: batch[handled - 1] } } : {}),
|
|
844
883
|
},
|
|
845
884
|
});
|
|
846
|
-
await
|
|
885
|
+
await conn.state.put(bindingKey(binding.scopeId), synced);
|
|
847
886
|
files.moved = false;
|
|
848
887
|
await files.drain();
|
|
849
888
|
await saveFiles(synced);
|
|
@@ -863,15 +902,18 @@ const statedRefusal = (err) => err instanceof FortnoxApiError && err.status >= 4
|
|
|
863
902
|
* approval: the block is lifted first, while it still can be, then the invoice is approved and booked.
|
|
864
903
|
* That order leaves nothing payable unblocked, because such a company cannot pay an unbooked invoice.
|
|
865
904
|
*
|
|
866
|
-
* Only
|
|
867
|
-
*
|
|
905
|
+
* Only transient failures are retried here. A refusal in Fortnox's own words is not, because the next
|
|
906
|
+
* pass would get the same answer and a person has to act: a decision's goes to the vertical at once,
|
|
907
|
+
* and a hold's is remembered on the invoice's note and fails one pass, not every pass (#3452).
|
|
868
908
|
*/
|
|
869
|
-
async function writeBackInvoices(
|
|
909
|
+
async function writeBackInvoices(conn, binding, operations, pass) {
|
|
870
910
|
const { api, budget, expired, nowMs } = pass;
|
|
911
|
+
const connectionId = conn.connection.id;
|
|
912
|
+
const state = conn.state;
|
|
871
913
|
// A pass with no budget left for one write asks nothing of Fortnox, not even who the company is.
|
|
872
914
|
if (budget.details < INVOICE_HOLD_CALLS || expired())
|
|
873
915
|
return { held: 0, written: 0, more: true, failure: null };
|
|
874
|
-
const scope = await
|
|
916
|
+
const scope = await conn.scope(scopeIdSchema.parse(binding.scopeId));
|
|
875
917
|
const company = await pass.company();
|
|
876
918
|
const waiting = fortnoxInvoiceWriteback.parse(await scope.invoke(operations.read, {
|
|
877
919
|
connectionId,
|
|
@@ -882,11 +924,11 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
|
|
|
882
924
|
for (const { givenNumber } of waiting.hold) {
|
|
883
925
|
const key = invoiceHoldKey(givenNumber);
|
|
884
926
|
// A released hold does not count: an invoice can come back to the queue, and then it is held again.
|
|
885
|
-
const known = (await
|
|
927
|
+
const known = (await state.get(key));
|
|
886
928
|
const live = known && !known.cleared ? known : null;
|
|
887
929
|
// Only a block this connector saw set is left alone. Someone else's is looked at again, because
|
|
888
930
|
// lifting it would leave the undecided invoice payable, and so is one Fortnox never confirmed.
|
|
889
|
-
if ((live?.ours && !live.unconfirmed) || live?.approved)
|
|
931
|
+
if ((live?.ours && !live.unconfirmed) || live?.approved || live?.refused)
|
|
890
932
|
continue;
|
|
891
933
|
if (budget.details < INVOICE_HOLD_CALLS || expired()) {
|
|
892
934
|
out.more = true;
|
|
@@ -898,16 +940,16 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
|
|
|
898
940
|
if ((await api.supplierInvoice(givenNumber)).DisablePaymentFile) {
|
|
899
941
|
// Blocked already: ours when our unconfirmed write went through, someone else's otherwise.
|
|
900
942
|
if (!live || live.unconfirmed) {
|
|
901
|
-
await
|
|
943
|
+
await state.put(key, { ours: !!live?.ours, at: live?.at ?? at });
|
|
902
944
|
}
|
|
903
945
|
continue;
|
|
904
946
|
}
|
|
905
947
|
// Remembered before the write: a pass that dies between them must not leave a block nobody
|
|
906
948
|
// knows is ours, which no approval would ever clear and which keeps a good invoice unpaid.
|
|
907
|
-
await
|
|
949
|
+
await state.put(key, { ours: true, at, unconfirmed: true });
|
|
908
950
|
asked = true;
|
|
909
951
|
await api.setSupplierInvoicePaymentBlock(givenNumber, true);
|
|
910
|
-
await
|
|
952
|
+
await state.put(key, { ours: true, at });
|
|
911
953
|
out.held += 1;
|
|
912
954
|
}
|
|
913
955
|
catch (err) {
|
|
@@ -915,14 +957,20 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
|
|
|
915
957
|
// note stays unconfirmed and the next pass reads the invoice to find out.
|
|
916
958
|
if (fortnoxErrorCode(err) === APPROVED_LOCKED) {
|
|
917
959
|
// Approved before it could be held: asking again gets the same answer every pass.
|
|
918
|
-
await
|
|
919
|
-
out.failure ??= new
|
|
920
|
-
`so it cannot be blocked over the API. Block it in Fortnox if it must wait for the decision
|
|
960
|
+
await state.put(key, { ours: false, at, approved: true });
|
|
961
|
+
out.failure ??= new FortnoxSaidFailure(`hold of supplier invoice ${givenNumber}: it was approved in Fortnox before it could be held, ` +
|
|
962
|
+
`so it cannot be blocked over the API. Block it in Fortnox if it must wait for the decision. ${asError(err).message}`, `supplier invoice ${givenNumber} was approved in Fortnox before it could be held: ${fortnoxAnswered(err)}`);
|
|
963
|
+
continue;
|
|
964
|
+
}
|
|
965
|
+
if (asked && statedRefusal(err) && err instanceof FortnoxApiError) {
|
|
966
|
+
// Refused in Fortnox's words, so the block was not set and asking again gets the same answer:
|
|
967
|
+
// remembered, and failed for once (#3452), rather than asked and failed on every pass.
|
|
968
|
+
const refused = { status: err.status, code: fortnoxErrorCode(err), at };
|
|
969
|
+
await state.put(key, { ours: false, at, refused });
|
|
970
|
+
out.failure ??= writeFailure(`hold of supplier invoice ${givenNumber}`, 'was refused, and is not asked again until the invoice is decided', err);
|
|
921
971
|
continue;
|
|
922
972
|
}
|
|
923
|
-
|
|
924
|
-
await host.admin.putConnectorState(connectionId, key, known ?? null);
|
|
925
|
-
out.failure ??= new Error(`hold of supplier invoice ${givenNumber}: ${asError(err).message}`);
|
|
973
|
+
out.failure ??= writeFailure(`hold of supplier invoice ${givenNumber}`, 'failed', err);
|
|
926
974
|
}
|
|
927
975
|
}
|
|
928
976
|
for (const decision of waiting.decisions) {
|
|
@@ -932,20 +980,26 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
|
|
|
932
980
|
}
|
|
933
981
|
budget.details -= INVOICE_DECISION_CALLS;
|
|
934
982
|
const tries = invoiceWriteKey(decision.key);
|
|
983
|
+
const progress = { step: 'the read' };
|
|
935
984
|
try {
|
|
936
|
-
await settleInvoiceDecision(
|
|
985
|
+
await settleInvoiceDecision(state, api, decision, at, progress);
|
|
986
|
+
progress.step = 'the receipt';
|
|
937
987
|
await scope.invoke(operations.record, fortnoxInvoiceWritebackReceipt.parse({ key: decision.key, status: 'done', error: null }));
|
|
938
|
-
await
|
|
988
|
+
await state.put(tries, null);
|
|
989
|
+
await forgetRefusedHold(state, decision.givenNumber, at);
|
|
939
990
|
out.written += 1;
|
|
940
991
|
}
|
|
941
992
|
catch (err) {
|
|
942
993
|
const error = asError(err);
|
|
943
|
-
const attempts = ((await
|
|
944
|
-
|
|
994
|
+
const attempts = ((await state.get(tries))?.attempts ?? 0) + 1;
|
|
995
|
+
// The step says how far the decision got (#3452): a refused second booking reads apart from a
|
|
996
|
+
// first booking that was refused for another reason.
|
|
997
|
+
out.failure ??= writeFailure(`write-back of supplier invoice ${decision.givenNumber}`, `failed at ${progress.step}`, err);
|
|
945
998
|
if (statedRefusal(err) || attempts >= INVOICE_WRITE_ATTEMPTS) {
|
|
946
999
|
try {
|
|
947
1000
|
await scope.invoke(operations.record, fortnoxInvoiceWritebackReceipt.parse({ key: decision.key, status: 'failed', error: error.message }));
|
|
948
|
-
await
|
|
1001
|
+
await state.put(tries, null);
|
|
1002
|
+
await forgetRefusedHold(state, decision.givenNumber, at);
|
|
949
1003
|
continue;
|
|
950
1004
|
}
|
|
951
1005
|
catch {
|
|
@@ -953,21 +1007,33 @@ async function writeBackInvoices(host, connectionId, binding, operations, pass)
|
|
|
953
1007
|
// again, and this pass goes on to the rest. The first failure is already the one reported.
|
|
954
1008
|
}
|
|
955
1009
|
}
|
|
956
|
-
await
|
|
1010
|
+
await state.put(tries, { attempts, lastError: error.message });
|
|
957
1011
|
}
|
|
958
1012
|
}
|
|
959
1013
|
return out;
|
|
960
1014
|
}
|
|
1015
|
+
/**
|
|
1016
|
+
* A settled decision ends what a refused hold remembered, so an invoice that comes back to the queue
|
|
1017
|
+
* is asked about again. A note for any other hold stays: whether to lift that block is the release's.
|
|
1018
|
+
*/
|
|
1019
|
+
async function forgetRefusedHold(state, givenNumber, at) {
|
|
1020
|
+
const key = invoiceHoldKey(givenNumber);
|
|
1021
|
+
const hold = (await state.get(key));
|
|
1022
|
+
if (hold?.refused && !hold.cleared)
|
|
1023
|
+
await state.put(key, { ...hold, cleared: at });
|
|
1024
|
+
}
|
|
961
1025
|
/** Bring Fortnox to what one decision says. Safe to repeat: every step looks before it writes. */
|
|
962
|
-
async function settleInvoiceDecision(
|
|
1026
|
+
async function settleInvoiceDecision(state, api, decision, at, progress) {
|
|
963
1027
|
const { givenNumber, book, release, comment } = decision;
|
|
1028
|
+
progress.step = 'the read';
|
|
964
1029
|
const invoice = await api.supplierInvoice(givenNumber);
|
|
965
1030
|
const key = invoiceHoldKey(givenNumber);
|
|
966
1031
|
/** Lift the block this binding set, once. */
|
|
967
1032
|
const releaseHold = async () => {
|
|
968
|
-
const hold = (await
|
|
1033
|
+
const hold = (await state.get(key));
|
|
969
1034
|
if (!hold?.ours || hold.cleared)
|
|
970
1035
|
return;
|
|
1036
|
+
progress.step = 'the release';
|
|
971
1037
|
if (invoice.DisablePaymentFile) {
|
|
972
1038
|
try {
|
|
973
1039
|
await api.setSupplierInvoicePaymentBlock(givenNumber, false);
|
|
@@ -979,11 +1045,12 @@ async function settleInvoiceDecision(host, connectionId, api, decision, at) {
|
|
|
979
1045
|
`so its payment block can be lifted only in Fortnox: ${err.message}`, err.status, err.body);
|
|
980
1046
|
}
|
|
981
1047
|
}
|
|
982
|
-
await
|
|
1048
|
+
await state.put(key, { ...hold, cleared: at });
|
|
983
1049
|
};
|
|
984
1050
|
let released = false;
|
|
985
1051
|
if (book && !invoice.Booked) {
|
|
986
1052
|
try {
|
|
1053
|
+
progress.step = 'the booking';
|
|
987
1054
|
await api.bookSupplierInvoice(givenNumber);
|
|
988
1055
|
}
|
|
989
1056
|
catch (err) {
|
|
@@ -993,12 +1060,15 @@ async function settleInvoiceDecision(host, connectionId, api, decision, at) {
|
|
|
993
1060
|
if (release)
|
|
994
1061
|
await releaseHold();
|
|
995
1062
|
released = true;
|
|
1063
|
+
progress.step = 'the approval';
|
|
996
1064
|
await api.approveSupplierInvoice(givenNumber);
|
|
1065
|
+
progress.step = 'the booking after approval';
|
|
997
1066
|
await api.bookSupplierInvoice(givenNumber);
|
|
998
1067
|
}
|
|
999
1068
|
}
|
|
1000
1069
|
if (release && !released)
|
|
1001
1070
|
await releaseHold();
|
|
1071
|
+
progress.step = 'the comment';
|
|
1002
1072
|
if (comment !== null && !(await api.supplierInvoiceComments(givenNumber)).includes(comment)) {
|
|
1003
1073
|
await api.addSupplierInvoiceComment(givenNumber, comment);
|
|
1004
1074
|
}
|
|
@@ -1014,8 +1084,7 @@ const triedKey = (entry) => JSON.stringify([entry.givenNumber, entry.entity.enti
|
|
|
1014
1084
|
* them all: it is the company's consent, and every other file would answer the same.
|
|
1015
1085
|
*/
|
|
1016
1086
|
class InvoiceFiles {
|
|
1017
|
-
|
|
1018
|
-
connectionId;
|
|
1087
|
+
conn;
|
|
1019
1088
|
scopeId;
|
|
1020
1089
|
scopeRef;
|
|
1021
1090
|
api;
|
|
@@ -1036,9 +1105,8 @@ class InvoiceFiles {
|
|
|
1036
1105
|
skipped = [];
|
|
1037
1106
|
/** True once the queue differs from what the binding holds. */
|
|
1038
1107
|
moved = false;
|
|
1039
|
-
constructor(
|
|
1040
|
-
this.
|
|
1041
|
-
this.connectionId = connectionId;
|
|
1108
|
+
constructor(conn, scopeId, scopeRef, api, budget, expired, held = []) {
|
|
1109
|
+
this.conn = conn;
|
|
1042
1110
|
this.scopeId = scopeId;
|
|
1043
1111
|
this.scopeRef = scopeRef;
|
|
1044
1112
|
this.api = api;
|
|
@@ -1122,7 +1190,7 @@ class InvoiceFiles {
|
|
|
1122
1190
|
this.budget.details -= 1;
|
|
1123
1191
|
const connected = await this.api.supplierInvoiceFiles(entry.givenNumber);
|
|
1124
1192
|
const key = filesLandedKey(this.scopeId, entry.givenNumber);
|
|
1125
|
-
const held = (await this.
|
|
1193
|
+
const held = (await this.conn.state.get(key));
|
|
1126
1194
|
const sameEntity = held?.entity.entityType === entry.entity.entityType && held.entity.entityId === entry.entity.entityId;
|
|
1127
1195
|
let landed = sameEntity ? held.fileIds : [];
|
|
1128
1196
|
for (const file of connected) {
|
|
@@ -1133,7 +1201,7 @@ class InvoiceFiles {
|
|
|
1133
1201
|
this.budget.details -= 1;
|
|
1134
1202
|
await this.land(entry, file);
|
|
1135
1203
|
landed = [...landed, file.FileId];
|
|
1136
|
-
await this.
|
|
1204
|
+
await this.conn.state.put(key, { entity: entry.entity, fileIds: landed });
|
|
1137
1205
|
}
|
|
1138
1206
|
return true;
|
|
1139
1207
|
}
|
|
@@ -1153,7 +1221,7 @@ class InvoiceFiles {
|
|
|
1153
1221
|
this.skipped.push({ givenNumber: entry.givenNumber, reason: `${name} is ${read.tooLarge} bytes, over ${INVOICE_FILE_MAX_BYTES}` });
|
|
1154
1222
|
return;
|
|
1155
1223
|
}
|
|
1156
|
-
this.attachments ??= await this.
|
|
1224
|
+
this.attachments ??= await this.conn.attachments(this.scopeRef);
|
|
1157
1225
|
await this.attachments.upload({
|
|
1158
1226
|
entity: entry.entity,
|
|
1159
1227
|
filename: name,
|
|
@@ -1212,14 +1280,14 @@ const leaseKey = (scope) => `fortnox:lease:${scope}`;
|
|
|
1212
1280
|
* compare-and-set, so the take is a write and a read back of its token, and two takers that
|
|
1213
1281
|
* interleave within those few milliseconds can both hold it.
|
|
1214
1282
|
*/
|
|
1215
|
-
async function takePollLease(
|
|
1283
|
+
async function takePollLease(state, scopeId, nowMs) {
|
|
1216
1284
|
const key = leaseKey(scopeId);
|
|
1217
|
-
const held = (await
|
|
1285
|
+
const held = (await state.get(key));
|
|
1218
1286
|
if (held && Date.parse(held.until) > nowMs)
|
|
1219
1287
|
return null;
|
|
1220
1288
|
const token = ulid();
|
|
1221
|
-
await
|
|
1222
|
-
const after = (await
|
|
1289
|
+
await state.put(key, { token, until: new Date(nowMs + POLL_LEASE_MS).toISOString() });
|
|
1290
|
+
const after = (await state.get(key));
|
|
1223
1291
|
return after?.token === token ? token : null;
|
|
1224
1292
|
}
|
|
1225
1293
|
/**
|
|
@@ -1228,12 +1296,12 @@ async function takePollLease(host, connectionId, scopeId, nowMs) {
|
|
|
1228
1296
|
* left alone. A body read is not a boundary: one that streams longer than the lease can outlive it.
|
|
1229
1297
|
* Best effort, as the release: a renewal that fails leaves the lease to expire, never the request.
|
|
1230
1298
|
*/
|
|
1231
|
-
function leaseRenewing(
|
|
1299
|
+
function leaseRenewing(state, scopeId, token, fetch, now) {
|
|
1232
1300
|
let renewedAt = now();
|
|
1233
1301
|
const renew = async (at) => {
|
|
1234
|
-
const held = (await
|
|
1302
|
+
const held = (await state.get(leaseKey(scopeId)));
|
|
1235
1303
|
if (held?.token === token)
|
|
1236
|
-
await
|
|
1304
|
+
await state.put(leaseKey(scopeId), { token, until: new Date(at + POLL_LEASE_MS).toISOString() });
|
|
1237
1305
|
};
|
|
1238
1306
|
return async (input, init) => {
|
|
1239
1307
|
if (now() - renewedAt >= POLL_LEASE_MS / 3) {
|
|
@@ -1244,15 +1312,15 @@ function leaseRenewing(host, connectionId, scopeId, token, fetch, now) {
|
|
|
1244
1312
|
};
|
|
1245
1313
|
}
|
|
1246
1314
|
/** Give the lease back, unless it expired and another poll took it over. */
|
|
1247
|
-
async function releasePollLease(
|
|
1315
|
+
async function releasePollLease(state, scopeId, token) {
|
|
1248
1316
|
const key = leaseKey(scopeId);
|
|
1249
|
-
const held = (await
|
|
1317
|
+
const held = (await state.get(key));
|
|
1250
1318
|
if (held?.token === token)
|
|
1251
|
-
await
|
|
1319
|
+
await state.put(key, null);
|
|
1252
1320
|
}
|
|
1253
1321
|
/**
|
|
1254
|
-
* Poll Fortnox for every scope this connection is bound to — the
|
|
1255
|
-
*
|
|
1322
|
+
* Poll Fortnox for every scope this connection is bound to — what the platform's sweeper runs
|
|
1323
|
+
* for each connection, handed its door (#3377). A ledger binding syncs its year of books
|
|
1256
1324
|
* ({@link syncFortnoxScope}); an invoice binding lands the supplier invoices changed since its
|
|
1257
1325
|
* cursor ({@link syncFortnoxSupplierInvoices}). The name predates invoices and is kept.
|
|
1258
1326
|
*
|
|
@@ -1264,8 +1332,10 @@ async function releasePollLease(host, connectionId, scopeId, token) {
|
|
|
1264
1332
|
* anything, and a failure on one scope is recorded and stepped over rather than sinking
|
|
1265
1333
|
* the pass — one vertical's missing grant must not stop another tenant's books syncing.
|
|
1266
1334
|
*/
|
|
1267
|
-
export async function sweepFortnoxLedger(
|
|
1268
|
-
const
|
|
1335
|
+
export async function sweepFortnoxLedger(door, options) {
|
|
1336
|
+
const connectionId = door.connectionId;
|
|
1337
|
+
const state = door.state;
|
|
1338
|
+
const rows = await state.list(options.scopeId === undefined ? BINDING_PREFIX : bindingKey(options.scopeId));
|
|
1269
1339
|
const result = { found: 0, synced: [], invoices: [], unchanged: 0, failed: [], busy: [] };
|
|
1270
1340
|
// One budget and one rate window per pass: every binding on this connection reads the same company.
|
|
1271
1341
|
const budget = { details: INVOICE_DETAILS_PER_PASS };
|
|
@@ -1288,14 +1358,22 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
|
|
|
1288
1358
|
}
|
|
1289
1359
|
let lease = null;
|
|
1290
1360
|
try {
|
|
1291
|
-
lease = await takePollLease(
|
|
1361
|
+
lease = await takePollLease(state, binding.scopeId, clock());
|
|
1292
1362
|
if (lease === null) {
|
|
1293
1363
|
result.busy.push(binding.scopeId);
|
|
1294
1364
|
continue;
|
|
1295
1365
|
}
|
|
1296
|
-
|
|
1366
|
+
// The company the binding records (#2316) and its owner (#3410); the door opens only this
|
|
1367
|
+
// connection there, so the credential that reads and the identity that lands are one.
|
|
1368
|
+
const opened = await door.open({
|
|
1369
|
+
tenantId: binding.tenantId,
|
|
1370
|
+
vertical: binding.vertical,
|
|
1371
|
+
externalAccountRef: binding.externalAccountRef ?? null,
|
|
1372
|
+
ownerScopeId: ownerOf(connectionId, binding),
|
|
1373
|
+
});
|
|
1374
|
+
const leased = { ...opened, fetch: leaseRenewing(state, binding.scopeId, lease, opened.fetch, clock) };
|
|
1297
1375
|
if (binding.kind === 'supplier-invoice') {
|
|
1298
|
-
const r = await syncFortnoxSupplierInvoices(
|
|
1376
|
+
const r = await syncFortnoxSupplierInvoices(leased, binding, { ...pass, budget });
|
|
1299
1377
|
if (r.landed > 0 || r.files > 0 || r.held > 0 || r.written > 0 || r.skipped || r.pending)
|
|
1300
1378
|
result.invoices.push(r);
|
|
1301
1379
|
else
|
|
@@ -1303,7 +1381,7 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
|
|
|
1303
1381
|
continue;
|
|
1304
1382
|
}
|
|
1305
1383
|
if (binding.form === 'sie') {
|
|
1306
|
-
const { synced, failed } = await syncFortnoxSieFiles(
|
|
1384
|
+
const { synced, failed } = await syncFortnoxSieFiles(leased, binding, pass);
|
|
1307
1385
|
const landed = synced.filter((r) => r.changed);
|
|
1308
1386
|
result.synced.push(...landed);
|
|
1309
1387
|
for (const f of failed) {
|
|
@@ -1316,7 +1394,7 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
|
|
|
1316
1394
|
result.unchanged += 1;
|
|
1317
1395
|
continue;
|
|
1318
1396
|
}
|
|
1319
|
-
const r = await syncFortnoxScope(
|
|
1397
|
+
const r = await syncFortnoxScope(leased, binding, pass);
|
|
1320
1398
|
if (r.changed)
|
|
1321
1399
|
result.synced.push(r);
|
|
1322
1400
|
else
|
|
@@ -1326,13 +1404,13 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
|
|
|
1326
1404
|
result.failed.push({
|
|
1327
1405
|
scopeId: binding.scopeId,
|
|
1328
1406
|
error: err instanceof Error ? err.message : String(err),
|
|
1329
|
-
...(err instanceof
|
|
1407
|
+
...(err instanceof FortnoxSaidFailure ? { said: err.said } : {}),
|
|
1330
1408
|
});
|
|
1331
1409
|
}
|
|
1332
1410
|
finally {
|
|
1333
1411
|
// A release that fails leaves the lease to expire.
|
|
1334
1412
|
if (lease !== null)
|
|
1335
|
-
await releasePollLease(
|
|
1413
|
+
await releasePollLease(state, binding.scopeId, lease).catch(() => undefined);
|
|
1336
1414
|
}
|
|
1337
1415
|
}
|
|
1338
1416
|
return result;
|
|
@@ -1341,8 +1419,8 @@ export async function sweepFortnoxLedger(host, connectionId, options) {
|
|
|
1341
1419
|
* Poll ONE scope's bindings now — {@link sweepFortnoxLedger} narrowed to the scope, so the same
|
|
1342
1420
|
* budget, deadline and rate window bound it as bound a pass.
|
|
1343
1421
|
*/
|
|
1344
|
-
export async function pollFortnoxScope(
|
|
1345
|
-
const r = await sweepFortnoxLedger(
|
|
1422
|
+
export async function pollFortnoxScope(door, scopeId, options) {
|
|
1423
|
+
const r = await sweepFortnoxLedger(door, { ...options, scopeId });
|
|
1346
1424
|
const pending = r.invoices.some((i) => i.pending);
|
|
1347
1425
|
if (r.failed.length > 0) {
|
|
1348
1426
|
const said = r.failed.flatMap((f) => (f.said ? [f.said] : []));
|
|
@@ -1384,25 +1462,24 @@ export async function probeFortnoxSecret(secret, options) {
|
|
|
1384
1462
|
};
|
|
1385
1463
|
}
|
|
1386
1464
|
const timeoutMs = options.timeoutMs ?? 15_000;
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
secret: parsed.data,
|
|
1393
|
-
// Probe stub, not where expiry is set. Fortnox mints 1h access tokens via client_credentials and has NO refresh token (api.ts); recording the access token expiry here would warn on every row. See connections.md §3.6.
|
|
1394
|
-
expiresAt: null,
|
|
1395
|
-
fetch: deadlineFetch(options.fetch, timeoutMs),
|
|
1396
|
-
};
|
|
1397
|
-
return probeWith(conn, options);
|
|
1465
|
+
// No row yet, so no connection is named; a candidate's failure is not a fact about a live one.
|
|
1466
|
+
// Not where expiry is set either: Fortnox mints 1h access tokens via client_credentials and has
|
|
1467
|
+
// NO refresh token (api.ts); recording the access token expiry would warn on every row. See
|
|
1468
|
+
// connections.md §3.6.
|
|
1469
|
+
return probeWith(apiConnection({ secret: parsed.data, fetch: deadlineFetch(options.fetch, timeoutMs) }), options);
|
|
1398
1470
|
}
|
|
1399
|
-
/**
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1471
|
+
/**
|
|
1472
|
+
* Probe the credential a live connection already holds. Verifying is itself a use: `conn.fetch` is
|
|
1473
|
+
* the platform's, bounded and recorded against the connection.
|
|
1474
|
+
*
|
|
1475
|
+
* The answer names what the consent covers (`consent`). A probe a person asked for is a fresh check,
|
|
1476
|
+
* so the platform records it whenever there is one, rewriting what the console reads: over the call
|
|
1477
|
+
* contract the probe answers it as a write of the connection's state ({@link runFortnoxCall}).
|
|
1478
|
+
*/
|
|
1479
|
+
export async function probeFortnoxConnection(conn, options) {
|
|
1480
|
+
return probeWith(apiConnection(conn), options);
|
|
1404
1481
|
}
|
|
1405
|
-
async function probeWith(conn, options
|
|
1482
|
+
async function probeWith(conn, options) {
|
|
1406
1483
|
const api = new FortnoxApi(conn, {
|
|
1407
1484
|
apiBase: options.apiBase,
|
|
1408
1485
|
oauthBase: options.oauthBase,
|
|
@@ -1413,8 +1490,6 @@ async function probeWith(conn, options, record) {
|
|
|
1413
1490
|
// The mint first: it proves the client pair and the consent, and names what the consent
|
|
1414
1491
|
// covers (#2422). A read outside that set would answer 403, which is not a refused key.
|
|
1415
1492
|
consent = await fortnoxConsentOf(api, options.consentScopes ?? FORTNOX_CONSENT_SCOPES, new Date(options.now?.() ?? Date.now()).toISOString());
|
|
1416
|
-
if (consent && record)
|
|
1417
|
-
await record(consent);
|
|
1418
1493
|
const consentFact = consent
|
|
1419
1494
|
? {
|
|
1420
1495
|
label: 'Consent',
|
|
@@ -1485,8 +1560,8 @@ async function probeWith(conn, options, record) {
|
|
|
1485
1560
|
* synced", which is the question an operator asks when a figure looks stale, and it
|
|
1486
1561
|
* answers it without spending a provider round trip.
|
|
1487
1562
|
*/
|
|
1488
|
-
export async function fortnoxConnectionActivity(
|
|
1489
|
-
const rows = await
|
|
1563
|
+
export async function fortnoxConnectionActivity(state) {
|
|
1564
|
+
const rows = await state.list(BINDING_PREFIX);
|
|
1490
1565
|
const entries = rows
|
|
1491
1566
|
.filter(({ value }) => value !== null && typeof value === 'object')
|
|
1492
1567
|
.map(({ key, value }) => {
|
|
@@ -1516,7 +1591,7 @@ export async function fortnoxConnectionActivity(host, connectionId) {
|
|
|
1516
1591
|
],
|
|
1517
1592
|
};
|
|
1518
1593
|
});
|
|
1519
|
-
const consent = await readFortnoxConsent(
|
|
1594
|
+
const consent = await readFortnoxConsent(state);
|
|
1520
1595
|
return connectionActivity.parse({
|
|
1521
1596
|
source: 'ledger',
|
|
1522
1597
|
entries,
|
|
@@ -1536,14 +1611,10 @@ export async function fortnoxConnectionActivity(host, connectionId) {
|
|
|
1536
1611
|
* identifier, not a secret — and it is the field an operator most needs to read when a
|
|
1537
1612
|
* connection syncs the wrong company's books.
|
|
1538
1613
|
*/
|
|
1539
|
-
export
|
|
1540
|
-
// #2316: this company's connection, not whichever one (tenant, vertical) would
|
|
1541
|
-
// scope's own (#3410) only when the row says so.
|
|
1542
|
-
const
|
|
1543
|
-
if (!open) {
|
|
1544
|
-
throw new Error(`no live 'fortnox' connection for tenant ${connection.tenantId} / vertical '${connection.vertical}'`);
|
|
1545
|
-
}
|
|
1546
|
-
const secret = fortnoxSecret.parse(open.secret);
|
|
1614
|
+
export function fortnoxCredentialSummary(storedSecret) {
|
|
1615
|
+
// #2316: the platform opens this company's connection, not whichever one (tenant, vertical) would
|
|
1616
|
+
// pick; and a scope's own (#3410) only when the row says so. The connector reads the credential.
|
|
1617
|
+
const secret = fortnoxSecret.parse(storedSecret);
|
|
1547
1618
|
return {
|
|
1548
1619
|
fields: [
|
|
1549
1620
|
{ key: 'clientId', label: 'Client ID', value: secret.clientId, masked: false },
|
|
@@ -1564,45 +1635,4 @@ function ownerOf(connectionId, binding) {
|
|
|
1564
1635
|
}
|
|
1565
1636
|
return binding.ownerScopeId ?? null;
|
|
1566
1637
|
}
|
|
1567
|
-
/**
|
|
1568
|
-
* Open the live Fortnox connection for a (tenant, vertical) — and, with several companies
|
|
1569
|
-
* connected, the one `account.externalAccountRef` names (#2316) — with health recorded.
|
|
1570
|
-
*
|
|
1571
|
-
* `account.expected` is the connection a binding names. The credential that reads and the
|
|
1572
|
-
* identity that writes must be the same connection, so a mismatch is refused loudly rather than
|
|
1573
|
-
* landing one company's books as another's connection — Planima's backstop, which here guards a
|
|
1574
|
-
* reachable case: a binding written before it recorded the account, once a second company exists.
|
|
1575
|
-
*/
|
|
1576
|
-
async function openFortnoxConnection(admin, fetchImpl, tenant, vertical, timeoutMs, account = {}) {
|
|
1577
|
-
const parsedTenant = tenantIdSchema.parse(tenant);
|
|
1578
|
-
// `owner` opens a scope's OWN connection (#3410); without it only the tenant's is ever opened.
|
|
1579
|
-
const owner = account.owner ? scopeIdSchema.parse(account.owner) : undefined;
|
|
1580
|
-
const open = await admin.openConnection(parsedTenant, vertical, 'fortnox', account.externalAccountRef ?? undefined, owner);
|
|
1581
|
-
if (!open) {
|
|
1582
|
-
throw new Error(`no live 'fortnox' connection for tenant ${tenant} / vertical '${vertical}'` +
|
|
1583
|
-
(account.externalAccountRef ? ` and company ${account.externalAccountRef}` : ''));
|
|
1584
|
-
}
|
|
1585
|
-
if (account.expected !== undefined && open.id !== account.expected) {
|
|
1586
|
-
throw new Error(`binding names connection ${account.expected}, but the live 'fortnox' connection opened for tenant ` +
|
|
1587
|
-
`${tenant} / vertical '${vertical}' is ${open.id} — the credential that reads and the identity ` +
|
|
1588
|
-
`that writes must be the same connection. Re-bind the scope against ${account.expected}.`);
|
|
1589
|
-
}
|
|
1590
|
-
const bounded = deadlineFetch(fetchImpl, timeoutMs);
|
|
1591
|
-
return {
|
|
1592
|
-
...open,
|
|
1593
|
-
fetch: async (input, init) => {
|
|
1594
|
-
// #1691: timed, so the host's per-call data point carries a duration.
|
|
1595
|
-
const started = Date.now();
|
|
1596
|
-
try {
|
|
1597
|
-
const res = await bounded(input, init);
|
|
1598
|
-
await admin.recordConnectionUse(open.id, settleConnectionUse('fortnox', Date.now() - started, { response: res }));
|
|
1599
|
-
return res;
|
|
1600
|
-
}
|
|
1601
|
-
catch (err) {
|
|
1602
|
-
await admin.recordConnectionUse(open.id, settleConnectionUse('fortnox', Date.now() - started, { error: err }));
|
|
1603
|
-
throw err;
|
|
1604
|
-
}
|
|
1605
|
-
},
|
|
1606
|
-
};
|
|
1607
|
-
}
|
|
1608
1638
|
//# sourceMappingURL=index.js.map
|