@openlup/platform 0.22.0 → 0.23.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.
Files changed (156) hide show
  1. package/CHANGELOG.md +222 -99
  2. package/README.md +59 -589
  3. package/dist/fulfillment/adapterConformance.js +1 -1
  4. package/dist/fulfillment/bindings.js +1 -1
  5. package/dist/fulfillment/contracts/conformance.d.ts +3 -1
  6. package/dist/fulfillment/contracts/dispatch.d.ts +41 -3
  7. package/dist/fulfillment/contracts/index.d.ts +3 -3
  8. package/dist/fulfillment/contracts/observation.d.ts +21 -1
  9. package/dist/fulfillment/contracts/readback.d.ts +21 -0
  10. package/dist/fulfillment/contracts/store.d.ts +3 -0
  11. package/dist/fulfillment/contracts/sync.d.ts +58 -2
  12. package/dist/fulfillment/dispatchProjection.d.ts +20 -1
  13. package/dist/fulfillment/dispatchProjection.js +95 -6
  14. package/dist/fulfillment/index.d.ts +3 -2
  15. package/dist/fulfillment/index.js +2 -2
  16. package/dist/fulfillment/migrations.d.ts +5 -0
  17. package/dist/fulfillment/migrations.js +1 -0
  18. package/dist/fulfillment/observationProjection.d.ts +24 -3
  19. package/dist/fulfillment/observationProjection.js +65 -12
  20. package/dist/fulfillment/omnipack/client.d.ts +3 -1
  21. package/dist/fulfillment/omnipack/client.js +17 -7
  22. package/dist/fulfillment/omnipack/index.d.ts +4 -1
  23. package/dist/fulfillment/omnipack/index.js +104 -45
  24. package/dist/fulfillment/omnipack/mappers.d.ts +7 -1
  25. package/dist/fulfillment/omnipack/mappers.js +24 -2
  26. package/dist/fulfillment/omnipack/observation.d.ts +11 -4
  27. package/dist/fulfillment/omnipack/observation.js +44 -29
  28. package/dist/fulfillment/omnipack/reconciliation.d.ts +15 -0
  29. package/dist/fulfillment/omnipack/reconciliation.js +55 -0
  30. package/dist/fulfillment/postgresDispatchStore.js +1 -1
  31. package/dist/fulfillment/postgresShipmentSpine.d.ts +8 -1
  32. package/dist/fulfillment/postgresShipmentSpine.js +17 -3
  33. package/dist/fulfillment/postgresStockSyncPort.js +6 -3
  34. package/dist/fulfillment/providerDispatchAcceptance.d.ts +1 -0
  35. package/dist/fulfillment/providerDispatchAcceptance.js +8 -2
  36. package/dist/fulfillment/providerDispatchWorker.d.ts +13 -0
  37. package/dist/fulfillment/providerDispatchWorker.js +47 -20
  38. package/dist/fulfillment/providerReconciliationWorker.d.ts +27 -19
  39. package/dist/fulfillment/providerReconciliationWorker.js +75 -19
  40. package/dist/fulfillment/providerStockSyncWorker.d.ts +5 -1
  41. package/dist/fulfillment/providerStockSyncWorker.js +229 -120
  42. package/dist/fulfillment/providerTrackingReferences.d.ts +3 -2
  43. package/dist/fulfillment/verifiedIngress.d.ts +38 -11
  44. package/dist/fulfillment/verifiedIngress.js +36 -8
  45. package/dist/invoicing/capabilities.d.ts +11 -0
  46. package/dist/invoicing/capabilities.js +10 -0
  47. package/dist/invoicing/contracts/capabilities.d.ts +40 -0
  48. package/dist/invoicing/contracts/capabilities.js +1 -0
  49. package/dist/invoicing/contracts/companyLookup.d.ts +49 -0
  50. package/dist/invoicing/contracts/companyLookup.js +1 -0
  51. package/dist/invoicing/contracts/delivery.d.ts +74 -0
  52. package/dist/invoicing/contracts/delivery.js +1 -0
  53. package/dist/invoicing/contracts/facts.d.ts +100 -0
  54. package/dist/invoicing/contracts/facts.js +1 -0
  55. package/dist/invoicing/contracts/host.d.ts +246 -0
  56. package/dist/invoicing/contracts/host.js +1 -0
  57. package/dist/invoicing/contracts/index.d.ts +16 -0
  58. package/dist/invoicing/contracts/index.js +1 -0
  59. package/dist/invoicing/contracts/provider.d.ts +126 -0
  60. package/dist/invoicing/contracts/provider.js +1 -0
  61. package/dist/invoicing/contracts/settlement.d.ts +66 -0
  62. package/dist/invoicing/contracts/settlement.js +1 -0
  63. package/dist/invoicing/contracts/store.d.ts +267 -0
  64. package/dist/invoicing/contracts/store.js +1 -0
  65. package/dist/invoicing/index.d.ts +1 -0
  66. package/dist/invoicing/index.js +1 -0
  67. package/dist/subscriptions/automaticRenewal.d.ts +44 -0
  68. package/dist/subscriptions/automaticRenewal.js +81 -0
  69. package/dist/subscriptions/automaticRenewalExecution.d.ts +21 -0
  70. package/dist/subscriptions/automaticRenewalExecution.js +44 -0
  71. package/dist/subscriptions/contracts/commands.d.ts +115 -0
  72. package/dist/subscriptions/contracts/commands.js +1 -0
  73. package/dist/subscriptions/contracts/dunning.d.ts +133 -0
  74. package/dist/subscriptions/contracts/dunning.js +1 -0
  75. package/dist/subscriptions/contracts/index.d.ts +6 -0
  76. package/dist/subscriptions/contracts/index.js +1 -0
  77. package/dist/subscriptions/contracts/messages.d.ts +43 -0
  78. package/dist/subscriptions/contracts/messages.js +1 -0
  79. package/dist/subscriptions/contracts/renewal.d.ts +533 -0
  80. package/dist/subscriptions/contracts/renewal.js +1 -0
  81. package/dist/subscriptions/contracts/stockWait.d.ts +73 -0
  82. package/dist/subscriptions/contracts/stockWait.js +1 -0
  83. package/dist/subscriptions/index.d.ts +39 -0
  84. package/dist/subscriptions/index.js +17 -0
  85. package/dist/subscriptions/paymentOutcomes.d.ts +8 -0
  86. package/dist/subscriptions/paymentOutcomes.js +27 -0
  87. package/dist/subscriptions/postgresRenewalStore.d.ts +20 -0
  88. package/dist/subscriptions/postgresRenewalStore.js +61 -0
  89. package/dist/subscriptions/postgresRetryStore.d.ts +78 -0
  90. package/dist/subscriptions/postgresRetryStore.js +142 -0
  91. package/dist/subscriptions/renewalCycleFailureMechanism.d.ts +34 -0
  92. package/dist/subscriptions/renewalCycleFailureMechanism.js +79 -0
  93. package/dist/subscriptions/renewalCycleMechanism.d.ts +46 -0
  94. package/dist/subscriptions/renewalCycleMechanism.js +157 -0
  95. package/dist/subscriptions/renewalCycleRefusalMechanism.d.ts +41 -0
  96. package/dist/subscriptions/renewalCycleRefusalMechanism.js +160 -0
  97. package/dist/subscriptions/renewalIdentity.d.ts +3 -0
  98. package/dist/subscriptions/renewalIdentity.js +4 -0
  99. package/package.json +22 -2
  100. package/release-gates.json +56 -3
  101. package/sql/20261022160000_subscription_retry_lifecycle.sql +328 -0
  102. package/sql/20261022165000_fulfillment_stock_evidence_replay_reopen.sql +30 -0
  103. package/src/fulfillment/adapterConformance.ts +1 -1
  104. package/src/fulfillment/bindings.ts +1 -1
  105. package/src/fulfillment/contracts/conformance.ts +3 -1
  106. package/src/fulfillment/contracts/dispatch.ts +20 -5
  107. package/src/fulfillment/contracts/index.ts +3 -3
  108. package/src/fulfillment/contracts/observation.ts +11 -3
  109. package/src/fulfillment/contracts/readback.ts +13 -0
  110. package/src/fulfillment/contracts/store.ts +1 -0
  111. package/src/fulfillment/contracts/sync.ts +13 -2
  112. package/src/fulfillment/dispatchProjection.ts +92 -7
  113. package/src/fulfillment/index.ts +3 -2
  114. package/src/fulfillment/migrations.ts +1 -0
  115. package/src/fulfillment/observationProjection.ts +64 -13
  116. package/src/fulfillment/omnipack/client.ts +19 -7
  117. package/src/fulfillment/omnipack/index.ts +96 -39
  118. package/src/fulfillment/omnipack/mappers.ts +23 -2
  119. package/src/fulfillment/omnipack/observation.ts +45 -27
  120. package/src/fulfillment/omnipack/reconciliation.ts +56 -0
  121. package/src/fulfillment/postgresDispatchStore.ts +1 -1
  122. package/src/fulfillment/postgresShipmentSpine.ts +21 -4
  123. package/src/fulfillment/postgresStockSyncPort.ts +6 -3
  124. package/src/fulfillment/providerDispatchAcceptance.ts +9 -3
  125. package/src/fulfillment/providerDispatchWorker.ts +48 -20
  126. package/src/fulfillment/providerReconciliationWorker.ts +81 -25
  127. package/src/fulfillment/providerStockSyncWorker.ts +222 -126
  128. package/src/fulfillment/providerTrackingReferences.ts +3 -2
  129. package/src/fulfillment/verifiedIngress.ts +44 -11
  130. package/src/invoicing/capabilities.ts +9 -0
  131. package/src/invoicing/contracts/capabilities.ts +15 -0
  132. package/src/invoicing/contracts/companyLookup.ts +13 -0
  133. package/src/invoicing/contracts/delivery.ts +24 -0
  134. package/src/invoicing/contracts/facts.ts +60 -0
  135. package/src/invoicing/contracts/host.ts +85 -0
  136. package/src/invoicing/contracts/index.ts +16 -0
  137. package/src/invoicing/contracts/provider.ts +78 -0
  138. package/src/invoicing/contracts/settlement.ts +39 -0
  139. package/src/invoicing/contracts/store.ts +98 -0
  140. package/src/invoicing/index.ts +1 -0
  141. package/src/subscriptions/automaticRenewal.ts +87 -0
  142. package/src/subscriptions/automaticRenewalExecution.ts +39 -0
  143. package/src/subscriptions/contracts/commands.ts +46 -0
  144. package/src/subscriptions/contracts/dunning.ts +48 -0
  145. package/src/subscriptions/contracts/index.ts +6 -0
  146. package/src/subscriptions/contracts/messages.ts +18 -0
  147. package/src/subscriptions/contracts/renewal.ts +325 -0
  148. package/src/subscriptions/contracts/stockWait.ts +34 -0
  149. package/src/subscriptions/index.ts +24 -0
  150. package/src/subscriptions/paymentOutcomes.ts +23 -0
  151. package/src/subscriptions/postgresRenewalStore.ts +76 -0
  152. package/src/subscriptions/postgresRetryStore.ts +174 -0
  153. package/src/subscriptions/renewalCycleFailureMechanism.ts +119 -0
  154. package/src/subscriptions/renewalCycleMechanism.ts +225 -0
  155. package/src/subscriptions/renewalCycleRefusalMechanism.ts +215 -0
  156. package/src/subscriptions/renewalIdentity.ts +5 -0
