@owlmeans/server-payment 0.1.21 → 0.2.0-alpha.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 (296) hide show
  1. package/README.md +52 -54
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/server-payment/SKILL.md +272 -330
  4. package/agent-meta/skills/server-payment/parts/reference.md +3 -3
  5. package/build/access/types.d.ts +7 -16
  6. package/build/access/types.d.ts.map +1 -1
  7. package/build/access.d.ts.map +1 -1
  8. package/build/access.js +6 -8
  9. package/build/access.js.map +1 -1
  10. package/build/actions/resync.d.ts +3 -3
  11. package/build/actions/resync.js +5 -5
  12. package/build/actions/resync.js.map +1 -1
  13. package/build/actions/webhook.d.ts +4 -1
  14. package/build/actions/webhook.d.ts.map +1 -1
  15. package/build/actions/webhook.js +8 -4
  16. package/build/actions/webhook.js.map +1 -1
  17. package/build/bootstrap/types.d.ts +13 -7
  18. package/build/bootstrap/types.d.ts.map +1 -1
  19. package/build/bootstrap.d.ts +4 -4
  20. package/build/bootstrap.d.ts.map +1 -1
  21. package/build/bootstrap.js +19 -10
  22. package/build/bootstrap.js.map +1 -1
  23. package/build/catalogue/types.d.ts +3 -3
  24. package/build/catalogue/types.d.ts.map +1 -1
  25. package/build/catalogue.d.ts.map +1 -1
  26. package/build/catalogue.js +4 -8
  27. package/build/catalogue.js.map +1 -1
  28. package/build/checkout/types.d.ts +21 -0
  29. package/build/checkout/types.d.ts.map +1 -0
  30. package/build/{plugins/stripe → checkout}/types.js.map +1 -1
  31. package/build/checkout.d.ts +6 -0
  32. package/build/checkout.d.ts.map +1 -0
  33. package/build/checkout.js +374 -0
  34. package/build/checkout.js.map +1 -0
  35. package/build/config.d.ts +10 -16
  36. package/build/config.d.ts.map +1 -1
  37. package/build/config.js +18 -59
  38. package/build/config.js.map +1 -1
  39. package/build/consts.d.ts +3 -49
  40. package/build/consts.d.ts.map +1 -1
  41. package/build/consts.js +3 -61
  42. package/build/consts.js.map +1 -1
  43. package/build/consumer/cancellation/types.d.ts +6 -4
  44. package/build/consumer/cancellation/types.d.ts.map +1 -1
  45. package/build/consumer/cancellation.d.ts.map +1 -1
  46. package/build/consumer/cancellation.js +11 -5
  47. package/build/consumer/cancellation.js.map +1 -1
  48. package/build/consumer/capture/types.d.ts +8 -12
  49. package/build/consumer/capture/types.d.ts.map +1 -1
  50. package/build/consumer/capture.d.ts.map +1 -1
  51. package/build/consumer/capture.js +48 -53
  52. package/build/consumer/capture.js.map +1 -1
  53. package/build/consumer/index.d.ts +4 -0
  54. package/build/consumer/index.d.ts.map +1 -1
  55. package/build/consumer/index.js +2 -0
  56. package/build/consumer/index.js.map +1 -1
  57. package/build/consumer/reconcile.d.ts.map +1 -1
  58. package/build/consumer/reconcile.js +82 -72
  59. package/build/consumer/reconcile.js.map +1 -1
  60. package/build/consumer/records/types.d.ts +4 -4
  61. package/build/consumer/records/types.d.ts.map +1 -1
  62. package/build/consumer/records.d.ts.map +1 -1
  63. package/build/consumer/records.js +16 -13
  64. package/build/consumer/records.js.map +1 -1
  65. package/build/consumer/service.d.ts +2 -2
  66. package/build/consumer/service.d.ts.map +1 -1
  67. package/build/consumer/service.js +28 -21
  68. package/build/consumer/service.js.map +1 -1
  69. package/build/consumer/types.d.ts +1 -4
  70. package/build/consumer/types.d.ts.map +1 -1
  71. package/build/consumer/types.local.d.ts +1 -9
  72. package/build/consumer/types.local.d.ts.map +1 -1
  73. package/build/consumer/withdrawal/types.d.ts +14 -12
  74. package/build/consumer/withdrawal/types.d.ts.map +1 -1
  75. package/build/consumer/withdrawal.d.ts.map +1 -1
  76. package/build/consumer/withdrawal.js +55 -71
  77. package/build/consumer/withdrawal.js.map +1 -1
  78. package/build/index.d.ts +12 -6
  79. package/build/index.d.ts.map +1 -1
  80. package/build/index.js +7 -4
  81. package/build/index.js.map +1 -1
  82. package/build/paygate/providers.d.ts +13 -0
  83. package/build/paygate/providers.d.ts.map +1 -0
  84. package/build/paygate/providers.js +38 -0
  85. package/build/paygate/providers.js.map +1 -0
  86. package/build/paygate/registry.d.ts +6 -0
  87. package/build/paygate/registry.d.ts.map +1 -0
  88. package/build/paygate/registry.js +37 -0
  89. package/build/paygate/registry.js.map +1 -0
  90. package/build/paygate/types.d.ts +577 -0
  91. package/build/paygate/types.d.ts.map +1 -0
  92. package/build/{plugins/session → paygate}/types.js.map +1 -1
  93. package/build/plan/types.d.ts +6 -1
  94. package/build/plan/types.d.ts.map +1 -1
  95. package/build/plan.d.ts.map +1 -1
  96. package/build/plan.js +16 -2
  97. package/build/plan.js.map +1 -1
  98. package/build/plugins/checkout-policy/types.d.ts +5 -3
  99. package/build/plugins/checkout-policy/types.d.ts.map +1 -1
  100. package/build/plugins/checkout-policy.d.ts.map +1 -1
  101. package/build/plugins/checkout-policy.js +5 -3
  102. package/build/plugins/checkout-policy.js.map +1 -1
  103. package/build/plugins/consts.local.d.ts +8 -10
  104. package/build/plugins/consts.local.d.ts.map +1 -1
  105. package/build/plugins/consts.local.js +2 -19
  106. package/build/plugins/consts.local.js.map +1 -1
  107. package/build/plugins/customer-lock/types.d.ts +2 -2
  108. package/build/plugins/customer-lock/types.d.ts.map +1 -1
  109. package/build/plugins/customer-lock.js +2 -2
  110. package/build/plugins/customer-lock.js.map +1 -1
  111. package/build/plugins/estimate/cache.js +1 -1
  112. package/build/plugins/estimate/cache.js.map +1 -1
  113. package/build/plugins/estimate/types.d.ts +10 -10
  114. package/build/plugins/estimate/types.d.ts.map +1 -1
  115. package/build/plugins/estimate.d.ts.map +1 -1
  116. package/build/plugins/estimate.js +48 -122
  117. package/build/plugins/estimate.js.map +1 -1
  118. package/build/plugins/events/types.d.ts +17 -10
  119. package/build/plugins/events/types.d.ts.map +1 -1
  120. package/build/plugins/events.d.ts +6 -5
  121. package/build/plugins/events.d.ts.map +1 -1
  122. package/build/plugins/events.js +162 -173
  123. package/build/plugins/events.js.map +1 -1
  124. package/build/plugins/fx/types.d.ts +10 -21
  125. package/build/plugins/fx/types.d.ts.map +1 -1
  126. package/build/plugins/fx.d.ts +1 -1
  127. package/build/plugins/fx.d.ts.map +1 -1
  128. package/build/plugins/fx.js +17 -54
  129. package/build/plugins/fx.js.map +1 -1
  130. package/build/plugins/portal/types.d.ts +8 -37
  131. package/build/plugins/portal/types.d.ts.map +1 -1
  132. package/build/plugins/portal.d.ts.map +1 -1
  133. package/build/plugins/portal.js +38 -208
  134. package/build/plugins/portal.js.map +1 -1
  135. package/build/plugins/refunds/types.d.ts +11 -11
  136. package/build/plugins/refunds/types.d.ts.map +1 -1
  137. package/build/plugins/refunds.d.ts.map +1 -1
  138. package/build/plugins/refunds.js +14 -39
  139. package/build/plugins/refunds.js.map +1 -1
  140. package/build/plugins/snapshot/types.d.ts +11 -0
  141. package/build/plugins/snapshot/types.d.ts.map +1 -0
  142. package/build/plugins/snapshot/types.js +2 -0
  143. package/build/plugins/snapshot/types.js.map +1 -0
  144. package/build/plugins/snapshot.d.ts +4 -0
  145. package/build/plugins/snapshot.d.ts.map +1 -0
  146. package/build/plugins/snapshot.js +19 -0
  147. package/build/plugins/snapshot.js.map +1 -0
  148. package/build/plugins/subscriptions/types.d.ts +17 -17
  149. package/build/plugins/subscriptions/types.d.ts.map +1 -1
  150. package/build/plugins/subscriptions.d.ts +4 -4
  151. package/build/plugins/subscriptions.d.ts.map +1 -1
  152. package/build/plugins/subscriptions.js +69 -77
  153. package/build/plugins/subscriptions.js.map +1 -1
  154. package/build/plugins/types.local.d.ts +9 -43
  155. package/build/plugins/types.local.d.ts.map +1 -1
  156. package/build/plugins/webhook-manager/types.d.ts +15 -43
  157. package/build/plugins/webhook-manager/types.d.ts.map +1 -1
  158. package/build/plugins/webhook-manager.d.ts +3 -3
  159. package/build/plugins/webhook-manager.d.ts.map +1 -1
  160. package/build/plugins/webhook-manager.js +21 -199
  161. package/build/plugins/webhook-manager.js.map +1 -1
  162. package/build/protocol.d.ts +1 -1
  163. package/build/protocol.d.ts.map +1 -1
  164. package/build/protocol.js +1 -1
  165. package/build/protocol.js.map +1 -1
  166. package/build/service.d.ts +11 -11
  167. package/build/service.d.ts.map +1 -1
  168. package/build/service.js +59 -23
  169. package/build/service.js.map +1 -1
  170. package/build/sync/types.d.ts +17 -13
  171. package/build/sync/types.d.ts.map +1 -1
  172. package/build/sync.d.ts.map +1 -1
  173. package/build/sync.js +22 -122
  174. package/build/sync.js.map +1 -1
  175. package/build/types.d.ts +46 -101
  176. package/build/types.d.ts.map +1 -1
  177. package/build/utils/types.d.ts +0 -8
  178. package/build/utils/types.d.ts.map +1 -1
  179. package/build/utils.d.ts +1 -4
  180. package/build/utils.d.ts.map +1 -1
  181. package/build/utils.js +1 -15
  182. package/build/utils.js.map +1 -1
  183. package/package.json +20 -22
  184. package/src/access/types.ts +7 -16
  185. package/src/access.ts +7 -15
  186. package/src/actions/resync.ts +5 -5
  187. package/src/actions/webhook.ts +8 -4
  188. package/src/bootstrap/types.ts +13 -7
  189. package/src/bootstrap.ts +23 -13
  190. package/src/catalogue/types.ts +3 -3
  191. package/src/catalogue.ts +4 -8
  192. package/src/checkout/types.ts +21 -0
  193. package/src/checkout.ts +414 -0
  194. package/src/config.ts +19 -66
  195. package/src/consts.ts +3 -69
  196. package/src/consumer/cancellation/types.ts +6 -4
  197. package/src/consumer/cancellation.ts +13 -7
  198. package/src/consumer/capture/types.ts +8 -12
  199. package/src/consumer/capture.ts +50 -59
  200. package/src/consumer/index.ts +4 -0
  201. package/src/consumer/reconcile.ts +69 -68
  202. package/src/consumer/records/types.ts +4 -4
  203. package/src/consumer/records.ts +19 -14
  204. package/src/consumer/service.ts +35 -22
  205. package/src/consumer/types.local.ts +1 -8
  206. package/src/consumer/types.ts +1 -4
  207. package/src/consumer/withdrawal/types.ts +14 -12
  208. package/src/consumer/withdrawal.ts +61 -77
  209. package/src/index.ts +12 -6
  210. package/src/paygate/providers.ts +48 -0
  211. package/src/paygate/registry.ts +53 -0
  212. package/src/paygate/types.ts +640 -0
  213. package/src/plan/types.ts +6 -1
  214. package/src/plan.ts +21 -3
  215. package/src/plugins/checkout-policy/types.ts +5 -3
  216. package/src/plugins/checkout-policy.ts +6 -5
  217. package/src/plugins/consts.local.ts +2 -26
  218. package/src/plugins/customer-lock/types.ts +2 -2
  219. package/src/plugins/customer-lock.ts +2 -2
  220. package/src/plugins/estimate/cache.ts +1 -1
  221. package/src/plugins/estimate/types.ts +10 -10
  222. package/src/plugins/estimate.ts +52 -128
  223. package/src/plugins/events/types.ts +17 -9
  224. package/src/plugins/events.ts +172 -190
  225. package/src/plugins/fx/types.ts +10 -23
  226. package/src/plugins/fx.ts +28 -64
  227. package/src/plugins/portal/types.ts +8 -38
  228. package/src/plugins/portal.ts +48 -229
  229. package/src/plugins/refunds/types.ts +11 -11
  230. package/src/plugins/refunds.ts +16 -40
  231. package/src/plugins/snapshot/types.ts +11 -0
  232. package/src/plugins/snapshot.ts +22 -0
  233. package/src/plugins/subscriptions/types.ts +17 -17
  234. package/src/plugins/subscriptions.ts +81 -81
  235. package/src/plugins/types.local.ts +9 -33
  236. package/src/plugins/webhook-manager/types.ts +15 -43
  237. package/src/plugins/webhook-manager.ts +24 -220
  238. package/src/protocol.ts +1 -1
  239. package/src/service.ts +66 -30
  240. package/src/sync/types.ts +17 -13
  241. package/src/sync.ts +25 -143
  242. package/src/types.ts +47 -97
  243. package/src/utils/types.ts +0 -9
  244. package/src/utils.ts +2 -20
  245. package/tests/capabilities.spec.ts +219 -0
  246. package/tests/entitlement.spec.ts +4 -4
  247. package/tests/gate-handlers.spec.ts +6 -6
  248. package/tests/gate.spec.ts +2 -2
  249. package/tests/grants.spec.ts +2 -2
  250. package/tests/internal-plan.spec.ts +2 -2
  251. package/tests/limit-gate.spec.ts +2 -2
  252. package/tests/paygates.spec.ts +132 -0
  253. package/tests/protocol.spec.ts +4 -5
  254. package/tests/usage.spec.ts +2 -2
  255. package/tests/webhook.spec.ts +137 -0
  256. package/build/plugins/session/types.d.ts +0 -34
  257. package/build/plugins/session/types.d.ts.map +0 -1
  258. package/build/plugins/session.d.ts +0 -4
  259. package/build/plugins/session.d.ts.map +0 -1
  260. package/build/plugins/session.js +0 -71
  261. package/build/plugins/session.js.map +0 -1
  262. package/build/plugins/status.d.ts +0 -8
  263. package/build/plugins/status.d.ts.map +0 -1
  264. package/build/plugins/status.js +0 -21
  265. package/build/plugins/status.js.map +0 -1
  266. package/build/plugins/stripe/types.d.ts +0 -20
  267. package/build/plugins/stripe/types.d.ts.map +0 -1
  268. package/build/plugins/stripe.d.ts +0 -6
  269. package/build/plugins/stripe.d.ts.map +0 -1
  270. package/build/plugins/stripe.js +0 -518
  271. package/build/plugins/stripe.js.map +0 -1
  272. package/src/plugins/session/types.ts +0 -30
  273. package/src/plugins/session.ts +0 -86
  274. package/src/plugins/status.ts +0 -22
  275. package/src/plugins/stripe/types.ts +0 -20
  276. package/src/plugins/stripe.ts +0 -571
  277. package/tests/checkout-consumer.spec.ts +0 -366
  278. package/tests/checkout-locks.spec.ts +0 -161
  279. package/tests/checkout-plugins.spec.ts +0 -164
  280. package/tests/checkout.spec.ts +0 -313
  281. package/tests/consumer-events.spec.ts +0 -215
  282. package/tests/consumer-fixtures.ts +0 -141
  283. package/tests/consumer-ops.spec.ts +0 -361
  284. package/tests/consumer-rights.integration.spec.ts +0 -147
  285. package/tests/consumer-rights.spec.ts +0 -606
  286. package/tests/context.ts +0 -110
  287. package/tests/estimate.spec.ts +0 -350
  288. package/tests/events.spec.ts +0 -367
  289. package/tests/fake-stripe.ts +0 -1004
  290. package/tests/gateway-options.spec.ts +0 -180
  291. package/tests/portal.spec.ts +0 -202
  292. package/tests/sync.spec.ts +0 -114
  293. package/tests/usage.integration.spec.ts +0 -165
  294. package/tests/webhook-manager.spec.ts +0 -149
  295. /package/build/{plugins/session → checkout}/types.js +0 -0
  296. /package/build/{plugins/stripe → paygate}/types.js +0 -0
