@happyvertical/smrt-commerce 0.62.4 → 0.62.6

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.
Files changed (74) hide show
  1. package/AGENTS.md +1 -0
  2. package/agents/accounting-connection.md +76 -0
  3. package/agents/accounting-live-gate.md +40 -0
  4. package/agents/accounting-mapping.md +60 -0
  5. package/agents/accounting-payment-sync.md +76 -0
  6. package/agents/ordinary-accounting.md +3 -0
  7. package/dist/accounting-connection.d.ts +179 -0
  8. package/dist/accounting-connection.d.ts.map +1 -0
  9. package/dist/accounting-live-gate.d.ts +50 -0
  10. package/dist/accounting-live-gate.d.ts.map +1 -0
  11. package/dist/accounting-mapping.d.ts +189 -0
  12. package/dist/accounting-mapping.d.ts.map +1 -0
  13. package/dist/accounting-payment-sync.d.ts +233 -0
  14. package/dist/accounting-payment-sync.d.ts.map +1 -0
  15. package/dist/chunks/{InvoiceCollection-Cc-fJrHy.js → InvoiceCollection-xooQnUwq.js} +10 -10
  16. package/dist/chunks/{InvoiceCollection-Cc-fJrHy.js.map → InvoiceCollection-xooQnUwq.js.map} +1 -1
  17. package/dist/chunks/{allocation-integrity-CvXQm3wK.js → allocation-integrity-C4SZJcao.js} +6 -6
  18. package/dist/chunks/{allocation-integrity-CvXQm3wK.js.map → allocation-integrity-C4SZJcao.js.map} +1 -1
  19. package/dist/chunks/{contract-money-BoKHNfV6.js → contract-money-ATacxU6t.js} +4 -7
  20. package/dist/chunks/{contract-money-BoKHNfV6.js.map → contract-money-ATacxU6t.js.map} +1 -1
  21. package/dist/chunks/{invoice-posting-DlR_-TG1.js → invoice-posting-CDfxug3Q.js} +4 -5
  22. package/dist/chunks/{invoice-posting-DlR_-TG1.js.map → invoice-posting-CDfxug3Q.js.map} +1 -1
  23. package/dist/chunks/retention-accounting-BA4wXUQc.js +8710 -0
  24. package/dist/chunks/retention-accounting-BA4wXUQc.js.map +1 -0
  25. package/dist/chunks/{tenant-money-barrier-Bmu4YiID.js → tenant-money-barrier-BdyXIVT5.js} +3 -3
  26. package/dist/chunks/{tenant-money-barrier-Bmu4YiID.js.map → tenant-money-barrier-BdyXIVT5.js.map} +1 -1
  27. package/dist/collections/AccountingConnectionCollection.d.ts +27 -0
  28. package/dist/collections/AccountingConnectionCollection.d.ts.map +1 -0
  29. package/dist/collections/AccountingMappingCollection.d.ts +24 -0
  30. package/dist/collections/AccountingMappingCollection.d.ts.map +1 -0
  31. package/dist/collections/AccountingSyncRecordCollections.d.ts +27 -0
  32. package/dist/collections/AccountingSyncRecordCollections.d.ts.map +1 -0
  33. package/dist/collections/index.d.ts +3 -0
  34. package/dist/collections/index.d.ts.map +1 -1
  35. package/dist/index.d.ts +10 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1532 -21
  38. package/dist/index.js.map +1 -1
  39. package/dist/invoice-accounting-sync.d.ts +6 -0
  40. package/dist/invoice-accounting-sync.d.ts.map +1 -1
  41. package/dist/invoices.js +1 -1
  42. package/dist/manifest.json +6303 -3740
  43. package/dist/models/AccountingConnection.d.ts +101 -0
  44. package/dist/models/AccountingConnection.d.ts.map +1 -0
  45. package/dist/models/AccountingMapping.d.ts +85 -0
  46. package/dist/models/AccountingMapping.d.ts.map +1 -0
  47. package/dist/models/AccountingSyncRecords.d.ts +95 -0
  48. package/dist/models/AccountingSyncRecords.d.ts.map +1 -0
  49. package/dist/models/index.d.ts +3 -0
  50. package/dist/models/index.d.ts.map +1 -1
  51. package/dist/ordinary-accounting.d.ts +1 -0
  52. package/dist/ordinary-accounting.d.ts.map +1 -1
  53. package/dist/recipes.d.ts +1 -1
  54. package/dist/retention-accounting.d.ts +1 -0
  55. package/dist/retention-accounting.d.ts.map +1 -1
  56. package/dist/smrt-knowledge.json +1327 -99
  57. package/dist/smrt-knowledge.okf.md +55 -23
  58. package/package.json +15 -15
  59. package/dist/chunks/ContractLineItemCollection-BKHy-nR8.js +0 -260
  60. package/dist/chunks/ContractLineItemCollection-BKHy-nR8.js.map +0 -1
  61. package/dist/chunks/DocumentTaxCollection-BRebznXF.js +0 -4649
  62. package/dist/chunks/DocumentTaxCollection-BRebznXF.js.map +0 -1
  63. package/dist/chunks/TaxCodeCollection-BBqCugs5.js +0 -155
  64. package/dist/chunks/TaxCodeCollection-BBqCugs5.js.map +0 -1
  65. package/dist/chunks/TaxComponentCollection-BHJjbQxq.js +0 -134
  66. package/dist/chunks/TaxComponentCollection-BHJjbQxq.js.map +0 -1
  67. package/dist/chunks/credit-allocation-yspz0Lab.js +0 -121
  68. package/dist/chunks/credit-allocation-yspz0Lab.js.map +0 -1
  69. package/dist/chunks/retention-accounting-D0KzSw3f.js +0 -3069
  70. package/dist/chunks/retention-accounting-D0KzSw3f.js.map +0 -1
  71. package/dist/chunks/retention-accounting-internal-DNxLLVvK.js +0 -30
  72. package/dist/chunks/retention-accounting-internal-DNxLLVvK.js.map +0 -1
  73. package/dist/chunks/units-8ElbjVZK.js +0 -60
  74. package/dist/chunks/units-8ElbjVZK.js.map +0 -1