@@ -1,20 +1,35 @@
1
- import type { FulfillmentObservation, FulfillmentObservationPort, FulfillmentRefusal } from "./contracts/index.js";
1
+ import type { FulfillmentObservation, FulfillmentObservationCodecs, FulfillmentObservationPort, FulfillmentRefusal } from "./contracts/index.js";
2
+ import { safeDiagnosticCode } from "./dispatchProjection.js";
2
3
  import { applyFulfillmentObservationEffects } from "./fulfillmentObservationEffects.js";
3
4
  import { observationStatusPolicy, projectObservation } from "./observationProjection.js";
4
5
  import { uniqueTrackingReferences } from "./providerTrackingReferences.js";
5
6
 
6
7
  type EffectInput = Parameters<typeof applyFulfillmentObservationEffects<FulfillmentObservation["fact"]["canonicalStatus"], "in_transit" | "delivered">>[0];
7
8
  type DispatchRef = { orderRef: string; fulfillmentRef: string; dispatchRef: string; externalRef: string | null };
9
+ export interface FulfillmentIngressCounts { invalidTimestamps: number; rejectedCorrelationRefs: number; rejectedTrackingRefs: number; rejectedTrackingUrls: number }
10
+ export type FulfillmentIngressResult = { counts: FulfillmentIngressCounts } & (
11
+ | { kind: "refused"; receiptId: null; refusal: FulfillmentRefusal; diagnostics?: { invalidTimestamp?: true; rejectedCorrelationRefs?: number } }
12
+ | { kind: "processed" | "ignored" | "superseded"; receiptId: string; observation: FulfillmentObservation; replayed: boolean; trackingRefs: number; trackingReadBacks: number; supersededCause?: string });
13
+ /** Safe response classes only; the host owns HTTP and localized message text. */
14
+ export function fulfillmentIngressHttpResult(result: FulfillmentIngressResult): { status: 200 | 400 | 403 | 503; messageClass: "accepted" | "bad_request" | "forbidden" | "upstream_unavailable" } {
15
+ if (result.kind !== "refused") return { status: 200, messageClass: "accepted" };
16
+ if (result.refusal.reason === "untrusted") return { status: 403, messageClass: "forbidden" };
17
+ if (result.refusal.reason === "disabled" || result.refusal.reason === "not_ready" || result.refusal.retryable)
18
+ return { status: 503, messageClass: "upstream_unavailable" };
19
+ return { status: 400, messageClass: "bad_request" };
20
+ }
8
21
  /** Adapter verification owns auth-before-parse; the host owns durable replay. */