package/src/consts.ts CHANGED
@@ -1,28 +1,8 @@
1
1
  import { INTERNAL_PAYGATE, LIMIT_GATE } from '@owlmeans/payment'
2
2
  export { INTERNAL_PAYGATE, LIMIT_GATE }
3
3
 
4
- export const STRIPE_PAYGATE_ALIAS = 'stripe'
5
- export const STRIPE_PLUGIN_CONFIG = '_external:stripe'
6
- export const STRIPE_PORTAL_PLUGIN_CONFIG = '_external:stripe-portal'
7
- /** Stripe-only pricing settings (FX Quotes API version, the unspecified-price migration switch) — never advertised to the browser, unlike the `PricingPolicy` record itself. */
8
- export const STRIPE_PRICING_PLUGIN_CONFIG = '_external:stripe-pricing'
9
- export const STRIPE_SIGNATURE = 'Stripe-Signature'
10
-
11
- /**
12
- * The FX Quotes API is a Stripe PREVIEW endpoint as of this writing: it answers only a
13
- * `Stripe-Version` header naming a preview version, never the SDK's pinned stable one. Verify this
14
- * string against https://docs.stripe.com/api/fx_quotes/create before relying on it, and override it
15
- * with `declarePaymentPricing({ stripe: { fxApiVersion } })` once Stripe moves the API or renames
16
- * the preview.
17
- */
18
- /**
19
- * The Stripe API version every client of this package is pinned to (the one stripe-node 17 defaulted to).
20
- * Moving it re-creates the stored webhook endpoints with their payload shapes, so it moves together with
21
- * the readers of `current_period_*`, an invoice's subscription and a credit note's refund.
22
- */
23
- export const STRIPE_PINNED_API_VERSION = '2025-02-24.acacia'
24
-
25
- export const STRIPE_FX_QUOTES_API_VERSION = '2025-07-30.preview'
4
+ /** The payment providers registered in a context (`ensurePaymentProviders`) — a lazy service. */
5
+ export const PAYMENT_PROVIDERS = 'payment-providers'
26
6
  export const GATEWAY_SERVICE = 'payment-gateway'