package/AGENTS.md CHANGED
@@ -32,6 +32,7 @@ recipes show carry `@field({ description })` text; keep both in plain
32
32
  language for end users and update them when a recipe's fields change. See
33
33
  [core recipes](../core/agents/recipes.md).
34
34
 
35
+ QuickBooks for tenants (#5136-#5139): [connection](agents/accounting-connection.md), [mappings](agents/accounting-mapping.md), [live gate](agents/accounting-live-gate.md), [payment sync](agents/accounting-payment-sync.md).
35
36
  See [historical issued sales](agents/historical-sales.md) for exact original source
36
37
  money, immutable source children and combined historical/live customer funds.
37
38
  See [payment allocation integrity](agents/payment-allocations.md) for atomic splits,
@@ -0,0 +1,76 @@
1
+ # Tenant accounting connection (#5136)
2
+
3
+ A tenant connects one QuickBooks Online company. Source:
4
+ `src/accounting-connection.ts`, `src/models/AccountingConnection.ts`.
5
+
6
+ ## Why smrt-commerce
7
+
8
+ Commerce already owns accounting sync (`syncFrozenInvoiceToAccounting`), depends
9
+ on `@happyvertical/accounting`, and takes smrt-secrets through a structural port
10
+ (`ConnectedPaymentSecretReader` precedent), so the connection, its mappings
11
+ (#5137) and the live-mode gate (#5138) share one tenant/realm/environment scope
12
+ without a new package or a dependency cycle. Commerce does not import
13
+ `@happyvertical/smrt-secrets`; the app passes a `SecretService`
14
+ (`AccountingSecretStore`: `storeForTenant`, `retrieveForTenant`,
15
+ `deleteForTenant`).
16
+
17
+ ## Model
18
+
19
+ `AccountingConnection { tenantId, provider, realmId, environment, status,
20
+ lastError, lastErrorAt, connectedBy, connectedAt, disconnectedAt, tokenVersion,
21
+ lastRefreshedAt, leaseToken, leaseExpiresAt }`, unique on `(tenantId,
22
+ provider)`. Tenant-level: no user owns it. Status `connected`, `needs_reconnect`
23
+ or `disconnected`. The refresh token is only in smrt-secrets
24
+ (`accounting-quickbooks-refresh-token`, category `accounting.quickbooks`); the
25
+ row holds a version counter, never token material. `lastError` is a code
26
+ (`REAUTH_REQUIRED`), never provider text. Read-only generated surface; `save()`
27
+ refuses writes outside the commands; never deleted (it owns sync history).
28
+
29
+ ## Commands
30
+
31
+ | Command | Does |
32
+ |---|---|
33
+ | `completeQuickBooksConnection(deps, { tenantId, realmId, environment, tokens, connectedBy })` | The completion hook for the shared OAuth connect flow (smrt#5128): the callback supplies `realmId`, environment and the exchanged tokens. Stores the refresh token, rebinds the tenant's row to `connected`, clears errors. Reconnecting reuses the row (the company may change). |
34
+ | `withTenantQuickBooksProvider(config, tenantId, fn)` | Ready provider for the tenant's connection; apps never handle tokens. |
35
+ | `disconnectQuickBooks(deps, { tenantId, oauth })` | Revoke at Intuit, delete the secret, mark `disconnected`; row and history stay. Idempotent. A failed revoke throws `REVOKE_FAILED` and changes nothing. |
36
+ | `getAccountingConnection(deps, tenantId)` | Read the row. |
37
+
38
+ Errors are `AccountingConnectionError` with `code` `INVALID_INPUT`,
39
+ `NOT_CONNECTED`, `NEEDS_RECONNECT`, `LEASE_TIMEOUT` or `REVOKE_FAILED`.
40
+
41
+ ## Serialized rotation
42
+
43
+ Intuit rotates the refresh token on every refresh and a fresh `QuickBooksProvider`
44
+ has no access token, so it refreshes on first use: two concurrent users of the
45
+ stored token lose one. Locking only in `onTokenRefresh` would be too late (the
46
+ refresh already happened). Instead the whole first refresh runs under a
47
+ per-connection **lease** (`leaseToken`/`leaseExpiresAt`): a conditional
48
+ `UPDATE ... RETURNING` (SQLite and PostgreSQL), never a transaction held across
49
+ the Intuit call or the secret write. Waiters poll up to `waitMs`, then throw
50
+ `LEASE_TIMEOUT`. Inside the lease the stored token is read, the provider is
51
+ created with `onTokenRefresh` persisting the rotated token (before the lease is
52
+ released), and `ensureAccessToken()` is called; `fn` then runs on the fresh
53
+ provider outside the lease. `completeQuickBooksConnection` and
54
+ `disconnectQuickBooks` take the same lease, so an in-flight refresh cannot
55
+ overwrite a fresh connect or resurrect a deleted secret.
56
+
57
+ A rejected grant (sdk#1541 `AccountingReauthRequiredError`, detected
58
+ structurally as `code === 'REAUTH_REQUIRED'`, or raw `invalid_grant`) is
59
+ re-checked: if the stored token changed meanwhile it retries once, otherwise the
60
+ connection becomes `needs_reconnect` and callers get `NEEDS_RECONNECT` without
61
+ further provider calls, until `completeQuickBooksConnection` runs again.
62
+
63
+ ## SDK seams
64
+
65
+ - `@happyvertical/accounting` sdk#1541: `AccountingReauthRequiredError`
66
+ (`code: 'REAUTH_REQUIRED'`) and `QuickBooksOAuthClient.refresh`. smrt matches
67
+ the error structurally and only needs `revoke` from the OAuth client.
68
+ - A provider that accepts a seeded access token and expiry would avoid the
69
+ refresh-per-provider; today every new provider refreshes once, which the lease
70
+ covers. A later refresh by a long-lived provider (after about 55 minutes)
71
+ persists through `onTokenRefresh` but is not leased: build providers per job.
72
+
73
+ ## Live mode
74
+
75
+ `enableLiveAccounting` / `disableLiveAccounting` set the per-company production
76
+ enablement the sync functions check; see [live-mode gate](accounting-live-gate.md).
@@ -0,0 +1,40 @@
1
+ # Live-mode gate on accounting sync (#5138)
2
+
3
+ Source: `src/accounting-live-gate.ts`, `enableLiveAccounting` /
4
+ `disableLiveAccounting` in `src/accounting-connection.ts`.
5
+
6
+ `runQuickBooksPilot` refuses anything but a fixture sandbox, but the frozen
7
+ invoice, credit and refund sync accepted any provider with
8
+ `environment: 'production'`. They no longer do without a deliberate enablement.
9
+
10
+ ## Rule
11
+
12
+ A write is **production** when any of the caller's mapping scope, the provider's
13
+ own `environment`, or the environment the document is already synced under says
14
+ so. They must agree (`ACCOUNTING_ENVIRONMENT_MISMATCH` otherwise, so a
15
+ sandbox-labelled mapping cannot reach a production provider). A production write
16
+ needs, on the tenant's `AccountingConnection`:
17
+
18
+ 1. `status === 'connected'` and `environment === 'production'`;
19
+ 2. `liveEnabledRealmId === realmId`, set by
20
+ `enableLiveAccounting({ tenantId, realmId, enabledBy, evidenceRef })`, which
21
+ itself refuses unless the connected production company is that realm.
22
+
23
+ Otherwise `AccountingLiveGateError` (`LIVE_ACCOUNTING_NOT_ENABLED`) is thrown
24
+ **before** any state is reserved or provider called, so state is unchanged.
25
+ Sandbox needs no enablement and no connection (it stays the default).
26
+
27
+ Enablement is per company: reconnecting to another realm or environment, or
28
+ disconnecting, clears it; `disableLiveAccounting` switches it off. The app owns
29
+ who may call `enableLiveAccounting` and when (Work reserves it for the owner);
30
+ commerce only refuses writes without it.
31
+
32
+ ## Where it is checked
33
+
34
+ `assertAccountingWriteAllowed` runs first in `syncFrozenInvoiceToAccounting`
35
+ (invoice and credit memo), `syncOrdinaryInvoiceToAccounting`,
36
+ `syncOrdinaryCreditToAccounting`, `syncOrdinaryRefundToAccounting`,
37
+ `syncRetainedInvoiceToAccounting`, `releaseRetainedInvoiceToAccounting`,
38
+ `syncRetainedCreditToAccounting`, `syncRetainedRefundToAccounting`, and the
39
+ payment sync (#5139). Reconcile and read paths do not write remotely and are
40
+ not gated. The fixture pilot stays sandbox-only.
@@ -0,0 +1,60 @@
1
+ # Accounting mappings (#5137)
2
+
3
+ Source: `src/accounting-mapping.ts`, `src/models/AccountingMapping.ts`. Replaces
4
+ the flat `Invoice.customerExternalId` and the hand-built
5
+ `FrozenQuickBooksTaxMapping`.
6
+
7
+ ## Model
8
+
9
+ `AccountingMapping { tenantId, provider, realmId, environment, kind, localId,
10
+ externalId, externalName, detailsJson, status, confirmedBy, confirmedAt,
11
+ invalidatedAt }`, unique on `(tenantId, provider, realmId, environment, kind,
12
+ localId)`. Read-only generated surface; written only by the commands.
13
+
14
+ | `kind` | `localId` | `externalId` |
15
+ |---|---|---|
16
+ | `customer` | commerce `Customer` id | provider customer id |
17
+ | `tax_code` | commerce `TaxCode` id, or `none` for untaxed lines | provider TaxCode id; `details.taxComponents` holds the ordered provider rates for compound tax |
18
+ | `tax_component` | commerce `TaxComponent` id | provider tax rate id |
19
+ | `item` | `default` or `sku:<sku>` (sku wins) | provider product/service item |
20
+ | `deposit_account` | `default` | provider clearing/deposit account (used by payment sync, #5139) |
21
+
22
+ `realmId` and `environment` are in the key, so another company or the other
23
+ environment never sees these rows. `completeQuickBooksConnection` also marks the
24
+ tenant's mappings of the previous company/environment `invalidated` (kept for
25
+ history, never used); `setAccountingMapping` reactivates a row.
26
+
27
+ ## Commands
28
+
29
+ - `setAccountingMapping` / `removeAccountingMapping` / `getAccountingMapping` /
30
+ `listAccountingMappings` (scope = `getAccountingMappingScope(db, tenantId)`,
31
+ the connected company).
32
+ - `buildFrozenInvoiceMapping({ db, tenantId, invoiceId })` returns a
33
+ `QuickBooksFrozenInvoiceMapping` (realm, environment, `lines`, `components`,
34
+ `customerRef`) from the records, so sync callers pass only the tenant and the
35
+ document. Missing mappings throw `AccountingMappingError('MAPPING_INCOMPLETE')`
36
+ with every missing `{ kind, localId }`, never a guess. `customerRef` replaces
37
+ the flat invoice field in the sync (`mapping.customerRef`).
38
+ - Customer resolution: `resolveAccountingCustomer` then, if needed,
39
+ `confirmAccountingCustomer`.
40
+
41
+ ## Customer resolution
42
+
43
+ 1. An active mapping wins; the provider is not called.
44
+ 2. Otherwise `directory.find({ name, email })`. Exactly one match that agrees on
45
+ email (or, without an email, on name) is linked and recorded.
46
+ 3. Several matches, or one that agrees on neither, return
47
+ `needs_confirmation` with the candidates and change nothing. The operator
48
+ calls `confirmAccountingCustomer` with a candidate (re-checked against the
49
+ provider) or `'create'` on purpose.
50
+ 4. No match: `directory.create` with a stable `requestId` per
51
+ (customer, realm, environment), then record the mapping. A crash between
52
+ create and record is healed by step 2 (the next lookup finds it).
53
+
54
+ ## SDK seam (sdk#1539)
55
+
56
+ `AccountingCustomerDirectory` (`find`, `create`) is the port; the host adapts
57
+ the SDK's customer find / find-or-create to it. smrt tests use fakes.
58
+
59
+ Optional Svelte pickers are not included; the provider lists they need come from
60
+ the host (`directory`-style ports), and Work owns that presentation.
@@ -0,0 +1,76 @@
1
+ # Payment sync, readback and batches (#5139)
2
+
3
+ Source: `src/accounting-payment-sync.ts`, `src/models/AccountingSyncRecords.ts`.
4
+
5
+ ## Payment push
6
+
7
+ `syncPaymentToAccounting({ db, tenantId, paymentId, payments, provider? })` (run
8
+ inside the tenant context) pushes one recorded payment to the connected company,
9
+ applied to its synced invoice(s) and deposited to the mapped clearing account
10
+ (`deposit_account:default`). It requires:
11
+
12
+ - a `completed`, non-refund `Payment` fully applied (`PaymentAllocation`s sum to
13
+ the amount) to invoices that are **synced to the same company and
14
+ environment** (`INVOICE_NOT_SYNCED` otherwise), one customer, one currency;
15
+ - the `customer` and `deposit_account:default` mappings (`MAPPING_INCOMPLETE`
16
+ lists what is missing);
17
+ - live mode in production (see [live-mode gate](accounting-live-gate.md)).
18
+
19
+ Exactly once, same shape as the invoice path: `AccountingPaymentSync` is unique
20
+ per `(tenant, provider, realm, environment, payment)`. The request id
21
+ (`smrt_pay_<hash of the exact facts>`) and the request JSON are persisted as
22
+ `in_flight` **before** the provider call. A definite rejection
23
+ (`error.outcome === 'rejected'`) or a dead grant (`REAUTH_REQUIRED`: nothing was
24
+ sent) becomes `rejected` and may be retried (an atomic conditional takeover, so
25
+ two retries cannot both push). Any other failure is `unknown`: retry throws
26
+ `RECONCILIATION_REQUIRED` until `reconcileAccountingPaymentSync` is given the
27
+ provider's authoritative lookup of that request (`found` completes it,
28
+ `absent` makes it retryable; an interrupted `in_flight` row also needs
29
+ `confirmInterruptedOwnerStopped`). Two concurrent calls: one pushes, the other
30
+ gets `SYNC_IN_PROGRESS`. A synced payment returns `unchanged`.
31
+
32
+ The local `Payment` row is not edited; `AccountingPaymentSync.externalId` is the
33
+ provider id. Payments cannot be un-applied by this module: if allocations change
34
+ after the push, readback reports drift.
35
+
36
+ ### SDK seam (sdk#1540)
37
+
38
+ `AccountingPaymentPort.create(request)` is the provider call; the host adapts
39
+ the SDK's payment creation to it (`requestId` is the idempotency key; throw an
40
+ error with `outcome: 'rejected'` on a definite refusal). smrt tests use fakes.
41
+
42
+ ## Readback
43
+
44
+ `readbackInvoice({ db, tenantId, invoiceId, reader })` reads the provider
45
+ document (and linked transactions) through `AccountingInvoiceReader`, projects
46
+ it with the pilot's `projectQuickBooksPilotEvidence` (balance, paid, credited,
47
+ refunded, state, transactions) and stores it in `AccountingInvoiceReadback`
48
+ (unique per invoice) with a status:
49
+
50
+ | status | when |
51
+ |---|---|
52
+ | `in_step` | provider paid amount equals Commerce's (completed allocations), no provider-only payment |
53
+ | `drift` | `PAID_AMOUNT_DIFFERS`, `PROVIDER_ONLY_PAYMENT` (a payment recorded only in the provider; ids in `providerOnlyJson`), or `VOIDED_IN_PROVIDER` |
54
+ | `needs_reconciliation` | evidence incomplete or inconsistent, scope or total mismatch, or the read failed |
55
+
56
+ Reads only; it never writes to the provider and never creates a Work payment
57
+ from a provider-only one (Epic J decision J-e).
58
+
59
+ ## Batches
60
+
61
+ Both are bounded (`limit` default 25, max 100) and resumable (`cursor` in,
62
+ `nextCursor` out; `null` at the end), so a job only schedules and locks:
63
+
64
+ - `syncPending({ db, tenantId, provider, payments, limit?, cursor?, customers? })`:
65
+ pushes pending frozen invoices and credit notes (built with
66
+ `buildFrozenInvoiceMapping`), then payments whose invoices are synced. Items
67
+ report `synced | unchanged | skipped | failed` with a code. A missing mapping
68
+ or unsynced source skips the item; a closed live gate or dead connection stops
69
+ the batch. `customers` (directory + describe) resolves missing customer
70
+ mappings; an ambiguous match is skipped, never created.
71
+ - `readbackDue({ db, tenantId, reader, limit?, olderThan?, cursor?, now? })`:
72
+ reads synced invoices never read or last read before `olderThan` (default 15
73
+ minutes).
74
+
75
+ Invoices with retention or ordinary-accounting state keep their own commands and
76
+ are not picked up by `syncPending`.
@@ -70,3 +70,6 @@ runs under the reservation lock, including unresolved exports; a mismatch leaves
70
70
  ordinary state absent. Once ordinary authority is reserved, base export uses the
71
71
  owning command so a competing generic export cannot replace that mapping between
72
72
  reservation and provider I/O. Read-only frozen projections remain available.
73
+
74
+ Production providers or mappings are refused unless live mode is enabled for the
75
+ tenant's connected company; see [live-mode gate](accounting-live-gate.md).
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Tenant-scoped accounting connection commands (#5136).
3
+ *
4
+ * A tenant connects one QuickBooks Online company. The refresh token lives in
5
+ * smrt-secrets (through the {@link AccountingSecretStore} port), never in a
6
+ * column. Intuit rotates the refresh token on every refresh, and a fresh
7
+ * `QuickBooksProvider` refreshes on its first call, so two concurrent users of
8
+ * the same stored token lose one of them. Every rotation therefore runs under a
9
+ * per-connection lease (`leaseToken`/`leaseExpiresAt` on the row): taken with a
10
+ * conditional `UPDATE`, never held across a database transaction, and renewed
11
+ * only by its owner. Waiters poll up to a bound instead of failing.
12
+ *
13
+ * Nothing here talks to Intuit directly: the host injects the OAuth client
14
+ * ({@link AccountingOAuthPort}) and the provider constructor, so fixtures
15
+ * can stand in for both. See `agents/accounting-connection.md`.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import type { AccountingProvider, QuickBooksOptions, TokenSet } from '@happyvertical/accounting';
20
+ import type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';
21
+ import { type AccountingConnection, type AccountingConnectionEnvironment } from './models/AccountingConnection.js';
22
+ /** smrt-secrets category for accounting tokens. */
23
+ export declare const ACCOUNTING_SECRET_CATEGORY = "accounting.quickbooks";
24
+ /** Name of the tenant's QuickBooks refresh-token secret. */
25
+ export declare const QUICKBOOKS_REFRESH_TOKEN_SECRET = "accounting-quickbooks-refresh-token";
26
+ /** Why an accounting-connection command refused. Messages never carry tokens. */
27
+ export type AccountingConnectionErrorCode = 'INVALID_INPUT' | 'NOT_CONNECTED' | 'NEEDS_RECONNECT' | 'LEASE_TIMEOUT' | 'REVOKE_FAILED';
28
+ /** Typed refusal from an accounting-connection command. */
29
+ export declare class AccountingConnectionError extends Error {
30
+ readonly code: AccountingConnectionErrorCode;
31
+ constructor(code: AccountingConnectionErrorCode, message: string);
32
+ }
33
+ /**
34
+ * The slice of smrt-secrets the connection needs. `SecretService` from
35
+ * `@happyvertical/smrt-secrets` satisfies it.
36
+ */
37
+ export interface AccountingSecretStore {
38
+ /** Store (upsert) a secret for the tenant. */
39
+ storeForTenant(tenantId: string, name: string, value: string, options?: {
40
+ category?: string;
41
+ description?: string;
42
+ }): Promise<unknown>;
43
+ /** Read a secret for the tenant; rejects when it does not exist. */
44
+ retrieveForTenant(tenantId: string, name: string): Promise<{
45
+ value: string;
46
+ }>;
47
+ /** Delete a secret for the tenant; `false` when absent. */
48
+ deleteForTenant(tenantId: string, name: string): Promise<boolean>;
49
+ }
50
+ /**
51
+ * The slice of the SDK's `QuickBooksOAuthClient` the connection needs
52
+ * (`createQuickBooksOAuthClient`). `refresh` arrives with happyvertical/sdk#1541.
53
+ */
54
+ export interface AccountingOAuthPort {
55
+ /** Revoke a refresh token at the provider. */
56
+ revoke(input: {
57
+ refreshToken: string;
58
+ }): Promise<void>;
59
+ }
60
+ /** Shared dependencies of the connection commands. */
61
+ export interface AccountingConnectionDeps {
62
+ readonly db: DatabaseInterface;
63
+ readonly secrets: AccountingSecretStore;
64
+ /** Lease lifetime in ms (default 120 000). */
65
+ readonly leaseMs?: number;
66
+ /** Longest a caller waits for a held lease in ms (default 30 000). */
67
+ readonly waitMs?: number;
68
+ /** Poll interval while waiting for a lease in ms (default 50). */
69
+ readonly pollMs?: number;
70
+ /** Clock override for tests. */
71
+ readonly now?: () => Date;
72
+ }
73
+ /**
74
+ * Whether a provider error means the grant is dead and the user must reconnect.
75
+ * Structural on purpose: `AccountingReauthRequiredError` (sdk#1541) carries
76
+ * `code === 'REAUTH_REQUIRED'`; a raw OAuth `invalid_grant` is treated alike.
77
+ */
78
+ export declare function isReauthRequired(error: unknown): boolean;
79
+ /** The tenant's QuickBooks connection record, or `null` (read-only). */
80
+ export declare function getAccountingConnection(deps: Pick<AccountingConnectionDeps, 'db'>, tenantId: string): Promise<AccountingConnection | null>;
81
+ /** Input of {@link completeQuickBooksConnection}. */
82
+ export interface CompleteQuickBooksConnectionInput {
83
+ readonly tenantId: string;
84
+ /** The company the user authorized (from the OAuth callback). */
85
+ readonly realmId: string;
86
+ /** The environment the callback was issued for. */
87
+ readonly environment: AccountingConnectionEnvironment;
88
+ /** The token exchange result; only the refresh token is retained. */
89
+ readonly tokens: Pick<TokenSet, 'refreshToken'>;
90
+ /** Opaque reference of the user who connected, for audit. */
91
+ readonly connectedBy?: string;
92
+ }
93
+ /**
94
+ * Bind a completed QuickBooks OAuth callback to the tenant (the completion hook
95
+ * for the shared connect flow, smrt#5128). The callback supplies the `realmId`,
96
+ * environment and exchanged tokens; the connection is tenant-level, so no user
97
+ * owns it. Stores the refresh token in smrt-secrets, then marks the row
98
+ * `connected` and clears any error. Reconnecting rebinds the same row (the
99
+ * company may differ) under the refresh lease, so an in-flight refresh cannot
100
+ * overwrite the fresh token.
101
+ */
102
+ export declare function completeQuickBooksConnection(deps: AccountingConnectionDeps, input: CompleteQuickBooksConnectionInput): Promise<AccountingConnection>;
103
+ /** Host configuration for {@link withTenantQuickBooksProvider}. */
104
+ export interface TenantQuickBooksProviderConfig extends AccountingConnectionDeps {
105
+ /** The Intuit app credentials (the host's own secrets; never stored here). */
106
+ readonly clientCredentials: () => {
107
+ clientId: string;
108
+ clientSecret: string;
109
+ redirectUri?: string;
110
+ } | Promise<{
111
+ clientId: string;
112
+ clientSecret: string;
113
+ redirectUri?: string;
114
+ }>;
115
+ /** Provider factory; defaults to the SDK's `getAccountingProvider`. */
116
+ readonly createProvider?: (options: QuickBooksOptions) => TenantQuickBooksProvider;
117
+ }
118
+ /**
119
+ * A `QuickBooksProvider` as the SDK factory returns it: the accounting provider
120
+ * plus the public `ensureAccessToken()` this module drives. Fixtures implement
121
+ * the `ensureAccessToken` slice with single-use refresh tokens.
122
+ */
123
+ export type TenantQuickBooksProvider = AccountingProvider & {
124
+ /** Refresh the access token if needed; reports rotation via `onTokenRefresh`. */
125
+ ensureAccessToken(): Promise<string>;
126
+ };
127
+ /**
128
+ * Run `fn` with a ready `QuickBooksProvider` for the tenant's connection, so
129
+ * the app never handles tokens.
130
+ *
131
+ * The refresh runs under the connection lease: the stored token is read inside
132
+ * the lease, the provider refreshes (`ensureAccessToken`), and the rotated token
133
+ * is persisted through `onTokenRefresh` before the lease is released. `fn` then
134
+ * runs on the already-fresh provider outside the lease. A rejected grant
135
+ * (`invalid_grant`, surfaced by the SDK as a `REAUTH_REQUIRED` error) is
136
+ * re-checked against the stored token under the lease and, if it was the
137
+ * current one, moves the connection to `needs_reconnect` and throws
138
+ * `NEEDS_RECONNECT` instead of failing jobs silently.
139
+ *
140
+ * Seam (sdk): a provider seeded with a valid access token would not refresh on
141
+ * first use; today a new provider always refreshes once, so this is a lease
142
+ * around each provider's first call.
143
+ */
144
+ export declare function withTenantQuickBooksProvider<T>(config: TenantQuickBooksProviderConfig, tenantId: string, fn: (provider: TenantQuickBooksProvider) => Promise<T>): Promise<T>;
145
+ /** Input of {@link disconnectQuickBooks}. */
146
+ export interface DisconnectQuickBooksInput {
147
+ readonly tenantId: string;
148
+ /** The SDK OAuth client used to revoke the refresh token at Intuit. */
149
+ readonly oauth: AccountingOAuthPort;
150
+ }
151
+ /**
152
+ * Disconnect: revoke the refresh token at Intuit, delete the secret, mark the
153
+ * row `disconnected`. The row (and the sync history keyed to it) is kept. Runs
154
+ * under the refresh lease so a refresh cannot resurrect the deleted secret. A
155
+ * grant the provider already rejects counts as revoked; any other revoke
156
+ * failure throws `REVOKE_FAILED` and leaves the connection untouched so the
157
+ * call can be retried. Idempotent.
158
+ */
159
+ export declare function disconnectQuickBooks(deps: AccountingConnectionDeps, input: DisconnectQuickBooksInput): Promise<AccountingConnection>;
160
+ /** Input of {@link enableLiveAccounting}. */
161
+ export interface EnableLiveAccountingInput {
162
+ readonly tenantId: string;
163
+ /** The company being enabled; must equal the connected one. */
164
+ readonly realmId: string;
165
+ /** Who is enabling live writes (an opaque user reference). */
166
+ readonly enabledBy: string;
167
+ /** Reference to the evidence that justified it (for example a sandbox report). */
168
+ readonly evidenceRef: string;
169
+ }
170
+ /**
171
+ * Deliberately enable production accounting writes for the tenant's connected
172
+ * company (#5138). Requires a `connected` **production** connection to the named
173
+ * company; the gate in the sync functions stays closed otherwise. Enablement is
174
+ * per company: rebinding the connection or disconnecting clears it.
175
+ */
176
+ export declare function enableLiveAccounting(deps: AccountingConnectionDeps, input: EnableLiveAccountingInput): Promise<AccountingConnection>;
177
+ /** Switch production accounting writes off again. Idempotent. */
178
+ export declare function disableLiveAccounting(deps: AccountingConnectionDeps, tenantId: string): Promise<AccountingConnection | null>;
179
+ //# sourceMappingURL=accounting-connection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accounting-connection.d.ts","sourceRoot":"","sources":["../src/accounting-connection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,QAAQ,EACT,MAAM,2BAA2B,CAAC;AAEnC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAI7E,OAAO,EACL,KAAK,oBAAoB,EACzB,KAAK,+BAA+B,EAErC,MAAM,kCAAkC,CAAC;AAE1C,mDAAmD;AACnD,eAAO,MAAM,0BAA0B,0BAA0B,CAAC;AAElE,4DAA4D;AAC5D,eAAO,MAAM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AAqB,CACzC,IAAI,EAAE,wBAAwB,EAC9B,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAQtC"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Live-mode gate on accounting writes (#5138).
3
+ *
4
+ * The frozen invoice, credit and refund sync functions accepted any provider
5
+ * with `environment: 'production'`; live use was blocked only by convention.
6
+ * Production writes now need a deliberate, persisted enablement on the tenant's
7
+ * {@link AccountingConnection} (`enableLiveAccounting`) for the same company,
8
+ * and a connected production connection. Sandbox stays the default and needs
9
+ * nothing. Without it a production write throws
10
+ * {@link AccountingLiveGateError} before any state is reserved or any provider
11
+ * call is made, so state is unchanged.
12
+ *
13
+ * See `agents/accounting-live-gate.md`.
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ import type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';
18
+ /** Why the gate refused a write. */
19
+ export type AccountingLiveGateErrorCode = 'LIVE_ACCOUNTING_NOT_ENABLED' | 'ACCOUNTING_ENVIRONMENT_MISMATCH';
20
+ /** Typed refusal: a production accounting write is not enabled. */
21
+ export declare class AccountingLiveGateError extends Error {
22
+ readonly code: AccountingLiveGateErrorCode;
23
+ constructor(code: AccountingLiveGateErrorCode, message: string);
24
+ }
25
+ /** What a sync function is about to write to. */
26
+ export interface AccountingWriteTarget {
27
+ readonly db: DatabaseInterface;
28
+ readonly tenantId: string;
29
+ /** The local document, used to read the realm and environment it is bound to. */
30
+ readonly invoiceId?: string;
31
+ /** The provider; its own `environment` is checked when it exposes one. */
32
+ readonly provider?: object;
33
+ /** The realm and environment the caller's mapping targets, when it has one. */
34
+ readonly scope?: {
35
+ readonly realmId: string;
36
+ readonly environment: 'sandbox' | 'production';
37
+ };
38
+ }
39
+ /**
40
+ * Refuse a production accounting write unless live mode is enabled for the
41
+ * tenant's connected company. Call before reserving state or calling the
42
+ * provider. Resolves for sandbox targets.
43
+ *
44
+ * The target environment is every one of: the caller's mapping scope, the
45
+ * provider's own `environment`, and the environment the document was already
46
+ * synced under. They must agree, so a sandbox-labelled mapping cannot reach a
47
+ * production provider; any production among them requires the gate.
48
+ */
49
+ export declare function assertAccountingWriteAllowed(target: AccountingWriteTarget): Promise<void>;
50
+ //# sourceMappingURL=accounting-live-gate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accounting-live-gate.d.ts","sourceRoot":"","sources":["../src/accounting-live-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAK7E,oCAAoC;AACpC,MAAM,MAAM,2BAA2B,GACnC,6BAA6B,GAC7B,iCAAiC,CAAC;AAEtC,mEAAmE;AACnE,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,QAAQ,CAAC,IAAI,EAAE,2BAA2B,CAAC;gBAE/B,IAAI,EAAE,2BAA2B,EAAE,OAAO,EAAE,MAAM;CAK/D;AAED,iDAAiD;AACjD,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,EAAE,EAAE,iBAAiB,CAAC;IAC/B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,iFAAiF;IACjF,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,0EAA0E;IAC1E,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,+EAA+E;IAC/E,QAAQ,CAAC,KAAK,CAAC,EAAE;QACf,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QACzB,QAAQ,CAAC,WAAW,EAAE,SAAS,GAAG,YAAY,CAAC;KAChD,CAAC;CACH;AA2BD;;;;;;;;;GASG;AACH,wBAAsB,4BAA4B,CAChD,MAAM,EAAE,qBAAqB,GAC5B,OAAO,CAAC,IAAI,CAAC,CAyDf"}