9
22
  export async function verifyAndNormalizeFulfillmentObservation(input: {
10
23
  enabled: boolean;
24
+ approveTrackingUrl?(url: string): boolean;
25
+ observationCodecs?: FulfillmentObservationCodecs;
11
26
  provider: FulfillmentObservationPort;
12
27
  verification: Parameters<FulfillmentObservationPort["verifyAndNormalize"]>[0];
13
28
  localPersistence: {
14
29
  /** G17: atomic insert by eventKey; retries keep the first stored firstReceivedAt. */
15
- recordObservation(observation: FulfillmentObservation): Promise<{ replayed: boolean }>;
30
+ recordObservation(observation: FulfillmentObservation): Promise<{ replayed: boolean; receiptId?: string }>;
16
31
  /** Idempotent; only called after completion or a classified superseding conflict. */
17
- markProcessed(eventKey: string, outcome: { status: "processed" | "ignored"; refusal?: FulfillmentRefusal }): Promise<void>;
32
+ markProcessed(eventKey: string, outcome: { status: "processed" | "ignored"; refusal?: FulfillmentRefusal; supersededCause?: string }): Promise<void>;
18
33
  };
19
34
  lifecycle: {
20
35
  findDispatchRef(observation: FulfillmentObservation): Promise<DispatchRef | null>;
@@ -23,19 +38,34 @@ export async function verifyAndNormalizeFulfillmentObservation(input: {
23
38
  effects: EffectInput["port"];
24
39
  keys: { stock(ref: string): string; handoff(ref: string): string; tracking(eventKey: string, number: string): string };
25
40
  issueAccountingInvoice?(ref: string): Promise<void>;
41
+ /** Return a machine identity, never exception prose. */
42
+ supersededCause?(error: unknown): string | null;
26
43
  classifyFailure(error: unknown): "stock_contention" | "state_conflict" | "other";
27
44
  annotateStockContention?(eventKey: string, fulfillmentRef: string): Promise<void>;
28
45
  };
29
- }): Promise<{ kind: "refused"; refusal: FulfillmentRefusal } | { kind: "processed" | "ignored" | "superseded"; observation: FulfillmentObservation; replayed: boolean; trackingRefs: number; trackingReadBacks: number }> {
30
- if (!input.enabled) return { kind: "refused", refusal: { reason: "disabled", phase: "verify", retryable: false } };
46
+ }): Promise<FulfillmentIngressResult> {
47
+ const counts: FulfillmentIngressCounts = { invalidTimestamps: 0, rejectedCorrelationRefs: 0, rejectedTrackingRefs: 0, rejectedTrackingUrls: 0 };
48
+ if (!input.enabled) return { kind: "refused", receiptId: null, counts, refusal: { reason: "disabled", phase: "verify", retryable: false } };
31
49
  const verified = await input.provider.verifyAndNormalize(input.verification);
32
- if (verified.kind === "refused") return verified;
33
- const observation = projectObservation(verified.observation);
50
+ if (verified.kind === "refused") {
51
+ if (verified.diagnostics?.invalidTimestamp) counts.invalidTimestamps++;
52
+ const rejected = verified.diagnostics?.rejectedCorrelationRefs;
53
+ if (typeof rejected === "number" && Number.isSafeInteger(rejected) && rejected > 0) counts.rejectedCorrelationRefs = rejected;
54
+ return { kind: "refused", receiptId: null, refusal: verified.refusal, counts,
55
+ ...(counts.invalidTimestamps || counts.rejectedCorrelationRefs ? { diagnostics: {
56
+ ...(counts.invalidTimestamps ? { invalidTimestamp: true as const } : {}),
57
+ ...(counts.rejectedCorrelationRefs ? { rejectedCorrelationRefs: counts.rejectedCorrelationRefs } : {}),
58
+ } } : {}) };
59
+ }
60
+ const observation = projectObservation(verified.observation, input.approveTrackingUrl, input.observationCodecs);
61
+ counts.rejectedTrackingRefs = observation.diagnostics?.admission?.rejectedTrackingRefs ?? 0;
62
+ counts.rejectedTrackingUrls = observation.diagnostics?.admission?.rejectedTrackingUrls ?? 0;
34
63
  const inbound = await input.localPersistence.recordObservation(observation);
64
+ const receiptId = inbound.receiptId ?? observation.eventKey;
35
65
  const ref = await input.lifecycle.findDispatchRef(observation);
36
66
  if (!ref) {
37
67
  await input.localPersistence.markProcessed(observation.eventKey, { status: "ignored", refusal: { reason: "local_missing", phase: "apply", retryable: false } });
38
- return { kind: "ignored", observation, replayed: inbound.replayed, trackingRefs: 0, trackingReadBacks: 0 };
68
+ return { kind: "ignored", receiptId, counts, observation, replayed: inbound.replayed, trackingRefs: 0, trackingReadBacks: 0 };
39
69
  }
40
70
  const externalRef = observation.correlation.externalRef?.trim() || ref.externalRef?.trim();
41
71
  if (!externalRef) throw new TypeError("fulfillment_dispatch_acceptance_external_ref_missing");
@@ -71,10 +101,13 @@ export async function verifyAndNormalizeFulfillmentObservation(input: {
71
101
  try { await applyFulfillmentObservationEffects(effects, observationStatusPolicy); }
72
102
  catch (error) {
73
103
  if (input.lifecycle.classifyFailure(error) !== "state_conflict") throw error;
74
- await input.localPersistence.markProcessed(observation.eventKey, { status: "processed" });
75
- return { kind: "superseded", observation, replayed: inbound.replayed || statusEvidence.replayed, trackingRefs, trackingReadBacks };
104
+ const cause = input.lifecycle.supersededCause ? input.lifecycle.supersededCause(error)
105
+ : error && typeof error === "object" && "reason" in error ? error.reason : null;
106
+ const supersededCause = safeDiagnosticCode(cause) ?? "fulfillment_state_conflict";
107
+ await input.localPersistence.markProcessed(observation.eventKey, { status: "processed", supersededCause });
108
+ return { kind: "superseded", receiptId, counts, supersededCause, observation, replayed: inbound.replayed || statusEvidence.replayed, trackingRefs, trackingReadBacks };
76
109
  }
77
110
  }
78
111
  await input.localPersistence.markProcessed(observation.eventKey, { status: "processed" });
79
- return { kind: "processed", observation, replayed: inbound.replayed || statusEvidence.replayed, trackingRefs, trackingReadBacks };
112
+ return { kind: "processed", receiptId, counts, observation, replayed: inbound.replayed || statusEvidence.replayed, trackingRefs, trackingReadBacks };
80
113
  }
@@ -0,0 +1,9 @@
1
+ import type { InvoiceCapabilities, InvoiceCapabilitySelection } from "./contracts/capabilities.js";
2
+ /** @consumer Host readiness / installed cold consumer. Default off and explicit
3
+ * provider selection precede capability use; construction never selects a provider.
4
+ */
5
+ export function readInvoiceCapabilities(input: { readonly enabled?: boolean; readonly selection: { readonly providerRef: string } | null; readonly capability: InvoiceCapabilities | null }): InvoiceCapabilitySelection {
6
+ if (input.enabled !== true) return { kind: "refused", code: "disabled", retryable: false, effectMayHaveSucceeded: false };
7
+ if (!input.selection || !input.capability || input.selection.providerRef !== input.capability.providerRef) return { kind: "refused", code: "selection_required", retryable: false, effectMayHaveSucceeded: false };
8
+ return { kind: "ready", capability: input.capability };
9
+ }
@@ -0,0 +1,15 @@
1
+ import type { InvoiceDiagnosticCode, InvoiceUnsupported } from "./provider.js";
2
+ export interface InvoiceCapabilities {
3
+ readonly version: "invoicing.capabilities.v1";
4
+ readonly providerRef: string;
5
+ readonly fiscalScope: { readonly scopeRef: string; readonly version: string };
6
+ readonly policies: { readonly identifierRef: string; readonly taxRef: string; readonly roundingRef: string };
7
+ readonly documentKinds: readonly string[];
8
+ readonly correctionKinds: readonly "full_reversal"[];
9
+ readonly numberingOwner: "provider";
10
+ readonly sellerTiming: "execution" | "first_claim";
11
+ readonly operations: Readonly<Record<"issue" | "correction" | "recovery" | "readback" | "exactAbsence" | "artifact" | "clearance" | "settlement" | "companyLookup", { readonly supported: true } | { readonly supported: false; readonly reason: "host_required" | "not_implemented" | "not_exposed" }>> & { readonly remoteVoid: { readonly supported: false; readonly reason: "not_implemented" } };
12
+ readonly defaultOff: true;
13
+ }
14
+ /** Interpretation only: no environment discovery, activation, writes or provider calls. */
15
+ export type InvoiceCapabilitySelection = InvoiceUnsupported | { readonly kind: "ready"; readonly capability: InvoiceCapabilities } | { readonly kind: "refused"; readonly code: Extract<InvoiceDiagnosticCode, "disabled" | "selection_required">; readonly retryable: false; readonly effectMayHaveSucceeded: false };
@@ -0,0 +1,13 @@
1
+ import type { InvoiceProof, InvoiceUnsupported } from "./provider.js";
2
+ /** Injected registry seam. Host owns identifier validation, freshness and fallback;
3
+ * lookup evidence never overwrites checkout truth or becomes a renewal prerequisite.
4
+ * Carrier: accountingControlContracts lookup fields, generalized per A5 fit probe.
5
+ */
6
+ export interface InvoiceCompanyLookupPort {
7
+ lookup(input: { readonly identifier: { readonly scheme: string; readonly value: string; readonly country?: string }; readonly asOf: string; readonly sourceRef: string }): Promise<
8
+ | { readonly kind: "found" | "partial"; readonly identifier: { readonly scheme: string; readonly value: string; readonly country?: string }; readonly legalName: string | null; readonly registrationIds: readonly { readonly scheme: string; readonly value: string }[]; readonly address: { readonly line1: string; readonly postalCode: string; readonly city: string; readonly country: string } | null; readonly taxRegistrations: readonly { readonly scheme: string; readonly status: "active" | "not_registered" | "exempt" | "unknown" }[]; readonly sourceRef: string; readonly proof: InvoiceProof }
9
+ | { readonly kind: "not_found"; readonly identifier: Parameters<InvoiceCompanyLookupPort["lookup"]>[0]["identifier"]; readonly sourceRef: string; readonly proof: InvoiceProof }
10
+ | { readonly kind: "unknown"; readonly sourceRef: string; readonly code: "unknown" }
11
+ | InvoiceUnsupported
12
+ >;
13
+ }
@@ -0,0 +1,24 @@
1
+ import type { InvoiceDocumentIdentity, InvoiceProof, InvoiceUnsupported } from "./provider.js";
2
+ /** Durable opaque references; signed URLs and downloaded bytes are transient. */
3
+ export type InvoiceArtifactResult =
4
+ | { readonly kind: "found"; readonly identity: InvoiceDocumentIdentity; readonly artifact: { readonly kind: "pdf" | "structured_document" | "clearance_receipt"; readonly ref: string; readonly owner: "provider" | "host_storage"; readonly mediaType: string; readonly proof: InvoiceProof } }
5
+ | { readonly kind: "absent"; readonly identity: InvoiceDocumentIdentity; readonly evidence: InvoiceProof & { readonly exact: true; readonly complete: true; readonly scope: { readonly identity: InvoiceDocumentIdentity; readonly kind: "pdf" | "structured_document" | "clearance_receipt"; readonly artifactRef: string | null } } }
6
+ | { readonly kind: "unknown"; readonly identity: InvoiceDocumentIdentity; readonly code: "unknown" }
7
+ | InvoiceUnsupported;
8
+ /** Observation only; unsupported is never not_required. No clearance submission. */
9
+ export type InvoiceClearanceObservation = { readonly proof: InvoiceProof } & (
10
+ | { readonly state: "accepted"; readonly reference: string }
11
+ | { readonly state: "not_submitted" | "pending" | "rejected" | "not_required" | "unsupported"; readonly reference: string | null }
12
+ );
13
+ export interface InvoiceDeliveryPort {
14
+ /** Host M04 content/transport; provider acceptance is not inbox delivery.
15
+ * Preserve delivery/request keys, recipient, filename and bytes. Validate PDF
16
+ * type, size and signature before send; uncertain send must never repeat sending.
17
+ */
18
+ send(input: { readonly deliveryRef: string; readonly requestKey: string; readonly attemptCount: number; readonly documentRef: string; readonly orderId: string; readonly orderRef: string; readonly invoiceRef: string; readonly providerDocumentRef: string; readonly clientRef: string | null; readonly recipient: string; readonly source: string | null; readonly providerDocumentNumber: string | null; readonly filename: string; readonly content: Uint8Array; readonly contentType: string }): Promise<
19
+ | { readonly kind: "provider_accepted"; readonly receiptRef: string; readonly proof: InvoiceProof }
20
+ | { readonly kind: "failed_before_send"; readonly retryable: boolean; readonly code: "retryable" | "invalid_artifact" }
21
+ | { readonly kind: "uncertain"; readonly code: "uncertain_delivery"; readonly receiptRef: string | null }
22
+ | InvoiceUnsupported
23
+ >;
24
+ }
@@ -0,0 +1,60 @@
1
+ /** Frozen host facts; no catalogue, registry or country-policy reread on retry.
2
+ * Carrier: donor providerPorts snapshot and invoiceContracts LocalInvoiceSnapshot;
3
+ * native invoicing_install_facts adds dates/refs/policyVersion and explicit totals.
4
+ */
5
+ export interface InvoiceSeller {
6
+ readonly name: string;
7
+ readonly address: { readonly line1: string; readonly postalCode: string; readonly city: string };
8
+ readonly taxIdentifier: { readonly scheme: string; readonly value: string };
9
+ readonly registrationIds?: readonly { readonly scheme: string; readonly value: string }[];
10
+ readonly bankAccount: string | null;
11
+ /** Opaque host routing reference, interpreted only by the selected adapter. */
12
+ readonly routingRef: string | null;
13
+ }
14
+ export interface InvoiceBuyer {
15
+ readonly name: string;
16
+ readonly email: string | null;
17
+ readonly taxIdentifier: { readonly scheme: string; readonly value: string } | null;
18
+ readonly companyName: string | null;
19
+ readonly address: { readonly line1: string | null; readonly postalCode: string | null; readonly city: string | null; readonly country: string | null } | null;
20
+ }
21
+ /** Safe integer minor amounts; taxRateBps is a rate, never a fiscal-support claim.
22
+ * Preserve array order and quantityUnit; no inferred shipping residual or FX.
23
+ */
24
+ export interface InvoiceLine {
25
+ readonly description: string;
26
+ readonly quantity: number;
27
+ readonly quantityUnit?: string;
28
+ readonly unitNetMinor: number;
29
+ readonly unitGrossMinor: number;
30
+ readonly totalNetMinor: number;
31
+ readonly totalTaxMinor: number;
32
+ readonly totalGrossMinor: number;
33
+ readonly taxRateBps: number;
34
+ readonly taxRateLabel?: string;
35
+ readonly positionKind: "item" | "delivery" | null;
36
+ readonly catalogTotalGrossMinor: number | null;
37
+ readonly discountAllocatedMinor: number | null;
38
+ readonly shippingGrossMinor: number | null;
39
+ readonly shippingDiscountMinor: number | null;
40
+ }
41
+ export interface InvoiceFacts {
42
+ readonly factRevision: string;
43
+ readonly policyVersion: string;
44
+ readonly refs: { readonly orderId: string; readonly orderRef: string; readonly invoiceRef: string };
45
+ readonly dates: { readonly issueDate: string; readonly sellDate: string; readonly handedOverAt: string | null; readonly paymentCompletedAt: string | null };
46
+ /** Host-defined kind selected through the identifier/tax seam, never guessed. */
47
+ readonly documentKind: string;
48
+ readonly clearanceRequired: boolean;
49
+ readonly currency: string;
50
+ readonly buyer: InvoiceBuyer;
51
+ /** Supplied separately for execution; P8 freezes it at first claim before provider I/O. */
52
+ readonly seller?: InvoiceSeller;
53
+ readonly payment: { readonly intentRef: string; readonly providerRef: string | null; readonly providerPaymentRef: string | null; readonly amountMinor: number; readonly currency: string; readonly localSettlementState: "matched" | "unavailable" };
54
+ readonly orderMoney: { readonly subtotalMinor: number; readonly discountMinor: number; readonly shippingMinor: number; readonly shippingDiscountMinor: number; readonly totalMinor: number } | null;
55
+ readonly lines: readonly InvoiceLine[];
56
+ readonly totalNetMinor: number;
57
+ readonly totalTaxMinor: number;
58
+ readonly totalGrossMinor: number;
59
+ readonly chargedTotalGrossMinor: number;
60
+ }
@@ -0,0 +1,85 @@
1
+ import type { InvoiceFacts, InvoiceSeller } from "./facts.js";
2
+ import type { InvoiceDocumentIdentity, InvoiceProof, InvoiceProviderPort, InvoiceUnsupported } from "./provider.js";
3
+ import type { InvoiceArtifactResult, InvoiceClearanceObservation, InvoiceDeliveryPort } from "./delivery.js";
4
+ import type { InvoiceCompanyLookupPort } from "./companyLookup.js";
5
+ import type { InvoiceSettlementPort } from "./settlement.js";
6
+ import type { InvoiceCapabilities } from "./capabilities.js";
7
+ import type { InvoiceStorePort } from "./store.js";
8
+ /** Host facts, fiscal routing, M07 reads, storage, registry, M04 delivery and M12
9
+ * history are required selections. Every missing native capability refuses before
10
+ * any write; an owed duty remains observable. This interface grants no authority.
11
+ */
12
+ export interface InvoiceHostPorts {
13
+ facts: { read(orderId: string): Promise<{ readonly kind: "found"; readonly facts: InvoiceFacts } | { readonly kind: "unknown"; readonly code: "missing_facts" } | InvoiceUnsupported> };
14
+ /** Read the current host seller for the next claim, never per duty. Null orderId
15
+ * means an unscoped claim (including corrections). P8 freezes this seller at
16
+ * first claim; revisionRef feeds the claim wrapper's revision argument.
17
+ */
18
+ seller: { read(input: { readonly orderId: string | null }): Promise<{ readonly kind: "found"; readonly seller: InvoiceSeller; readonly revisionRef: string } | { readonly kind: "unknown"; readonly code: "unknown" } | InvoiceUnsupported> };
19
+ /** Read-only projection of the final claimed M07 identity, never a refund writer.
20
+ * Missing nullable money is unavailable, never fabricated zero or mismatch.
21
+ */
22
+ money: { read(input: { readonly intentRef: string; readonly providerRef: string; readonly providerPaymentRef: string | null; readonly expectedMoney: { readonly amountMinor: number; readonly currency: string } }): Promise<
23
+ | { readonly kind: "observed"; readonly status: "succeeded" | "failed" | "pending"; readonly amountMinor: number | null; readonly currency: string | null; readonly proof: InvoiceProof }
24
+ | { readonly kind: "absent"; readonly evidence: InvoiceProof & { readonly exact: true; readonly complete: true; readonly scope: Parameters<InvoiceHostPorts["money"]["read"]>[0] } }
25
+ | { readonly kind: "unknown" | "unavailable"; readonly code: "money_unavailable" }
26
+ | InvoiceUnsupported
27
+ > };
28
+ artifacts: {
29
+ read(input: { readonly identity: InvoiceDocumentIdentity; readonly kind: "pdf" | "structured_document" | "clearance_receipt" }): Promise<InvoiceArtifactResult>;
30
+ /** Ownership must already be authorized; response bytes are not a storage receipt. */
31
+ download(input: { readonly identity: InvoiceDocumentIdentity; readonly artifactRef: string }): Promise<{ readonly kind: "downloaded"; readonly content: Uint8Array; readonly contentType: string } | { readonly kind: "unknown"; readonly code: "unknown" } | InvoiceUnsupported>;
32
+ persist(input: { readonly identity: InvoiceDocumentIdentity; readonly kind: "pdf" | "structured_document" | "clearance_receipt"; readonly content: Uint8Array; readonly contentType: string }): Promise<Exclude<InvoiceArtifactResult, { kind: "absent" }>>;
33
+ };
34
+ /** Host identifier/tax/rounding policy; refs must match the selected descriptor.
35
+ * No jurisdictional default is supplied. Carrier: TaxIdRoutingPort and injected
36
+ * canonical tax safety in accountingProviderSnapshot.
37
+ */
38
+ fiscal: { verify(input: { readonly facts: InvoiceFacts; readonly policies: InvoiceCapabilities["policies"] }): Promise<{ readonly kind: "verified"; readonly documentKind: string; readonly clearanceRequired: boolean; readonly proof: InvoiceProof } | { readonly kind: "refused"; readonly code: "blocked" | "money_mismatch" } | { readonly kind: "unknown"; readonly code: "unknown" } | InvoiceUnsupported> };
39
+ registry: InvoiceCompanyLookupPort;
40
+ delivery: InvoiceDeliveryPort;
41
+ clearance: { observe(input: { readonly identity: InvoiceDocumentIdentity; readonly providerDocumentRef: string }): Promise<{ readonly kind: "observed"; readonly observation: InvoiceClearanceObservation } | { readonly kind: "unknown"; readonly code: "unknown" } | InvoiceUnsupported> };
42
+ settlement: InvoiceSettlementPort;
43
+ policy: {
44
+ /** Carrier: channelInvoicePolicyGate and the approved explicit operator skip.
45
+ * Suppression receipts have no fabricated document ID. Host persists attribution.
46
+ * Executor decides before installFacts: suppressed orders get no local document.
47
+ * Readback consumers merge recorded receipts with duty readback.
48
+ * Transient read failures return unknown without recording a receipt.
49
+ */
50
+ decide(input: { readonly requestKey: string; readonly lookup: { readonly by: "order"; readonly orderId: string } | { readonly by: "fulfillmentOrder"; readonly fulfillmentOrderRef: string } }): Promise<
51
+ | { readonly kind: "issue"; readonly policyVersion: string }
52
+ | { readonly kind: "policy_suppressed"; readonly outcome: "channel_issues" | "no_document"; readonly policyVersion: string; readonly requestKey: string }
53
+ | { readonly kind: "operator_skipped"; readonly outcome: "operator_skip"; readonly actorRef: string; readonly reason: string; readonly requestKey: string }
54
+ | { readonly kind: "unknown"; readonly code: "unknown" }
55
+ | InvoiceUnsupported
56
+ >;
57
+ receipts(orderId: string): Promise<readonly (Extract<Awaited<ReturnType<InvoiceHostPorts["policy"]["decide"]>>, { kind: "policy_suppressed" | "operator_skipped" }> & { readonly recordedAt: string })[] | { readonly kind: "unknown"; readonly code: "unknown" } | InvoiceUnsupported>;
58
+ };
59
+ /** Authenticate and authorize ownership before reading artifacts. Safe projection
60
+ * only: no buyer/seller payload, raw provider errors, signed URL or arbitrary meta.
61
+ * Found is a complete owned projection; incomplete reads return unknown.
62
+ * Carrier: donor document history + customer download ticket owner/lineage.
63
+ */
64
+ accountHistory: {
65
+ read(input: { readonly accountRef: string; readonly orderId: string }): Promise<
66
+ | { readonly kind: "found"; readonly accountRef: string; readonly orderId: string; readonly documents: readonly { readonly documentRef: string; readonly invoiceRef: string; readonly parentDocumentRef: string | null; readonly role: "original" | "correction" | "replacement"; readonly status: string; readonly issuedAt: string | null; readonly clearance: { readonly state: InvoiceClearanceObservation["state"]; readonly reference: string | null } | null; readonly documentKind: string | null; readonly artifact: "invoice" | "correction"; readonly providerDocumentNumber: string | null; readonly totalGrossMinor: number | null; readonly currency: string; readonly emailState: "not_requested" | "pending" | "provider_accepted" | "failed"; readonly isCurrent: boolean; readonly createdAt: string; readonly downloadAvailable: boolean }[] }
67
+ | { readonly kind: "denied" }
68
+ | { readonly kind: "unknown"; readonly code: "unknown" }
69
+ | InvoiceUnsupported
70
+ >;
71
+ resolveDownload(input: { readonly accountRef: string; readonly orderId: string; readonly documentRef: string }): Promise<{ readonly kind: "authorized"; readonly identity: InvoiceDocumentIdentity; readonly artifactRef: string; readonly fileName: string; readonly parentDocumentRef: string | null } | { readonly kind: "denied" } | { readonly kind: "unknown"; readonly code: "unknown" } | InvoiceUnsupported>;
72
+ };
73
+ }
74
+ /** Future service composition inputs only; no constructor, worker or runtime route
75
+ * is supplied in P1. Closures/credentials must never be serialized with options.
76
+ */
77
+ export interface InvoiceServicesOptions {
78
+ readonly enabled?: boolean;
79
+ readonly selection: { readonly providerRef: string } | null;
80
+ readonly capability: InvoiceCapabilities | null;
81
+ readonly provider: InvoiceProviderPort | null;
82
+ readonly store: InvoiceStorePort | null;
83
+ readonly host: InvoiceHostPorts;
84
+ readiness(): Promise<{ readonly kind: "ready" } | InvoiceUnsupported>;
85
+ }
@@ -0,0 +1,16 @@
1
+ /** @consumer Frozen fact provider and installed declaration consumer. */
2
+ export type { InvoiceFacts, InvoiceLine, InvoiceSeller, InvoiceBuyer } from "./facts.js";
3
+ /** @consumer A4 issue/correction bridge, adapters and operator proof readback. */
4
+ export type { InvoiceIdentity, InvoiceDocumentIdentity, InvoiceWriteResult, InvoiceReadbackResult, InvoiceProviderPort, InvoiceUnsupported, InvoiceDiagnosticCode, InvoiceProof } from "./provider.js";
5
+ /** @consumer Host artifact storage/download binding. */
6
+ export type { InvoiceArtifactResult, InvoiceClearanceObservation } from "./delivery.js";
7
+ /** @consumer Host payout item recorder and resolver. */
8
+ export type { InvoiceSettlementResult, InvoiceSettlementPort, InvoiceSettlementItem } from "./settlement.js";
9
+ /** @consumer Explicit host selection and readInvoiceCapabilities. */
10
+ export type { InvoiceCapabilities } from "./capabilities.js";
11
+ /** @consumer Injected registry adapter (A5). */
12
+ export type { InvoiceCompanyLookupPort } from "./companyLookup.js";
13
+ /** @consumer Managed/native persistence adapter and operator duty readback; no implementation supplied. */
14
+ export type { InvoiceStorePort, InvoiceDutyReadback } from "./store.js";
15
+ /** @consumer Host composition and offline port-fit witnesses. */
16
+ export type { InvoiceHostPorts, InvoiceServicesOptions } from "./host.js";
@@ -0,0 +1,78 @@
1
+ import type { InvoiceFacts } from "./facts.js";
2
+ /** Original host key bytes, immutable revision and exact lookup scope travel together.
3
+ * Carrier: providerPorts create options + approved exact-lookup envelope (fit probe).
4
+ */
5
+ export interface InvoiceIdentity {
6
+ readonly providerRef: string;
7
+ readonly requestKey: string;
8
+ /** Persisted create identity from claim, distinct from original host request key. */
9
+ readonly providerCreateIdentity: string;
10
+ readonly factRevision: string;
11
+ readonly orderRef: string;
12
+ readonly invoiceRef: string;
13
+ readonly operation: "issue" | "full_reversal" | "remote_void";
14
+ readonly correctionRef: string | null;
15
+ readonly parentProviderDocumentRef: string | null;
16
+ }
17
+ /** Document rows and donor delivery/history carriers need no issue-duty metadata.
18
+ * @consumer Host artifacts, clearance, delivery and authorized download adapters.
19
+ */
20
+ export interface InvoiceDocumentIdentity {
21
+ readonly providerRef: string;
22
+ readonly documentRef: string;
23
+ readonly providerDocumentRef: string | null;
24
+ readonly orderRef: string;
25
+ readonly invoiceRef: string;
26
+ readonly parentProviderDocumentRef: string | null;
27
+ }
28
+ /** A closed diagnostic allowlist in the neutral contract. Codes only.
29
+ * @consumer A4 bridge and provider/store adapters. */
30
+ export type InvoiceDiagnosticCode =
31
+ | "faulted" | "missing_facts" | "legacy_facts_unproved" | "retryable" | "blocked"
32
+ | "unsupported" | "unknown" | "absent" | "host_binding_required"
33
+ | "selection_required" | "disabled" | "identity_mismatch" | "parent_mismatch"
34
+ | "money_mismatch" | "money_unavailable" | "invalid_artifact" | "uncertain_delivery";
35
+ /** Missing binding or capability: nothing written.
36
+ * @consumer Host and provider adapters. */
37
+ export interface InvoiceUnsupported {
38
+ readonly kind: "unsupported";
39
+ readonly code: "host_binding_required" | "unsupported";
40
+ readonly retryable: false;
41
+ readonly effectMayHaveSucceeded: false;
42
+ }
43
+ /** Evidence references/fingerprints are adapter-filtered; never raw payloads or errors.
44
+ * @consumer Host recorder, operator readback and adapters. */
45
+ export interface InvoiceProof {
46
+ readonly evidenceRef: string;
47
+ readonly fingerprint: string;
48
+ readonly observedAt: string;
49
+ }
50
+ /** Refused proves a definite provider refusal with no effect; post-request adapter
51
+ * or transport faults are unknown, even when no acknowledgement was received.
52
+ */
53
+ export type InvoiceWriteResult =
54
+ | { readonly kind: "issued"; readonly identity: InvoiceIdentity; readonly providerDocumentRef: string; readonly providerDocumentNumber: string | null; readonly proof: InvoiceProof; readonly replayed: boolean }
55
+ | { readonly kind: "refused"; readonly identity: InvoiceIdentity; readonly code: Extract<InvoiceDiagnosticCode, "blocked" | "retryable" | "missing_facts" | "identity_mismatch" | "parent_mismatch" | "money_mismatch">; readonly retryable: boolean; readonly effectMayHaveSucceeded: false }
56
+ | { readonly kind: "unknown"; readonly identity: InvoiceIdentity; readonly code: "unknown"; readonly effectMayHaveSucceeded: true }
57
+ | InvoiceUnsupported;
58
+ /** Exact scope is the full identity, including operation, parent and revision.
59
+ * Incomplete/truncated/failed lookup is unknown. Only exact complete absence can
60
+ * authorize another create; found is proof, never a nullable lookup shortcut.
61
+ */
62
+ export type InvoiceReadbackResult =
63
+ | { readonly kind: "found"; readonly identity: InvoiceIdentity; readonly providerDocumentRef: string; readonly providerDocumentNumber: string | null; readonly proof: InvoiceProof }
64
+ | { readonly kind: "absent"; readonly identity: InvoiceIdentity; readonly evidence: InvoiceProof & { readonly exact: true; readonly complete: true; readonly scope: InvoiceIdentity } }
65
+ | { readonly kind: "unknown"; readonly identity: InvoiceIdentity; readonly code: "unknown" }
66
+ | InvoiceUnsupported;
67
+ /** Correction bridge: positive immutable BEFORE facts, explicit zero AFTER,
68
+ * stable correctionRef and parent proof. Retry requires exact recovery before I/O.
69
+ * Carrier: donor createFullCorrection options and accountingProviderSnapshot.
70
+ * @consumer A4 conforming correction bridge and issue/readback adapters.
71
+ */
72
+ export interface InvoiceProviderPort {
73
+ issue(input: { readonly identity: InvoiceIdentity & { readonly operation: "issue"; readonly correctionRef: null; readonly parentProviderDocumentRef: null }; readonly facts: InvoiceFacts; readonly recoveryLookupRequired: boolean }): Promise<InvoiceWriteResult>;
74
+ correct(input: { readonly identity: InvoiceIdentity & { readonly operation: "full_reversal"; readonly correctionRef: string; readonly parentProviderDocumentRef: string }; readonly before: InvoiceFacts; readonly after: { readonly totalNetMinor: 0; readonly totalTaxMinor: 0; readonly totalGrossMinor: 0 }; readonly reason: string; readonly recoveryLookupRequired: boolean }): Promise<InvoiceWriteResult>;
75
+ read(input: InvoiceIdentity): Promise<InvoiceReadbackResult>;
76
+ /** Remote void stays cut; always refuse before I/O, never substitute local void. */
77
+ void(input: InvoiceIdentity & { readonly operation: "remote_void" }): Promise<InvoiceUnsupported>;
78
+ }
@@ -0,0 +1,39 @@
1
+ import type { InvoiceProof, InvoiceUnsupported } from "./provider.js";
2
+ /** One immutable balance item, never unique by batch+payment alone.
3
+ * Carrier: accountingControlContracts settlement + payout balance transaction ID.
4
+ * Null links and bankReceivedAt are facts; settlement is not an invoice gate.
5
+ * @consumer Host payout item recorder.
6
+ */
7
+ export interface InvoiceSettlementItem {
8
+ readonly requestKey: string;
9
+ readonly providerRef: string;
10
+ readonly batchRef: string;
11
+ readonly itemRef: string;
12
+ readonly providerPaymentRef: string;
13
+ readonly paymentIntentRef: string | null;
14
+ readonly paymentRef: string | null;
15
+ readonly invoiceRef: string | null;
16
+ readonly grossMinor: number;
17
+ readonly feeMinor: number;
18
+ readonly netMinor: number;
19
+ readonly currency: string;
20
+ readonly status: "matched" | "unmatched" | "mismatch" | "bank_pending";
21
+ readonly bankReceivedAt: string | null;
22
+ readonly proof: InvoiceProof;
23
+ }
24
+ type ItemScope = Pick<InvoiceSettlementItem, "providerRef" | "batchRef" | "itemRef" | "providerPaymentRef">;
25
+ export type InvoiceSettlementResult =
26
+ | { readonly kind: "found"; readonly scope: ItemScope; readonly paymentIntentRef: string | null; readonly paymentRef: string | null; readonly invoiceRef: string | null; readonly proof: InvoiceProof }
27
+ | { readonly kind: "absent"; readonly scope: ItemScope; readonly evidence: InvoiceProof & { readonly exact: true; readonly complete: true; readonly scope: ItemScope } }
28
+ | { readonly kind: "recorded"; readonly itemRef: string; readonly settlementItemRef: string; readonly replayed: boolean }
29
+ | { readonly kind: "conflict"; readonly itemRef: string; readonly code: "identity_mismatch" | "money_mismatch" }
30
+ | { readonly kind: "unknown"; readonly itemRef: string; readonly code: "unknown" }
31
+ | InvoiceUnsupported;
32
+ /** Host recorder/resolver owns richer item identity. Unsupported before any write
33
+ * when a native batch/payment row cannot represent distinct items or nullable links.
34
+ * @consumer Host payout item recorder/resolver.
35
+ */
36
+ export interface InvoiceSettlementPort {
37
+ record(item: InvoiceSettlementItem): Promise<Exclude<InvoiceSettlementResult, { kind: "found" | "absent" }>>;
38
+ resolve(input: ItemScope): Promise<Exclude<InvoiceSettlementResult, { kind: "recorded" | "conflict" }>>;
39
+ }
@@ -0,0 +1,98 @@
1
+ import type { InvoiceHostPorts } from "./host.js";
2
+ import type { InvoiceFacts } from "./facts.js";
3
+ import type { InvoiceIdentity, InvoiceDocumentIdentity, InvoiceProof, InvoiceUnsupported, InvoiceWriteResult, InvoiceReadbackResult } from "./provider.js";
4
+ import type { InvoiceClearanceObservation, InvoiceArtifactResult, InvoiceDeliveryPort } from "./delivery.js";
5
+ type InvoiceDutyStatus = "owed" | "blocked" | "ready" | "processing" | "unknown" | "issued" | "voided" | "unsupported" | "faulted";
6
+ /** Native duty/lease fields map to the pinned invoicing_* fixtures. Managed hosts
7
+ * translate their outboxId/attemptCount fences; never claim transaction equality.
8
+ */
9
+ export interface InvoiceClaim {
10
+ readonly dutyId: string;
11
+ readonly documentId: string;
12
+ readonly requestId: string;
13
+ readonly token: string;
14
+ readonly generation: number;
15
+ readonly leaseUntil: string;
16
+ readonly identity: InvoiceIdentity;
17
+ readonly facts: InvoiceFacts;
18
+ readonly action: "create" | "readback";
19
+ readonly correction: { readonly before: InvoiceFacts; readonly reason: string; readonly after: { readonly totalNetMinor: 0; readonly totalTaxMinor: 0; readonly totalGrossMinor: 0 } } | null;
20
+ }
21
+ /** Exact camel-case shape returned by invoicing_duty_readback. This is not
22
+ * payment truth's accountingRequested; empty duties never assert invoice absence.
23
+ * @consumer Operator owed-duty readback.
24
+ */
25
+ export interface InvoiceDutyReadback {
26
+ readonly orderId: string;
27
+ readonly captureFaults: readonly { readonly sourceId: string; readonly state: "retryable" | "faulted" | "resolved"; readonly attempts: number; readonly availableAt: string }[];
28
+ readonly duties: readonly {
29
+ readonly dutyId: string;
30
+ readonly parentDutyId: string | null;
31
+ readonly documentId: string | null;
32
+ readonly state: "owed" | "blocked" | "claimed" | "unknown" | "issued" | "voided" | "unsupported" | "faulted";
33
+ readonly attempts: number;
34
+ readonly factAttempts: number;
35
+ readonly diagnosticCode: "faulted" | "missing_facts" | "legacy_facts_unproved" | "retryable" | "blocked" | "unsupported" | "unknown" | "absent" | null;
36
+ readonly createdAt: string;
37
+ readonly availableAt: string;
38
+ readonly leaseUntil: string | null;
39
+ }[];
40
+ }
41
+ /** Every operation is one local transaction; commit before external I/O. Native
42
+ * success atomically saves late identity and compensation; stale catch writes nothing.
43
+ * Managed and native stores are bound to the selected provider at construction.
44
+ * No implementation, executor or migration is installed by these declarations.
45
+ */
46
+ export interface InvoiceStorePort {
47
+ /** Never call inside a renewal money, dunning or dispatch transaction without
48
+ * isolation: capture failure must not propagate; the sweep recovers.
49
+ */
50
+ captureDuty(input: { readonly requestKey: string; readonly sourceKind: "paid" | "handoff"; readonly sourceId: string; readonly orderId: string; readonly occurredAt: string; readonly evidence: { readonly settlementIntentId: string; readonly amountMinor: number; readonly currency: string } | { readonly shipmentId: string; readonly handedOverAt: string } }): Promise<{ readonly dutyId: string; readonly status: InvoiceDutyStatus } | InvoiceUnsupported>;
51
+ installFacts(input: { readonly dutyId: string; readonly facts: InvoiceFacts }): Promise<{ readonly dutyId: string; readonly status: InvoiceDutyStatus; readonly replayed?: boolean } | InvoiceUnsupported>;
52
+ /** Pinned split facts lease: sweep and prepare commit separately; finishing
53
+ * requires the same token and authoritative document/fact match. No host I/O
54
+ * under the duty lock, and unsupported never silently drops an owed duty.
55
+ */
56
+ sweep(limit: number): Promise<{ readonly collected: number; readonly claims: readonly { readonly dutyId: string; readonly token: string }[] } | InvoiceUnsupported>;
57
+ prepareFacts(input: { readonly dutyId: string; readonly token: string }): Promise<{ readonly status: "owed" | "ready" | "issued" | "voided" | "unsupported" | "stale"; readonly documentId?: string; readonly requestId?: string; readonly code?: "retryable" | "legacy_facts_unproved" } | InvoiceUnsupported>;
58
+ finishFacts(input: { readonly dutyId: string; readonly token: string; readonly result: Omit<Exclude<Awaited<ReturnType<InvoiceStorePort["prepareFacts"]>>, InvoiceUnsupported>, "status"> & { readonly status: "owed" | "ready" | "issued" | "voided" | "unsupported" } }): Promise<{ readonly dutyId: string; readonly status: "owed" | "ready" | "issued" | "voided" | "unsupported" | "faulted" | "stale" } | InvoiceUnsupported>;
59
+ readDuties(orderId: string): Promise<InvoiceDutyReadback | InvoiceUnsupported>;
60
+ /** Filter order before locking/limit; never lease unrelated orders then filter.
61
+ * P8 reads the injected host seller before calling the first-claim SQL wrapper;
62
+ * its revisionRef supplies p_revision, without requiring a duty from the caller.
63
+ */
64
+ claim(input: { readonly limit: number; readonly visibilitySeconds: number; readonly providerRef: string; readonly orderId?: string | null }): Promise<readonly InvoiceClaim[] | InvoiceUnsupported>;
65
+ preflight(input: { readonly claim: InvoiceClaim; readonly amountMinor: number | null; readonly currency: string | null } & (
66
+ | { readonly status: "succeeded" | "failed" | "pending" | "unknown" | "unavailable"; readonly proof: InvoiceProof | null }
67
+ | { readonly status: "absent"; readonly evidence: Extract<Awaited<ReturnType<InvoiceHostPorts["money"]["read"]>>, { kind: "absent" }>["evidence"] }
68
+ )): Promise<{ readonly kind: "ready" | "blocked" | "mismatch" | "unavailable" | "stale" } | InvoiceUnsupported>;
69
+ finish(input: { readonly claim: InvoiceClaim; readonly result: Extract<InvoiceWriteResult, { kind: "issued" }> | Extract<InvoiceReadbackResult, { kind: "found" }> }): Promise<{ readonly kind: "issued"; readonly replayed: boolean } | { readonly kind: "stale" } | InvoiceUnsupported>;
70
+ /** Retryable requires a definite refusal (effectMayHaveSucceeded:false) or a
71
+ * pre-I/O failure and phase before_send. Every other failure maps to unknown.
72
+ * Native result kinds other than stale/voided map to recorded.
73
+ */
74
+ fail(input: { readonly claim: InvoiceClaim; readonly retrySeconds: number } & (
75
+ | { readonly kind: "absent"; readonly evidence: Extract<InvoiceReadbackResult, { kind: "absent" }> }
76
+ | { readonly kind: "retryable"; readonly phase: "before_send"; readonly proof: InvoiceProof | null }
77
+ | { readonly kind: "blocked" | "unsupported" | "unknown"; readonly proof: InvoiceProof | null }
78
+ )): Promise<{ readonly kind: "recorded" | "voided" | "stale" } | InvoiceUnsupported>;
79
+ /** Native post-write unsupported maps to unsupported_recorded, retaining duty/replay.
80
+ * Missing means no M09 duty, never invoice absence: retain/retry the reversal
81
+ * intent and route legacy documents to the incumbent path.
82
+ */
83
+ requestReversal(input: { readonly requestKey: string; readonly orderId: string; readonly reason: "order_canceled" | "order_refunded"; readonly proof: InvoiceProof }): Promise<{ readonly kind: "missing" | "voided" | "pending_readback" | "correction_requested"; readonly dutyId?: string; readonly replayed?: boolean } | { readonly kind: "unsupported_recorded"; readonly dutyId?: string; readonly replayed?: boolean } | InvoiceUnsupported>;
84
+ /** Existing local-only request remains distinct from fiscal issuance. */
85
+ requestLocalDocument(input: { readonly requestKey: string; readonly orderId: string; readonly providerRef: string }): Promise<{ readonly kind: "requested"; readonly documentId: string; readonly invoiceRef: string; readonly status: string; readonly replayed: boolean } | InvoiceUnsupported>;
86
+ listClearanceTargets(limit: number): Promise<readonly { readonly documentId: string; readonly identity: InvoiceDocumentIdentity; readonly providerDocumentRef: string; readonly providerDocumentNumber: string | null; readonly state: InvoiceClearanceObservation["state"] }[] | InvoiceUnsupported>;
87
+ /** Native maps clearance state unsupported to observation kind unsupported;
88
+ * provider_mismatch returns InvoiceUnsupported before recording anything.
89
+ */
90
+ recordObservation(input: { readonly requestKey: string; readonly documentId: string; readonly eventRef: string; readonly eventKind: "clearance" | "artifacts" | "unsupported" | "provider_mismatch"; readonly identity: InvoiceDocumentIdentity; readonly providerDocumentRef: string; readonly providerDocumentNumber: string | null; readonly clearance: InvoiceClearanceObservation | null; readonly artifacts: readonly Extract<InvoiceArtifactResult, { kind: "found" }>["artifact"][]; readonly observedAt: string; readonly payloadHash: string; readonly source: "provider_api" | "provider_webhook" | "manual_reconciliation" }): Promise<{ readonly replayed: boolean } | InvoiceUnsupported>;
91
+ /** Verify M04 binding before claiming; document rows need no M09 issue duty. */
92
+ claimDeliveries(input: { readonly limit: number; readonly visibilitySeconds: number; readonly requireClearance: boolean; readonly orderId?: string | null }): Promise<readonly { readonly token: string; readonly generation: number; readonly identity: InvoiceDocumentIdentity; readonly providerDocumentRef: string; readonly delivery: Omit<Parameters<InvoiceDeliveryPort["send"]>[0], "filename" | "content" | "contentType"> }[] | InvoiceUnsupported>;
93
+ /** Native uncertain settlement passes p_receipt NULL and retains a non-null
94
+ * receiptRef hint in p_evidence; managed uses it as the provider message id.
95
+ * Managed failed_before_send uses retrySeconds for backoff; native ignores it.
96
+ */
97
+ settleDelivery(input: { readonly deliveryRef: string; readonly token: string; readonly generation: number; readonly providerDocumentRef: string; readonly retrySeconds: number; readonly result: Exclude<Awaited<ReturnType<InvoiceDeliveryPort["send"]>>, InvoiceUnsupported> }): Promise<{ readonly kind: "recorded" | "stale"; readonly replayed: boolean } | InvoiceUnsupported>;
98
+ }
@@ -0,0 +1 @@
1
+ export { readInvoiceCapabilities } from "./capabilities.js";