27
7
  export const PAYMENT_OBSERVER = 'payment-observer'
28
8
  export const ENTITLEMENT_SERVICE = 'payment-entitlement'
@@ -70,60 +50,14 @@ export const CONSUMER_RIGHTS_SERVICE = 'payment-consumer-rights'
70
50
  /** The consumer-rights mail options (trader, sender, archive copies) — never advertised. */
71
51
  export const CONSUMER_RIGHTS_MAIL_PLUGIN_CONFIG = '_external:payment-consumer-mail'
72
52
 
73
- /** Stripe's own bounds of a Checkout Session's `expires_at`, from now. */
74
- export const STRIPE_SESSION_TTL_MIN_SECONDS = 30 * 60
75
- export const STRIPE_SESSION_TTL_MAX_SECONDS = 24 * 60 * 60
76
-
77
- /** How far back `reconcile` looks for completed sessions that have no purchase row. */
53
+ /** How far back `reconcile` looks for completed checkouts that have no purchase row. */
78
54
  export const PURCHASE_BACKFILL_DAYS = 16
79
55
 
80
56
  /** Top-level domains that never receive mail (RFC 2606 / 6761) — e2e addresses are recorded as skipped. */
81
57
  export const RESERVED_MAIL_TLDS: readonly string[] = Object.freeze(['test', 'example', 'invalid', 'localhost'])
82
58
 
83
- /** The purchase id prefix of a Stripe purchase: `stripe:<session id>` or `stripe:<subscription id>`. */
84
- export const PURCHASE_ID_PREFIX = 'stripe'
85
-
86
59
  /**
87
60
  * The contract reference alphabet: digits and capitals without the look-alikes 0/O, 1/I/L, so a
88
61
  * reference read aloud or typed from paper is never ambiguous.
89
62
  */
90
63
  export const CONTRACT_REF_ALPHABET = '23456789ABCDEFGHJKMNPQRSTUVWXYZ'
91
-
92
- /** Fingerprint sku prefix of a portal configuration: `portal:<owner>` (the gateway's `owner`). */
93
- export const FINGERPRINT_PORTAL = 'portal'
94
-
95
- /**
96
- * The metadata every Stripe object this package creates carries (`{ owlmeans: 'payment', service }`,
97
- * `service` valued with the gateway's `owner`). It labels the object for an operator; several
98
- * deployments of one owner share it, so it never decides on its own that an object belongs to this
99
- * deployment.
100
- */
101
- export const STRIPE_OWNER_KEY = 'owlmeans'
102
- export const STRIPE_OWNER_VALUE = 'payment'
103
-
104
- /**
105
- * The metadata key naming the ONE deployment a portal configuration belongs to, valued with that
106
- * deployment's webhook URL (`webhookUrlOf`). Only an exact match lets a deployment adopt a
107
- * configuration it holds no fingerprint row for.
108
- */
109
- export const STRIPE_DEPLOYMENT_KEY = 'deployment'
110
-
111
- /**
112
- * Every Stripe event the managed webhook endpoint subscribes to.
113
- *
114
- * `invoice.upcoming` is enabled although nothing handles it (it carries no invoice id and nothing
115
- * is due), so an application can observe it without a Stripe dashboard change.
116
- */
117
- export const WEBHOOK_EVENTS: readonly string[] = Object.freeze([
118
- 'checkout.session.completed', 'checkout.session.async_payment_succeeded',
119
- 'checkout.session.async_payment_failed', 'checkout.session.expired',
120
- 'customer.created', 'customer.updated', 'customer.deleted',
121
- 'customer.subscription.created', 'customer.subscription.updated', 'customer.subscription.deleted',
122
- 'customer.subscription.paused', 'customer.subscription.resumed', 'customer.subscription.trial_will_end',
123
- 'customer.subscription.pending_update_applied', 'customer.subscription.pending_update_expired',
124
- 'invoice.paid', 'invoice.payment_failed', 'invoice.payment_action_required', 'invoice.upcoming',
125
- 'invoice.marked_uncollectible', 'invoice.voided',
126
- 'charge.refunded', 'refund.created', 'refund.updated', 'refund.failed',
127
- 'charge.dispute.created', 'charge.dispute.closed', 'charge.dispute.funds_withdrawn',
128
- 'charge.dispute.funds_reinstated',
129
- ])
@@ -1,13 +1,15 @@
1
- import type Stripe from 'stripe'
2
1
  import type { ConsumerDeclarationRecord, PaymentSubscriptionRecord } from '../../types.js'
2
+ import type { Paygate } from '../../paygate/types.js'
3
3
 
4
4
  /** The paygate step of a declared cancellation. */
5
5
  export interface CancellationHelper {
6
6
  /**
7
- * Schedule an ordinary cancellation at the paygate: at the period end (`cancel_at_period_end`), or
8
- * at a later boundary (`cancel_at`, no proration). Recorded as a `cancel-scheduled` event.
7
+ * Schedule an ordinary cancellation at the paygate (`subscriptions.scheduleCancel`): at the period
8
+ * end, or at a later boundary (no proration), under the idempotency key
9
+ * `cancellation:<id>:schedule[:<attempt>]`. Recorded as a `cancel-scheduled` event; a paygate
10
+ * without `subscriptions` records a failed one.
9
11
  */
10
12
  scheduleCancellation: (
11
- stripe: Stripe, declaration: ConsumerDeclarationRecord, row: PaymentSubscriptionRecord, attempt?: number,
13
+ paygate: Paygate, declaration: ConsumerDeclarationRecord, row: PaymentSubscriptionRecord, attempt?: number,
12
14
  ) => Promise<boolean>
13
15
  }
@@ -1,25 +1,31 @@
1
- import type Stripe from 'stripe'
1
+ import { PaygateError } from '@owlmeans/payment'
2
2
  import type { Context as ApiContext } from '@owlmeans/server-api'
3
3
  import { memoHelper } from '@owlmeans/context'
4
4
  import type { ConsumerDeclarationRecord, PaymentSubscriptionRecord } from '../types.js'
5
+ import type { Paygate } from '../paygate/types.js'
5
6
  import { paymentUtils } from '../utils.js'
6
7
  import { consumerRecordsOf } from './records.js'
7
8
  import type { CancellationHelper } from './cancellation/types.js'
8
9
 
9
10
  export const makeCancellationHelper = (ctx: ApiContext): CancellationHelper => {
10
11
  const scheduleCancellation = async (
11
- stripe: Stripe, declaration: ConsumerDeclarationRecord, row: PaymentSubscriptionRecord, attempt: number = 0,
12
+ paygate: Paygate, declaration: ConsumerDeclarationRecord, row: PaymentSubscriptionRecord, attempt: number = 0,
12
13
  ): Promise<boolean> => {
13
14
  const id = declaration.id as string
14
15
  const effectiveAt = declaration.effectiveAt != null ? new Date(declaration.effectiveAt) : null
15
16
  const atPeriodEnd = effectiveAt == null || row.periodEnd == null
16
17
  || effectiveAt.getTime() === new Date(row.periodEnd).getTime()
17
- const details = { comment: `cancellation:${id}` }
18
18
  try {
19
- await stripe.subscriptions.update(row.externalId, atPeriodEnd
20
- ? { cancel_at_period_end: true, cancellation_details: details }
21
- : { cancel_at: Math.floor((effectiveAt as Date).getTime() / 1000), proration_behavior: 'none', cancellation_details: details },
22
- { idempotencyKey: attempt > 0 ? `cancellation:${id}:schedule:${attempt}` : `cancellation:${id}:schedule` })
19
+ if (paygate.subscriptions == null) {
20
+ throw new PaygateError(`capability:subscriptions:${paygate.id}`)
21
+ }
22
+ await paygate.subscriptions.scheduleCancel(row.externalId, atPeriodEnd
23
+ ? { atPeriodEnd: true }
24
+ : { atPeriodEnd: false, at: effectiveAt as Date },
25
+ {
26
+ idempotencyKey: attempt > 0 ? `cancellation:${id}:schedule:${attempt}` : `cancellation:${id}:schedule`,
27
+ comment: `cancellation:${id}`,
28
+ })
23
29
  await consumerRecordsOf(ctx).recordEvent({
24
30
  recordId: id, recordKind: 'declaration', entityId: row.entityId, action: 'cancel-scheduled', ok: true,
25
31
  externalId: row.externalId, detail: JSON.stringify({ atPeriodEnd, effectiveAt: effectiveAt?.toISOString() }),
@@ -1,6 +1,6 @@
1
- import type Stripe from 'stripe'
2
1
  import type { PaymentSubscriptionRecord, PurchaseRecord } from '../../types.js'
3
2
  import type { CapturedPurchase, InvoiceEvidence, SessionEvidence } from '../types.js'
3
+ import type { CheckoutSnapshot, Paygate, PaygateSubscription } from '../../paygate/types.js'
4
4
 
5
5
  /** What a one-time checkout or a subscription's first invoice extra-records of its purchase. */
6
6
  export interface CapturedPaymentExtra {
@@ -13,17 +13,13 @@ export interface CapturedPaymentExtra {
13
13
 
14
14
  /** Paid checkouts and first invoices of a context, captured as purchases. */
15
15
  export interface CaptureHelper {
16
- /**
17
- * The buyer and totals of a Checkout Session. `presentment_details` (Adaptive Pricing) is not typed
18
- * by the pinned SDK, hence the narrow accessor.
19
- */
20
- sessionEvidenceOf: (session: Stripe.Checkout.Session) => SessionEvidence
16
+ /** The buyer and totals of a checkout session (the local-currency presentment, the terms acceptance). */
17
+ sessionEvidenceOf: (session: CheckoutSnapshot) => SessionEvidence
21
18
  /**
22
19
  * An invoice's evidence, best effort: an unreachable invoice is logged and yields nothing — the
23
- * withdrawal reads it again when it needs it. `invoice.payment_intent` is top-level on the pinned
24
- * API version.
20
+ * withdrawal reads it again when it needs it. A paygate without `payments` yields nothing.
25
21
  */
26
- invoiceEvidenceOf: (stripe: Stripe | null | undefined, invoiceId: string | undefined) => Promise<InvoiceEvidence>
22
+ invoiceEvidenceOf: (paygate: Paygate | null | undefined, invoiceId: string | undefined) => Promise<InvoiceEvidence>
27
23
  /**
28
24
  * A completed, paid ONE-TIME checkout as a purchase — the window and the contract registry. Runs
29
25
  * BEFORE the credits are granted: the billing country is locked first (first write wins; another
@@ -31,7 +27,7 @@ export interface CaptureHelper {
31
27
  * mailed. `null` when no consumer-rights policy is declared.
32
28
  */
33
29
  capturePaymentPurchase: (
34
- stripe: Stripe | null, session: Stripe.Checkout.Session, extra?: CapturedPaymentExtra, opts?: { mail?: boolean },
30
+ paygate: Paygate, session: CheckoutSnapshot, extra?: CapturedPaymentExtra, opts?: { mail?: boolean },
35
31
  ) => Promise<CapturedPurchase | null>
36
32
  /**
37
33
  * A subscription's FIRST invoice as a purchase — called while the subscription is committed, BEFORE
@@ -40,7 +36,7 @@ export interface CaptureHelper {
40
36
  * metadata names one) is the purchase's consent: `servicesStartedAt` and `consentedAt`.
41
37
  */
42
38
  captureSubscriptionPurchase: (
43
- stripe: Stripe | null, subscription: Stripe.Subscription, row: PaymentSubscriptionRecord,
39
+ paygate: Paygate, subscription: PaygateSubscription, row: PaymentSubscriptionRecord,
44
40
  ) => Promise<CapturedPurchase | null>
45
41
  /**
46
42
  * Refine a subscription purchase with its completed checkout: the buyer's own country (and so the
@@ -48,6 +44,6 @@ export interface CaptureHelper {
48
44
  * the billing country; mail the confirmation once.
49
45
  */
50
46
  completeSubscriptionPurchase: (
51
- stripe: Stripe | null, session: Stripe.Checkout.Session, purchase: PurchaseRecord, opts?: { mail?: boolean },
47
+ paygate: Paygate, session: CheckoutSnapshot, purchase: PurchaseRecord, opts?: { mail?: boolean },
52
48
  ) => Promise<PurchaseRecord>
53
49
  }
@@ -1,8 +1,7 @@
1
- import type Stripe from 'stripe'
2
1
  import { ConsentKind, CONSUMER_RIGHTS_COPY_VERSION, PurchaseKind, type ConsumerRightsPolicy, consumerRegionHelper, withdrawalDeadlineHelper } from '@owlmeans/payment'
3
2
  import type { Context as ApiContext } from '@owlmeans/server-api'
4
3
  import { memoHelper } from '@owlmeans/context'
5
- import { STRIPE_PAYGATE_ALIAS } from '../consts.js'
4
+ import type { CheckoutSnapshot, Paygate, PaygateSubscription } from '../paygate/types.js'
6
5
  import type { PurchaseDraft, CapturedPurchase, InvoiceEvidence, SessionEvidence } from './types.js'
7
6
  import type {
8
7
  BillingProfileRecord, PaymentSubscriptionRecord, PurchaseRecord, ConsumerConsentRecord,
@@ -21,65 +20,58 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
21
20
  const access = paymentAccessOf(ctx)
22
21
  const records = consumerRecordsOf(ctx)
23
22
 
24
- const sessionEvidenceOf = (session: Stripe.Checkout.Session): SessionEvidence => {
25
- const details = session.customer_details
26
- const presentment = (session as unknown as {
27
- presentment_details?: { presentment_amount?: number, presentment_currency?: string } | null
28
- }).presentment_details
29
- const subtotal = session.amount_subtotal ?? 0
30
- const tax = session.total_details?.amount_tax ?? 0
23
+ const sessionEvidenceOf = (session: CheckoutSnapshot): SessionEvidence => {
24
+ const subtotal = session.amountSubtotalMinor ?? 0
25
+ const tax = session.amountTaxMinor ?? 0
31
26
 
32
27
  return paymentUtils.compact({
33
- country: details?.address?.country?.toUpperCase() ?? undefined,
34
- email: details?.email ?? undefined,
35
- name: details?.name ?? undefined,
36
- business: (details?.tax_ids?.length ?? 0) > 0 || details?.tax_exempt === 'reverse' ? true : undefined,
28
+ country: session.buyer.country?.toUpperCase() ?? undefined,
29
+ email: session.buyer.email ?? undefined,
30
+ name: session.buyer.name ?? undefined,
31
+ business: session.buyer.business === true ? true : undefined,
37
32
  currency: (session.currency ?? '').toLowerCase(),
38
33
  subtotalMinor: subtotal,
39
34
  taxMinor: tax,
40
- totalMinor: session.amount_total ?? subtotal + tax,
41
- presentmentCurrency: presentment?.presentment_currency?.toLowerCase(),
42
- presentmentAmountMinor: presentment?.presentment_amount,
43
- termsAccepted: session.consent?.terms_of_service === 'accepted' ? true
44
- : session.consent?.terms_of_service != null ? false : undefined,
35
+ totalMinor: session.amountTotalMinor ?? subtotal + tax,
36
+ presentmentCurrency: session.presentment?.currency?.toLowerCase(),
37
+ presentmentAmountMinor: session.presentment?.amountMinor,
38
+ termsAccepted: session.termsAccepted,
45
39
  }) as SessionEvidence
46
40
  }
47
41
 
48
- const invoiceEvidenceOf = async (
49
- stripe: Stripe | null | undefined, invoiceId: string | undefined,
50
- ): Promise<InvoiceEvidence> => {
51
- if (stripe == null || invoiceId == null) {
42
+ const invoiceEvidenceOf = async (paygate: Paygate | null | undefined, invoiceId: string | undefined): Promise<InvoiceEvidence> => {
43
+ if (paygate?.payments == null || invoiceId == null) {
52
44
  return {}
53
45
  }
54
46
  try {
55
- const invoice = await stripe.invoices.retrieve(invoiceId)
56
- const typed = invoice as unknown as { payment_intent?: string | { id?: string } | null, tax?: number | null }
47
+ const invoice = await paygate.payments.invoice(invoiceId)
48
+ if (invoice == null) {
49
+ return {}
50
+ }
57
51
 
58
52
  return paymentUtils.compact({
59
53
  invoiceNumber: invoice.number ?? undefined,
60
- invoiceLineId: invoice.lines?.data?.[0]?.id,
61
- paymentIntentId: paymentUtils.idOf(typed.payment_intent),
62
- country: invoice.customer_address?.country?.toUpperCase() ?? undefined,
63
- subtotalMinor: invoice.subtotal ?? undefined,
64
- taxMinor: typed.tax ?? undefined,
65
- totalMinor: invoice.total ?? undefined,
54
+ invoiceLineId: invoice.firstLineId,
55
+ paymentIntentId: invoice.paymentId,
56
+ country: invoice.country?.toUpperCase() ?? undefined,
57
+ subtotalMinor: invoice.subtotalMinor ?? undefined,
58
+ taxMinor: invoice.taxMinor ?? undefined,
59
+ totalMinor: invoice.totalMinor ?? undefined,
66
60
  currency: invoice.currency ?? undefined,
67
61
  }) as InvoiceEvidence
68
62
  } catch (error) {
69
- if (!paymentUtils.isMissingObject(error)) {
70
- log.warn('Invoice unreadable for its purchase', { invoiceId, error })
71
- }
63
+ log.warn('Invoice unreadable for its purchase', { invoiceId, error })
72
64
  return {}
73
65
  }
74
66
  }
75
67
 
76
68
  /**
77
69
  * Lock the entity's billing country from a completed checkout, when the policy locks countries: the
78
- * buyer's address at Stripe, else the declared country — the pinned one first when the session held
79
- * it (`countryPinned`: tax was calculated on it, the card form's country moved nothing).
70
+ * buyer's address at the paygate, else the declared country — the pinned one first when the session
71
+ * held it (`countryPinned`: tax was calculated on it, the card form's country moved nothing).
80
72
  */
81
73
  const lockFromSession = async (
82
- policy: ConsumerRightsPolicy, entityId: string, session: Stripe.Checkout.Session,
74
+ paygate: Paygate, policy: ConsumerRightsPolicy, entityId: string, session: CheckoutSnapshot,
83
75
  evidence: SessionEvidence,
84
76
  ): Promise<BillingProfileRecord | null> => {
85
77
  const metadata = session.metadata ?? {}
@@ -90,7 +82,7 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
90
82
  return null
91
83
  }
92
84
  const { record } = await records.lockProfile(policy, {
93
- entityId, country, source: 'checkout', customerId: paymentUtils.idOf(session.customer), sessionId: session.id,
85
+ entityId, country, source: 'checkout', paygate: paygate.id, customerId: session.customerId, sessionId: session.id,
94
86
  ipCountry: metadata.ipCountry, email: evidence.email, name: evidence.name, business: evidence.business,
95
87
  currency: evidence.currency, language: metadata.language,
96
88
  })
@@ -121,7 +113,7 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
121
113
  }
122
114
 
123
115
  const capturePaymentPurchase = async (
124
- stripe: Stripe | null, session: Stripe.Checkout.Session, extra: CapturedPaymentExtra = {}, opts: { mail?: boolean } = {},
116
+ paygate: Paygate, session: CheckoutSnapshot, extra: CapturedPaymentExtra = {}, opts: { mail?: boolean } = {},
125
117
  ): Promise<CapturedPurchase | null> => {
126
118
  const policy = await access.payment().consumerRightsPolicy()
127
119
  if (policy == null) {
@@ -133,8 +125,8 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
133
125
  return null
134
126
  }
135
127
  const evidence = sessionEvidenceOf(session)
136
- const profile = await lockFromSession(policy, entityId, session, evidence)
137
- const existing = await access.purchases().byPurchaseId(records.purchaseIdOf(session.id))
128
+ const profile = await lockFromSession(paygate, policy, entityId, session, evidence)
129
+ const existing = await access.purchases().byPurchaseId(records.purchaseIdOf(paygate.id, session.id))
138
130
  if (existing != null) {
139
131
  if (opts.mail !== false) await confirmPurchase(policy, existing)
140
132
  return { purchase: existing, created: false }
@@ -144,16 +136,16 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
144
136
  const region = consumerRegionHelper.regionOf(country, policy)
145
137
  // Protected when either the buyer's own address or the organization's locked country is in scope.
146
138
  const scoped = consumerRegionHelper.inScope(region, country, policy) || (profile != null && consumerRegionHelper.inScope(profile.region, profile.country, policy))
147
- const invoice = await invoiceEvidenceOf(stripe, paymentUtils.idOf(session.invoice))
139
+ const invoice = await invoiceEvidenceOf(paygate, session.invoiceId)
148
140
  const purchasedAt = extra.at ?? new Date()
149
141
  const draft = paymentUtils.compact({
150
- purchaseId: records.purchaseIdOf(session.id),
142
+ purchaseId: records.purchaseIdOf(paygate.id, session.id),
151
143
  entityId,
152
144
  kind: PurchaseKind.TopUp,
153
- paygate: STRIPE_PAYGATE_ALIAS,
145
+ paygate: paygate.id,
154
146
  sessionId: session.id,
155
- paymentIntentId: paymentUtils.idOf(session.payment_intent) ?? invoice.paymentIntentId,
156
- invoiceId: paymentUtils.idOf(session.invoice),
147
+ paymentIntentId: session.paymentId ?? invoice.paymentIntentId,
148
+ invoiceId: session.invoiceId,
157
149
  invoiceNumber: invoice.invoiceNumber,
158
150
  invoiceLineId: invoice.invoiceLineId,
159
151
  productSku: metadata.productSku,
@@ -201,34 +193,33 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
201
193
  }
202
194
 
203
195
  const captureSubscriptionPurchase = async (
204
- stripe: Stripe | null, subscription: Stripe.Subscription, row: PaymentSubscriptionRecord,
196
+ paygate: Paygate, subscription: PaygateSubscription, row: PaymentSubscriptionRecord,
205
197
  ): Promise<CapturedPurchase | null> => {
206
198
  const policy = await access.payment().consumerRightsPolicy()
207
199
  if (policy == null) {
208
200
  return null
209
201
  }
210
- const purchaseId = records.purchaseIdOf(subscription.id)
202
+ const purchaseId = records.purchaseIdOf(paygate.id, subscription.id)
211
203
  const existing = await access.purchases().byPurchaseId(purchaseId)
212
204
  if (existing != null) {
213
205
  return { purchase: existing, created: false }
214
206
  }
215
207
  const metadata = subscription.metadata ?? {}
216
- const item = subscription.items?.data?.[0]
217
- const invoiceId = paymentUtils.idOf(subscription.latest_invoice)
218
- const invoice = await invoiceEvidenceOf(stripe, invoiceId)
208
+ const invoiceId = subscription.latestInvoiceId
209
+ const invoice = await invoiceEvidenceOf(paygate, invoiceId)
219
210
  const profile = await access.billingProfiles().byEntity(row.entityId)
220
211
  const country = invoice.country ?? profile?.country ?? metadata.country
221
212
  const region = consumerRegionHelper.regionOf(country, policy)
222
213
  const scoped = consumerRegionHelper.inScope(region, country, policy) || (profile != null && consumerRegionHelper.inScope(profile.region, profile.country, policy))
223
214
  const start = await startRequestOf(row.entityId, metadata.startRequestId)
224
- const subtotal = invoice.subtotalMinor ?? (item?.price?.unit_amount ?? 0) * (item?.quantity ?? 1)
215
+ const subtotal = invoice.subtotalMinor ?? (subscription.unitAmountMinor ?? 0) * (subscription.quantity ?? 1)
225
216
  const tax = invoice.taxMinor ?? 0
226
- const purchasedAt = paymentUtils.dateOf(subscription.created) ?? new Date()
217
+ const purchasedAt = subscription.createdAt ?? new Date()
227
218
  const draft = paymentUtils.compact({
228
219
  purchaseId,
229
220
  entityId: row.entityId,
230
221
  kind: PurchaseKind.Subscription,
231
- paygate: STRIPE_PAYGATE_ALIAS,
222
+ paygate: paygate.id,
232
223
  subscriptionId: subscription.id,
233
224
  paymentIntentId: invoice.paymentIntentId,
234
225
  invoiceId,
@@ -242,11 +233,11 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
242
233
  ipCountry: metadata.ipCountry,
243
234
  inScope: scoped,
244
235
  language: profile?.language ?? metadata.language ?? consumerRegionHelper.billingLanguageOf(country, policy),
245
- currency: (invoice.currency ?? subscription.currency ?? item?.price?.currency ?? 'usd').toLowerCase(),
236
+ currency: (invoice.currency ?? subscription.currency ?? subscription.priceCurrency ?? 'usd').toLowerCase(),
246
237
  amountSubtotalMinor: subtotal,
247
238
  amountTaxMinor: tax,
248
239
  amountTotalMinor: invoice.totalMinor ?? subtotal + tax,
249
- taxBehavior: item?.price?.tax_behavior ?? undefined,
240
+ taxBehavior: subscription.taxBehavior ?? undefined,
250
241
  textVersion: metadata.termsVersion ?? policy.textVersion,
251
242
  copyVersion: metadata.copyVersion ?? CONSUMER_RIGHTS_COPY_VERSION,
252
243
  startRequestId: start?.id,
@@ -262,7 +253,7 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
262
253
  }
263
254
 
264
255
  const completeSubscriptionPurchase = async (
265
- stripe: Stripe | null, session: Stripe.Checkout.Session, purchase: PurchaseRecord,
256
+ paygate: Paygate, session: CheckoutSnapshot, purchase: PurchaseRecord,
266
257
  opts: { mail?: boolean } = {},
267
258
  ): Promise<PurchaseRecord> => {
268
259
  const policy = await access.payment().consumerRightsPolicy()
@@ -270,16 +261,16 @@ export const makeCaptureHelper = (ctx: ApiContext): CaptureHelper => {
270
261
  return purchase
271
262
  }
272
263
  const evidence = sessionEvidenceOf(session)
273
- const profile = await lockFromSession(policy, purchase.entityId, session, evidence)
264
+ const profile = await lockFromSession(paygate, policy, purchase.entityId, session, evidence)
274
265
  const country = evidence.country ?? purchase.country ?? profile?.country
275
266
  const region = consumerRegionHelper.regionOf(country, policy)
276
267
  const scoped = consumerRegionHelper.inScope(region, country, policy) || (profile != null && consumerRegionHelper.inScope(profile.region, profile.country, policy))
277
268
  const invoice = purchase.invoiceLineId == null || purchase.paymentIntentId == null
278
- ? await invoiceEvidenceOf(stripe, purchase.invoiceId ?? paymentUtils.idOf(session.invoice)) : {}
269
+ ? await invoiceEvidenceOf(paygate, purchase.invoiceId ?? session.invoiceId) : {}
279
270
  const purchasedAt = new Date(purchase.purchasedAt)
280
271
  const fields = paymentUtils.compact({
281
272
  sessionId: session.id,
282
- invoiceId: purchase.invoiceId ?? paymentUtils.idOf(session.invoice),
273
+ invoiceId: purchase.invoiceId ?? session.invoiceId,
283
274
  invoiceNumber: purchase.invoiceNumber ?? invoice.invoiceNumber,
284
275
  invoiceLineId: purchase.invoiceLineId ?? invoice.invoiceLineId,
285
276
  paymentIntentId: purchase.paymentIntentId ?? invoice.paymentIntentId,
@@ -7,3 +7,7 @@ export type * from './origin/types.js'
7
7
  export * from './origin.js'
8
8
  export type * from './mail/types.js'
9
9
  export * from './mail.js'
10
+ export type * from './records/types.js'
11
+ export { consumerRecordsOf, makeConsumerRecords } from './records.js'
12
+ export type * from './capture/types.js'
13
+ export { captureOf, makeCaptureHelper } from './capture.js'